From bf04235dae35452061cc7ea3d86d96c19a58206c Mon Sep 17 00:00:00 2001 From: restrry Date: Fri, 22 May 2020 09:08:58 +0200 Subject: [PATCH] apply prettier styles --- .eslintrc.js | 2 +- Gruntfile.js | 2 +- .../public/alert_types/always_firing.tsx | 2 +- .../public/alert_types/astros.tsx | 10 +- .../server/alert_types/astros.ts | 5 +- .../public/components/count_until/index.tsx | 2 +- .../components/double_integers/index.tsx | 10 +- .../public/containers/app/index.tsx | 2 +- .../public/containers/app/sidebar/index.tsx | 2 +- examples/bfetch_explorer/server/plugin.ts | 2 +- .../server/async_demo_search_strategy.ts | 4 +- .../server/demo_search_strategy.ts | 2 +- .../list_container_component.tsx | 2 +- .../multi_task_todo_component.tsx | 2 +- .../multi_task_todo_embeddable.tsx | 2 +- .../searchable_list_container_component.tsx | 24 +- .../public/todo/todo_embeddable_factory.tsx | 4 +- examples/embeddable_explorer/public/app.tsx | 4 +- .../public/embeddable_panel_example.tsx | 2 +- .../public/todo_embeddable_example.tsx | 8 +- .../search_explorer/public/application.tsx | 4 +- .../public/async_demo_strategy.tsx | 2 +- .../search_explorer/public/demo_strategy.tsx | 4 +- examples/search_explorer/public/do_search.tsx | 4 +- .../search_explorer/public/es_strategy.tsx | 4 +- .../search_explorer/public/guide_section.tsx | 6 +- .../public/todo/todo.tsx | 18 +- .../with_data_services/components/app.tsx | 4 +- .../public/actions/actions.tsx | 8 +- examples/ui_actions_explorer/public/app.tsx | 2 +- .../public/trigger_context_example.tsx | 2 +- .../url_generators_examples/public/app.tsx | 2 +- .../public/url_generator.ts | 4 +- .../url_generators_explorer/public/app.tsx | 8 +- packages/elastic-datemath/__tests__/index.js | 145 +- packages/elastic-datemath/src/index.js | 4 +- packages/kbn-analytics/scripts/build.js | 4 +- packages/kbn-analytics/src/report.ts | 2 +- packages/kbn-analytics/src/reporter.ts | 2 +- .../kbn-babel-code-parser/src/code_parser.js | 2 +- .../kbn-babel-code-parser/src/strategies.js | 2 +- .../src/strategies.test.js | 2 +- .../kbn-babel-code-parser/src/visitors.js | 10 +- .../src/visitors.test.js | 2 +- .../src/errors/schema_error.test.ts | 4 +- .../src/errors/validation_error.ts | 4 +- .../kbn-config-schema/src/internals/index.ts | 4 +- .../src/typeguards/is_config_schema.test.ts | 2 +- .../kbn-config-schema/src/types/array_type.ts | 5 +- .../src/types/string_type.ts | 6 +- .../kbn-config-schema/src/types/union_type.ts | 2 +- .../ci_stats_reporter/ci_stats_reporter.ts | 2 +- .../src/kbn_client/kbn_client_requester.ts | 2 +- .../src/proc_runner/observe_readable.ts | 2 +- .../kbn-dev-utils/src/proc_runner/proc.ts | 4 +- .../src/proc_runner/proc_runner.ts | 18 +- .../src/proc_runner/with_proc_runner.test.ts | 14 +- packages/kbn-dev-utils/src/run/fail.ts | 2 +- packages/kbn-dev-utils/src/run/run.ts | 4 +- .../src/tooling_log/tooling_log.test.ts | 51 +- .../tooling_log_collecting_writer.ts | 2 +- packages/kbn-es/src/artifact.js | 4 +- packages/kbn-es/src/artifact.test.js | 6 +- packages/kbn-es/src/cli.js | 2 +- packages/kbn-es/src/cluster.js | 22 +- packages/kbn-es/src/errors.js | 4 +- packages/kbn-es/src/install/source.js | 8 +- .../integration_tests/__fixtures__/es_bin.js | 2 +- .../src/integration_tests/cluster.test.js | 10 +- packages/kbn-es/src/settings.ts | 2 +- packages/kbn-es/src/utils/build_snapshot.js | 8 +- packages/kbn-es/src/utils/decompress.js | 11 +- .../kbn-es/src/utils/extract_config_files.js | 2 +- .../src/utils/find_most_recently_changed.js | 2 +- .../utils/find_most_recently_changed.test.js | 2 +- packages/kbn-es/src/utils/native_realm.js | 6 +- .../lib/get_is_path_request.js | 2 +- .../lib/get_kibana_path.js | 2 +- .../lib/get_path_type.js | 4 +- .../lib/get_plugins.js | 12 +- .../lib/get_project_root.js | 2 +- .../lib/get_webpack_config.js | 4 +- .../lib/is_probably_webpack_shim.js | 8 +- .../lib/resolve_webpack_alias.js | 2 +- packages/kbn-eslint-plugin-eslint/lib.js | 2 +- .../rules/disallow_license_headers.js | 6 +- .../rules/module_migration.js | 4 +- .../rules/require_license_header.js | 6 +- packages/kbn-i18n/scripts/build.js | 4 +- packages/kbn-i18n/src/angular/filter.test.ts | 7 +- packages/kbn-i18n/src/loader.ts | 2 +- .../src/react/pseudo_locale_wrapper.tsx | 2 +- .../kbn-interpreter/src/common/lib/arg.js | 2 +- .../kbn-interpreter/src/common/lib/ast.js | 4 +- packages/kbn-interpreter/src/common/lib/fn.js | 2 +- .../src/common/lib/get_by_alias.js | 2 +- .../src/common/lib/registry.js | 2 +- .../kbn-interpreter/src/common/registries.js | 6 +- packages/kbn-interpreter/tasks/build/cli.js | 4 +- packages/kbn-optimizer/src/cli.ts | 4 +- .../src/common/array_helpers.test.ts | 12 +- packages/kbn-optimizer/src/common/bundle.ts | 2 +- .../disallowed_syntax.ts | 4 +- .../disallowed_syntax_plugin.ts | 8 +- .../src/common/event_stream_helpers.test.ts | 2 +- .../src/common/event_stream_helpers.ts | 4 +- .../src/common/parse_path.test.ts | 4 +- .../src/common/rxjs_helpers.test.ts | 10 +- .../kbn-optimizer/src/common/rxjs_helpers.ts | 4 +- .../basic_optimization.test.ts | 28 +- .../integration_tests/bundle_cache.test.ts | 2 +- .../watch_bundles_for_changes.test.ts | 4 +- .../kbn-optimizer/src/log_optimizer_state.ts | 2 +- .../assign_bundles_to_workers.test.ts | 2 +- .../optimizer/assign_bundles_to_workers.ts | 14 +- .../src/optimizer/cache_keys.test.ts | 2 +- .../kbn-optimizer/src/optimizer/cache_keys.ts | 2 +- .../kbn-optimizer/src/optimizer/get_mtimes.ts | 6 +- .../src/optimizer/get_plugin_bundles.test.ts | 2 +- .../src/optimizer/get_plugin_bundles.ts | 4 +- .../optimizer/handle_optimizer_completion.ts | 2 +- .../src/optimizer/kibana_platform_plugins.ts | 6 +- .../src/optimizer/observe_worker.ts | 12 +- .../src/optimizer/optimizer_config.ts | 4 +- .../src/optimizer/optimizer_state.ts | 6 +- .../src/optimizer/run_workers.ts | 8 +- .../optimizer/watch_bundles_for_changes.ts | 10 +- .../kbn-optimizer/src/optimizer/watcher.ts | 8 +- .../src/report_optimizer_stats.ts | 4 +- .../kbn-optimizer/src/worker/run_compilers.ts | 18 +- .../kbn-optimizer/src/worker/run_worker.ts | 4 +- .../kbn-optimizer/src/worker/theme_loader.ts | 2 +- .../src/worker/webpack.config.ts | 6 +- packages/kbn-plugin-generator/index.js | 2 +- .../kbn-plugin-generator/sao_template/sao.js | 8 +- packages/kbn-plugin-helpers/src/cli.ts | 4 +- packages/kbn-plugin-helpers/src/lib/docs.ts | 2 +- .../lib/enable_collecting_unknown_options.ts | 2 +- .../build_action_test_plugin/index.js | 2 +- .../create_build_test_plugin/index.js | 2 +- .../create_package_test_plugin/index.js | 2 +- .../integration_tests/build_action.test.js | 4 +- .../src/tasks/build/rewrite_package_json.ts | 2 +- .../src/tasks/start/start_task.ts | 2 +- packages/kbn-pm/src/cli.ts | 4 +- packages/kbn-pm/src/commands/bootstrap.ts | 2 +- packages/kbn-pm/src/commands/run.ts | 2 +- packages/kbn-pm/src/commands/watch.ts | 2 +- .../production/build_production_projects.ts | 4 +- packages/kbn-pm/src/run.ts | 2 +- .../kbn-pm/src/utils/bootstrap_cache_file.ts | 4 +- packages/kbn-pm/src/utils/fs.ts | 6 +- packages/kbn-pm/src/utils/kibana.ts | 4 +- .../utils/link_project_executables.test.ts | 2 +- .../src/utils/link_project_executables.ts | 4 +- packages/kbn-pm/src/utils/parallelize.test.ts | 8 +- packages/kbn-pm/src/utils/project.ts | 4 +- .../kbn-pm/src/utils/project_checksums.ts | 6 +- packages/kbn-pm/src/utils/projects.test.ts | 6 +- packages/kbn-pm/src/utils/projects.ts | 10 +- packages/kbn-pm/src/utils/watch.ts | 10 +- packages/kbn-pm/src/utils/workspaces.ts | 2 +- .../bin/spec_to_console.js | 2 +- packages/kbn-spec-to-console/lib/convert.js | 14 +- .../lib/convert/methods.js | 2 +- .../kbn-spec-to-console/lib/convert/params.js | 6 +- .../kbn-spec-to-console/lib/convert/parts.js | 4 +- .../kbn-spec-to-console/lib/convert/paths.js | 4 +- .../lib/replace_pattern.js | 2 +- packages/kbn-storybook/index.js | 2 +- packages/kbn-storybook/lib/storybook_entry.js | 12 +- .../storybook_config/middleware.js | 2 +- .../storybook_config/mocks/noop.js | 2 +- .../storybook_config/webpack.config.js | 2 +- .../kbn-test-subj-selector/__tests__/index.js | 4 +- packages/kbn-test-subj-selector/index.js | 7 +- .../add_messages_to_report.test.ts | 8 +- .../add_messages_to_report.ts | 4 +- .../src/failed_tests_reporter/github_api.ts | 2 +- .../run_failed_tests_reporter_cli.ts | 2 +- .../__tests__/integration/basic.js | 2 +- .../__tests__/integration/failure_hooks.js | 2 +- .../src/functional_test_runner/cli.ts | 2 +- .../functional_test_runner.ts | 2 +- .../lib/config/config.ts | 4 +- .../lib/config/schema.ts | 40 +- .../lib/failure_metadata.ts | 8 +- .../lib/lifecycle_event.ts | 2 +- .../lib/lifecycle_phase.test.ts | 6 +- .../functional_test_runner/lib/load_tracer.ts | 4 +- .../lib/mocha/assignment_proxy.js | 2 +- .../lib/mocha/decorate_mocha_ui.js | 4 +- .../lib/mocha/filter_suites_by_tags.js | 10 +- .../lib/mocha/filter_suites_by_tags.test.js | 8 +- .../lib/mocha/load_test_files.js | 2 +- .../lib/mocha/reporter/reporter.js | 22 +- .../lib/mocha/run_tests.ts | 2 +- .../lib/mocha/setup_mocha.js | 10 +- .../lib/providers/async_instance.ts | 2 +- .../lib/providers/provider_collection.ts | 4 +- .../lib/providers/read_provider_spec.ts | 2 +- .../lib/providers/verbose_instance.ts | 6 +- .../lib/suite_tracker.test.ts | 4 +- .../lib/suite_tracker.ts | 4 +- .../functional_tests/cli/run_tests/args.js | 8 +- .../src/functional_tests/cli/run_tests/cli.js | 2 +- .../cli/start_servers/args.js | 6 +- .../functional_tests/cli/start_servers/cli.js | 2 +- .../src/functional_tests/lib/run_cli.js | 7 +- .../src/functional_tests/lib/run_cli.test.js | 4 +- .../functional_tests/lib/run_elasticsearch.js | 2 +- .../functional_tests/lib/run_kibana_server.js | 10 +- .../kbn-test/src/functional_tests/tasks.js | 6 +- .../__tests__/junit_report_generation.js | 4 +- .../src/mocha/junit_report_generation.js | 24 +- packages/kbn-test/src/mocha/run_mocha_cli.js | 2 +- packages/kbn-ui-framework/Gruntfile.js | 22 +- .../src/actions/example_nav_actions.js | 2 +- .../src/components/guide_code/guide_code.js | 2 +- .../guide_code_viewer/guide_code_viewer.js | 2 +- .../src/components/guide_demo/guide_demo.js | 2 +- .../src/components/guide_link/guide_link.js | 2 +- .../src/components/guide_nav/guide_nav.js | 4 +- .../guide_page/guide_page_container.js | 2 +- .../guide_page_side_nav.js | 2 +- .../src/components/guide_text/guide_text.js | 2 +- .../kbn-ui-framework/doc_site/src/index.js | 6 +- .../doc_site/src/services/routes/routes.js | 4 +- .../doc_site/src/services/string/slugify.js | 2 +- .../src/store/reducers/sections_reducer.js | 2 +- .../doc_site/src/views/bar/bar_example.js | 2 +- .../src/views/button/button_elements.js | 4 +- .../src/views/button/button_example.js | 2 +- .../collapse_button/collapse_button_aria.js | 4 +- .../collapse_button_example.js | 2 +- .../empty_table_prompt_example.js | 2 +- .../doc_site/src/views/form/check_box.js | 8 +- .../doc_site/src/views/form/form_example.js | 2 +- .../doc_site/src/views/form/select.js | 13 +- .../doc_site/src/views/form/text_area.js | 12 +- .../src/views/form/text_area_non_resizable.js | 2 +- .../doc_site/src/views/form/text_input.js | 12 +- .../views/form_layout/form_layout_example.js | 2 +- .../doc_site/src/views/icon/icon_example.js | 2 +- .../views/info_panel/info_panel_example.js | 2 +- .../doc_site/src/views/link/link_example.js | 2 +- .../src/views/local_nav/local_nav_example.js | 2 +- .../doc_site/src/views/pager/pager_example.js | 2 +- .../doc_site/src/views/panel/panel_example.js | 2 +- .../views/status_text/status_text_example.js | 2 +- .../doc_site/src/views/table/fluid_table.js | 8 +- .../doc_site/src/views/table/listing_table.js | 2 +- .../doc_site/src/views/table/table.js | 24 +- .../doc_site/src/views/table/table_example.js | 2 +- .../doc_site/src/views/tabs/tabs.js | 2 +- .../doc_site/src/views/tabs/tabs_example.js | 2 +- .../src/views/tool_bar/tool_bar_example.js | 2 +- .../views/typography/typography_example.js | 2 +- .../vertical_rhythm_example.js | 2 +- .../doc_site/src/views/view/view_sandbox.js | 2 +- .../generator-kui/app/component.js | 2 +- .../generator-kui/app/documentation.js | 2 +- .../generator-kui/component/index.js | 4 +- .../generator-kui/documentation/index.js | 4 +- .../kbn-ui-framework/generator-kui/utils.js | 6 +- .../src/components/button/button.js | 2 +- .../src/components/button/button.test.js | 2 +- .../button/button_group/button_group.js | 2 +- .../button/button_icon/button_icon.js | 2 +- .../button/button_icon/button_icon.test.js | 2 +- .../src/components/button/link_button.test.js | 2 +- .../components/button/submit_button.test.js | 2 +- .../collapse_button/collapse_button.test.js | 2 +- .../src/components/form/select/select.test.js | 2 +- .../form/text_area/text_area.test.js | 2 +- .../form/text_input/text_input.test.js | 2 +- .../table/listing_table/listing_table.js | 2 +- .../table/listing_table/listing_table.test.js | 12 +- .../components/typography/typography.test.js | 2 +- .../accessibility/html_id_generator.js | 2 +- .../src/services/sort/sortable_properties.js | 2 +- .../services/sort/sortable_properties.test.js | 6 +- .../src/test/take_mounted_snapshot.js | 2 +- .../kbn-ui-shared-deps/public_path_loader.js | 2 +- packages/kbn-ui-shared-deps/scripts/build.js | 6 +- packages/kbn-ui-shared-deps/webpack.config.js | 4 +- packages/kbn-utility-types/index.ts | 6 +- scripts/es.js | 2 +- scripts/test_hardening.js | 6 +- src/apm.js | 2 +- src/cli/cli.js | 4 +- src/cli/cluster/cluster_manager.test.ts | 2 +- src/cli/cluster/cluster_manager.ts | 21 +- src/cli/cluster/worker.ts | 8 +- src/cli/command.js | 18 +- src/cli/help.js | 10 +- src/cli/repl/index.js | 6 +- src/cli/repl/repl.test.js | 6 +- .../integration_tests/invalid_config.test.ts | 10 +- .../reload_logging_config.test.ts | 40 +- src/cli/serve/read_keystore.js | 2 +- src/cli/serve/serve.js | 12 +- src/cli_keystore/add.test.js | 4 +- src/cli_keystore/cli_keystore.js | 4 +- src/cli_keystore/create.test.js | 4 +- src/cli_keystore/list.test.js | 4 +- src/cli_plugin/cli.js | 4 +- src/cli_plugin/install/cleanup.js | 2 +- src/cli_plugin/install/cleanup.test.js | 42 +- src/cli_plugin/install/download.js | 2 +- src/cli_plugin/install/download.test.js | 96 +- src/cli_plugin/install/downloaders/file.js | 2 +- src/cli_plugin/install/downloaders/http.js | 2 +- src/cli_plugin/install/index.test.js | 22 +- src/cli_plugin/install/kibana.test.js | 34 +- src/cli_plugin/install/pack.test.js | 34 +- src/cli_plugin/install/progress.test.js | 16 +- src/cli_plugin/install/rename.js | 2 +- src/cli_plugin/install/rename.test.js | 26 +- src/cli_plugin/install/settings.js | 2 +- src/cli_plugin/install/settings.test.js | 80 +- src/cli_plugin/install/zip.js | 22 +- src/cli_plugin/install/zip.test.js | 6 +- src/cli_plugin/lib/log_warnings.js | 4 +- src/cli_plugin/lib/logger.test.js | 32 +- src/cli_plugin/list/list.js | 2 +- src/cli_plugin/list/list.test.js | 22 +- src/cli_plugin/list/settings.test.js | 16 +- src/cli_plugin/remove/remove.test.js | 14 +- src/cli_plugin/remove/settings.test.js | 38 +- .../application/application_leave.test.ts | 6 +- .../application/application_service.mock.ts | 2 +- .../application/application_service.test.ts | 34 +- .../application/application_service.tsx | 20 +- .../application_service.test.tsx | 14 +- .../integration_tests/router.test.tsx | 2 +- .../application/integration_tests/utils.tsx | 2 +- .../public/application/scoped_history.test.ts | 6 +- src/core/public/application/scoped_history.ts | 2 +- .../application/ui/app_container.test.tsx | 4 +- .../public/application/ui/app_container.tsx | 2 +- src/core/public/chrome/chrome_service.test.ts | 49 +- src/core/public/chrome/chrome_service.tsx | 6 +- .../chrome/doc_title/doc_title_service.ts | 2 +- .../nav_controls/nav_controls_service.test.ts | 28 +- .../nav_controls/nav_controls_service.ts | 4 +- .../nav_links/nav_links_service.test.ts | 45 +- .../chrome/nav_links/nav_links_service.ts | 10 +- .../chrome/recently_accessed/persisted_log.ts | 4 +- .../chrome/ui/header/collapsible_nav.tsx | 8 +- src/core/public/chrome/ui/header/header.tsx | 8 +- .../public/chrome/ui/header/header_badge.tsx | 2 +- .../chrome/ui/header/header_breadcrumbs.tsx | 2 +- .../public/chrome/ui/header/header_logo.tsx | 4 +- src/core/public/chrome/ui/header/nav_link.tsx | 2 +- .../public/chrome/ui/loading_indicator.tsx | 2 +- src/core/public/entry_point.ts | 4 +- .../fatal_errors/fatal_errors_screen.tsx | 4 +- .../fatal_errors/fatal_errors_service.test.ts | 2 +- .../fatal_errors/fatal_errors_service.tsx | 4 +- src/core/public/http/base_path.ts | 2 +- src/core/public/http/fetch.test.ts | 12 +- src/core/public/http/fetch.ts | 2 +- src/core/public/http/intercept.ts | 8 +- .../public/http/loading_count_service.test.ts | 10 +- src/core/public/http/loading_count_service.ts | 6 +- .../moment/moment_service.test.mocks.ts | 2 +- .../moment/moment_service.test.ts | 2 +- .../styles/styles_service.test.ts | 2 +- src/core/public/legacy/legacy_service.ts | 4 +- .../toasts/global_toast_list.test.tsx | 2 +- .../toasts/global_toast_list.tsx | 2 +- .../notifications/toasts/toasts_api.test.ts | 5 +- .../notifications/toasts/toasts_api.tsx | 2 +- .../public/overlays/banners/banners_list.tsx | 2 +- .../overlays/banners/banners_service.test.ts | 6 +- .../overlays/banners/banners_service.tsx | 2 +- .../overlays/banners/user_banner_service.tsx | 2 +- .../overlays/modal/modal_service.test.tsx | 4 +- .../public/overlays/overlay.test.mocks.ts | 2 +- src/core/public/plugins/plugin.test.ts | 4 +- src/core/public/plugins/plugin_context.ts | 4 +- .../public/plugins/plugins_service.test.ts | 8 +- src/core/public/plugins/plugins_service.ts | 6 +- .../saved_objects/saved_objects_client.ts | 26 +- .../ui_settings/ui_settings_api.test.ts | 22 +- .../ui_settings/ui_settings_client.test.ts | 15 +- .../public/ui_settings/ui_settings_client.ts | 2 +- .../ui_settings/ui_settings_service.test.ts | 2 +- .../public/utils/share_weak_replay.test.ts | 4 +- src/core/public/utils/share_weak_replay.ts | 2 +- src/core/server/bootstrap.ts | 2 +- .../capabilities/capabilities_service.ts | 4 +- .../capabilities/resolve_capabilities.ts | 2 +- src/core/server/config/config.ts | 2 +- src/core/server/config/config_service.test.ts | 12 +- src/core/server/config/config_service.ts | 29 +- .../deprecation/apply_deprecations.test.ts | 4 +- .../deprecation/core_deprecations.test.ts | 4 +- .../config/deprecation/core_deprecations.ts | 10 +- .../deprecation/deprecation_factory.test.ts | 2 +- src/core/server/config/ensure_deep_object.ts | 2 +- .../config_deprecation.test.ts | 4 +- .../server/config/raw_config_service.test.ts | 11 +- src/core/server/config/raw_config_service.ts | 4 +- .../default_route_provider_config.test.ts | 6 +- .../integration_tests/static_assets.test.ts | 12 +- .../elasticsearch_config.test.ts | 4 +- .../elasticsearch/elasticsearch_config.ts | 6 +- .../elasticsearch_service.test.ts | 8 +- .../elasticsearch/elasticsearch_service.ts | 12 +- .../elasticsearch/retry_call_cluster.test.ts | 2 +- .../elasticsearch/retry_call_cluster.ts | 4 +- .../elasticsearch/scoped_cluster_client.ts | 2 +- src/core/server/elasticsearch/status.test.ts | 8 +- .../version_check/ensure_es_version.test.ts | 14 +- .../version_check/ensure_es_version.ts | 14 +- src/core/server/http/auth_headers_storage.ts | 2 +- src/core/server/http/auth_state_storage.ts | 2 +- .../server/http/base_path_proxy_server.ts | 8 +- src/core/server/http/base_path_service.ts | 2 +- .../http/cookie_session_storage.test.ts | 18 +- src/core/server/http/http_config.ts | 4 +- src/core/server/http/http_server.test.ts | 128 +- src/core/server/http/http_server.ts | 2 +- src/core/server/http/http_tools.test.ts | 6 +- src/core/server/http/http_tools.ts | 6 +- .../server/http/https_redirect_server.test.ts | 2 +- .../core_service.test.mocks.ts | 4 +- .../http/integration_tests/lifecycle.test.ts | 161 +- .../lifecycle_handlers.test.ts | 26 +- .../http/integration_tests/request.test.ts | 44 +- .../http/integration_tests/router.test.ts | 306 ++-- .../server/http/lifecycle/on_pre_response.ts | 2 +- .../validate_object.test.ts | 6 +- src/core/server/http/router/error_wrapper.ts | 2 +- src/core/server/http/router/headers.ts | 2 +- src/core/server/http/router/router.mock.ts | 2 +- .../http/router/validator/validator.test.ts | 4 +- src/core/server/http/ssl_config.ts | 2 +- .../config/ensure_valid_configuration.ts | 2 +- .../legacy/config/get_unused_config_keys.ts | 4 +- .../legacy_deprecation_adapters.test.ts | 4 +- .../server/legacy/legacy_internals.test.ts | 12 +- src/core/server/legacy/legacy_service.test.ts | 6 +- src/core/server/legacy/legacy_service.ts | 8 +- src/core/server/legacy/merge_vars.ts | 6 +- .../plugins/find_legacy_plugin_specs.ts | 12 +- .../legacy/plugins/get_nav_links.test.ts | 2 +- .../server/legacy/plugins/get_nav_links.ts | 6 +- .../plugins/log_legacy_plugins_warning.ts | 4 +- .../appenders/file/file_appender.test.ts | 2 +- .../logging/appenders/file/file_appender.ts | 2 +- .../server/logging/integration_tests/utils.ts | 4 +- .../server/logging/layouts/pattern_layout.ts | 2 +- src/core/server/logging/logging_config.ts | 4 +- src/core/server/logging/logging_service.ts | 2 +- src/core/server/metrics/collectors/process.ts | 2 +- src/core/server/metrics/collectors/server.ts | 4 +- .../server_collector.test.ts | 12 +- .../server/metrics/metrics_service.test.ts | 5 +- src/core/server/path/index.ts | 2 +- .../discovery/plugin_manifest_parser.ts | 4 +- .../discovery/plugins_discovery.test.ts | 4 +- .../plugins/discovery/plugins_discovery.ts | 18 +- .../integration_tests/plugins_service.test.ts | 2 +- src/core/server/plugins/plugin.test.ts | 4 +- .../server/plugins/plugins_service.test.ts | 4 +- src/core/server/plugins/plugins_service.ts | 16 +- .../server/plugins/plugins_system.test.ts | 8 +- src/core/server/plugins/plugins_system.ts | 20 +- src/core/server/rendering/views/fonts.tsx | 2 +- src/core/server/root/index.test.ts | 2 +- src/core/server/root/index.ts | 6 +- .../export/get_sorted_objects_for_export.ts | 2 +- .../export/inject_nested_depdendencies.ts | 6 +- .../saved_objects/export/sort_objects.ts | 6 +- .../import/collect_saved_objects.ts | 4 +- .../import/create_objects_filter.ts | 2 +- .../import/import_saved_objects.test.ts | 12 +- .../import/import_saved_objects.ts | 2 +- .../import/resolve_import_errors.test.ts | 26 +- .../import/resolve_import_errors.ts | 4 +- .../saved_objects/import/split_overwrites.ts | 4 +- .../import/validate_references.ts | 8 +- .../saved_objects/mappings/lib/get_types.ts | 2 +- .../migrations/core/build_active_mappings.ts | 11 +- .../migrations/core/build_index_map.test.ts | 2 +- .../migrations/core/build_index_map.ts | 2 +- .../migrations/core/document_migrator.test.ts | 10 +- .../migrations/core/document_migrator.ts | 8 +- .../migrations/core/elastic_index.ts | 8 +- .../migrations/core/index_migrator.test.ts | 2 +- .../migrations/core/index_migrator.ts | 6 +- .../migrations/core/migrate_raw_docs.ts | 2 +- .../migrations/core/migration_coordinator.ts | 2 +- .../migrations/kibana/kibana_migrator.mock.ts | 2 +- .../migrations/kibana/kibana_migrator.test.ts | 9 +- .../migrations/kibana/kibana_migrator.ts | 6 +- .../server/saved_objects/migrations/mocks.ts | 4 +- .../server/saved_objects/routes/export.ts | 2 +- .../server/saved_objects/routes/import.ts | 2 +- .../routes/integration_tests/export.test.ts | 2 +- .../routes/integration_tests/find.test.ts | 4 +- .../routes/integration_tests/migrate.test.ts | 15 +- .../routes/resolve_import_errors.ts | 2 +- src/core/server/saved_objects/routes/utils.ts | 8 +- .../saved_objects_service.test.ts | 4 +- .../saved_objects/saved_objects_service.ts | 10 +- .../saved_objects_type_registry.mock.ts | 5 +- .../saved_objects_type_registry.test.ts | 4 +- .../saved_objects_type_registry.ts | 2 +- .../saved_objects/service/lib/filter_utils.ts | 10 +- .../service/lib/included_fields.ts | 2 +- .../service/lib/priority_collection.test.ts | 4 +- .../service/lib/priority_collection.ts | 6 +- .../service/lib/repository.test.js | 103 +- .../saved_objects/service/lib/repository.ts | 30 +- .../service/lib/scoped_client_provider.ts | 2 +- .../lib/search_dsl/query_params.test.ts | 14 +- .../service/lib/search_dsl/query_params.ts | 4 +- src/core/server/saved_objects/status.ts | 2 +- src/core/server/saved_objects/utils.test.ts | 10 +- .../server/saved_objects/validation/index.ts | 2 +- src/core/server/status/status_service.test.ts | 4 +- src/core/server/status/status_service.ts | 2 +- .../create_or_upgrade_saved_config.test.ts | 4 +- .../get_upgradeable_config.ts | 2 +- .../create_or_upgrade.test.ts | 6 +- .../is_config_version_upgradeable.test.ts | 2 +- .../integration_tests/index.test.ts | 2 +- .../integration_tests/lib/servers.ts | 2 +- .../server/ui_settings/ui_settings_client.ts | 2 +- src/core/server/utils/crypto/pkcs12.test.ts | 4 +- src/core/server/utils/crypto/pkcs12.ts | 6 +- src/core/server/uuid/resolve_uuid.test.ts | 2 +- src/core/server/uuid/resolve_uuid.ts | 10 +- src/core/utils/context.test.ts | 22 +- src/core/utils/context.ts | 2 +- .../integration_tests/deep_freeze.test.ts | 2 +- src/core/utils/map_utils.ts | 2 +- src/core/utils/promise.test.ts | 4 +- src/core/utils/unset.ts | 4 +- src/core/utils/url.test.ts | 8 +- src/dev/build/args.ts | 2 +- src/dev/build/cli.js | 2 +- src/dev/build/lib/__tests__/config.js | 6 +- src/dev/build/lib/__tests__/exec.js | 2 +- src/dev/build/lib/__tests__/fs.js | 4 +- src/dev/build/lib/__tests__/runner.js | 12 +- src/dev/build/lib/__tests__/version_info.js | 10 +- src/dev/build/lib/config.js | 6 +- src/dev/build/lib/exec.js | 2 +- src/dev/build/lib/fs.js | 10 +- src/dev/build/lib/scan.ts | 2 +- src/dev/build/lib/scan_copy.test.ts | 7 +- src/dev/build/lib/scan_copy.ts | 6 +- src/dev/build/lib/scan_delete.ts | 8 +- src/dev/build/tasks/clean_tasks.js | 10 +- .../tasks/create_archives_sources_task.js | 2 +- .../build/tasks/create_package_json_task.js | 4 +- .../build/tasks/nodejs/__tests__/download.js | 12 +- .../__tests__/download_node_builds_task.js | 4 +- .../verify_existing_node_builds_task.js | 2 +- src/dev/build/tasks/nodejs/download.js | 2 +- .../tasks/nodejs/download_node_builds_task.js | 2 +- .../tasks/nodejs/extract_node_builds_task.js | 2 +- .../verify_existing_node_builds_task.js | 2 +- .../clean_client_modules_on_dll_task.js | 6 +- .../build/tasks/nodejs_modules/webpack_dll.js | 8 +- src/dev/build/tasks/path_length_task.js | 6 +- .../code_coverage/ingest_coverage/either.js | 16 +- .../code_coverage/ingest_coverage/ingest.js | 9 +- .../integration_tests/ingest_coverage.test.js | 18 +- .../ingest_coverage/json_stream.js | 2 +- .../code_coverage/ingest_coverage/process.js | 12 +- .../ingest_coverage/transforms.js | 48 +- .../code_coverage/ingest_coverage/utils.js | 8 +- src/dev/eslint/lint_files.ts | 2 +- src/dev/eslint/pick_files_to_lint.ts | 2 +- src/dev/globs.js | 2 +- src/dev/i18n/config.ts | 10 +- src/dev/i18n/extract_default_translations.js | 8 +- src/dev/i18n/extractors/code.test.js | 6 +- src/dev/i18n/extractors/html.js | 16 +- src/dev/i18n/extractors/i18n_call.js | 2 +- src/dev/i18n/extractors/i18n_call.test.js | 14 +- src/dev/i18n/extractors/pug.js | 4 +- src/dev/i18n/extractors/react.js | 6 +- src/dev/i18n/extractors/react.test.js | 10 +- src/dev/i18n/integrate_locale_files.ts | 2 +- src/dev/i18n/serializers/json5.ts | 4 +- src/dev/i18n/tasks/check_compatibility.ts | 2 +- src/dev/i18n/tasks/check_configs.ts | 2 +- .../tasks/extract_default_translations.ts | 2 +- .../tasks/extract_untracked_translations.ts | 6 +- src/dev/i18n/tasks/merge_configs.ts | 2 +- src/dev/i18n/utils.js | 12 +- src/dev/i18n/utils.test.js | 10 +- src/dev/jest/config.integration.js | 2 +- src/dev/jest/junit_reporter.js | 10 +- src/dev/jest/setup/mocks.js | 2 +- src/dev/jest/setup/polyfills.js | 2 +- .../license_checker/run_check_licenses_cli.ts | 4 +- src/dev/license_checker/valid.ts | 4 +- src/dev/notice/bundled_notices.js | 6 +- src/dev/notice/cli.js | 4 +- src/dev/notice/generate_notice_from_source.ts | 4 +- .../notice/generate_package_notice_text.js | 2 +- .../installed_packages.test.ts | 10 +- src/dev/precommit_hook/check_file_casing.js | 6 +- .../precommit_hook/get_files_for_commit.js | 6 +- src/dev/prs/helpers.ts | 2 +- src/dev/prs/run_update_prs_cli.ts | 10 +- src/dev/renovate/config.ts | 6 +- src/dev/renovate/package_groups.ts | 4 +- src/dev/run_check_file_casing.js | 2 +- src/dev/run_check_lockfile_symlinks.js | 24 +- src/dev/run_check_published_api_changes.ts | 8 +- src/dev/run_i18n_extract.ts | 4 +- src/dev/run_prettier_on_changed.ts | 6 +- src/dev/sass/build_sass.js | 12 +- src/dev/sasslint/lint_files.js | 2 +- src/dev/sasslint/pick_files_to_lint.js | 4 +- src/dev/storybook/run_storybook_cli.ts | 4 +- src/dev/typescript/exec_in_projects.ts | 4 +- .../get_ts_project_for_absolute_path.ts | 4 +- src/dev/typescript/project.ts | 4 +- src/dev/typescript/projects.ts | 12 +- .../typescript/run_check_ts_projects_cli.ts | 6 +- src/dev/typescript/run_type_check_cli.ts | 4 +- src/es_archiver/actions/edit.ts | 6 +- src/es_archiver/actions/load.ts | 6 +- src/es_archiver/actions/rebuild_all.ts | 4 +- src/es_archiver/cli.ts | 16 +- src/es_archiver/lib/__tests__/stats.ts | 4 +- .../lib/archives/__tests__/format.ts | 10 +- .../lib/archives/__tests__/parse.ts | 6 +- src/es_archiver/lib/archives/format.ts | 2 +- src/es_archiver/lib/archives/parse.ts | 4 +- src/es_archiver/lib/directory.ts | 4 +- src/es_archiver/lib/docs/__tests__/stubs.ts | 2 +- .../lib/docs/index_doc_records_stream.ts | 2 +- .../generate_index_records_stream.ts | 8 +- .../lib/indices/__tests__/stubs.ts | 12 +- src/es_archiver/lib/indices/delete_index.ts | 2 +- .../__tests__/filter_records_stream.ts | 2 +- src/es_archiver/lib/stats.ts | 6 +- src/fixtures/agg_resp/geohash_grid.js | 6 +- src/fixtures/logstash_fields.js | 2 +- src/fixtures/mock_index_patterns.js | 2 +- src/fixtures/mock_ui_state.js | 10 +- .../stubbed_logstash_index_pattern.js | 10 +- src/fixtures/stubbed_search_source.js | 10 +- src/legacy/core_plugins/apm_oss/index.js | 2 +- .../core_plugins/console_legacy/index.ts | 2 +- .../core_plugins/elasticsearch/index.js | 4 +- .../integration_tests/elasticsearch.test.ts | 6 +- .../elasticsearch/lib/version_health_check.js | 2 +- .../lib/version_health_check.test.js | 8 +- .../server/lib/__tests__/handle_es_error.js | 14 +- .../elasticsearch/server/lib/create_proxy.js | 2 +- src/legacy/core_plugins/kibana/index.js | 18 +- .../public/__tests__/discover/doc_table.js | 24 +- .../public/__tests__/discover/fixed_scroll.js | 34 +- .../public/__tests__/discover/row_headers.js | 174 +-- .../__tests__/vis_type_table/agg_table.js | 82 +- .../vis_type_table/agg_table_group.js | 16 +- .../__tests__/vis_type_tagcloud/tag_cloud.js | 106 +- .../tag_cloud_visualization.js | 14 +- .../vis_type_vega/vega_visualization.js | 10 +- .../__tests__/vis_type_vislib/_vis_fixture.js | 8 +- .../vis_type_vislib/lib/chart_title.js | 33 +- .../__tests__/vis_type_vislib/lib/dispatch.js | 52 +- .../vis_type_vislib/lib/handler/handler.js | 64 +- .../vis_type_vislib/lib/layout/layout.js | 54 +- .../public/__tests__/vis_type_vislib/vis.js | 88 +- .../visualizations/area_chart.js | 96 +- .../vis_type_vislib/visualizations/chart.js | 17 +- .../visualizations/column_chart.js | 98 +- .../visualizations/gauge_chart.js | 38 +- .../visualizations/heatmap_chart.js | 50 +- .../visualizations/line_chart.js | 70 +- .../visualizations/pie_chart.js | 84 +- .../local_application_service.ts | 6 +- .../kibana/public/management/index.js | 12 +- .../export/collect_references_deep.test.ts | 4 +- .../lib/export/collect_references_deep.ts | 2 +- .../server/lib/export/export_dashboards.js | 2 +- .../server/lib/import/import_dashboards.js | 4 +- .../management/saved_objects/relationships.js | 8 +- .../kibana/server/routes/api/export/index.js | 2 +- .../kibana/server/routes/api/import/index.js | 2 +- .../kibana/server/ui_setting_defaults.js | 4 +- src/legacy/core_plugins/status_page/index.js | 2 +- .../public/components/metric_tiles.js | 4 +- .../public/components/status_app.js | 2 +- .../public/components/status_table.js | 4 +- .../public/lib/load_status.test.js | 4 +- .../status_page/public/status_page.js | 2 +- src/legacy/core_plugins/testbed/index.js | 2 +- .../tests_bundle/find_source_files.js | 4 +- src/legacy/core_plugins/tests_bundle/index.js | 17 +- .../tests_bundle/tests_entry_template.js | 2 +- .../core_plugins/timelion/public/app.js | 70 +- .../components/timelionhelp_tabs_directive.js | 2 +- .../timelion/public/directives/cells/cells.js | 8 +- .../timelion/public/directives/chart/chart.js | 2 +- .../public/directives/fixed_element.js | 6 +- .../directives/fullscreen/fullscreen.js | 2 +- .../public/directives/saved_object_finder.js | 38 +- .../saved_object_save_as_checkbox.js | 2 +- .../directives/timelion_expression_input.js | 10 +- .../timelion_expression_input_helpers.js | 22 +- .../timelion_expression_suggestions.js | 12 +- .../timelion_expression_suggestions.js | 4 +- .../public/directives/timelion_grid.js | 10 +- .../directives/timelion_help/timelion_help.js | 16 +- .../timelion_interval/timelion_interval.js | 10 +- .../public/directives/timelion_load_sheet.js | 2 +- .../directives/timelion_options_sheet.js | 2 +- .../public/directives/timelion_save_sheet.js | 2 +- .../timelion/public/lib/observe_resize.js | 6 +- .../public/panels/timechart/schema.ts | 37 +- .../timelion/public/services/saved_sheets.ts | 2 +- .../public/shim/timelion_legacy_module.ts | 2 +- .../deprecation/__tests__/create_transform.js | 16 +- src/legacy/deprecation/create_transform.js | 2 +- .../deprecations/__tests__/rename.js | 14 +- .../deprecations/__tests__/unused.js | 14 +- .../__tests__/find_plugin_specs.js | 24 +- .../__tests__/fixtures/conflicts/foo/index.js | 2 +- .../__tests__/fixtures/plugins/bar/index.js | 2 +- .../__tests__/fixtures/plugins/foo/index.js | 2 +- .../plugin_discovery/find_plugin_specs.js | 36 +- .../__tests__/extend_config_service.js | 2 +- .../plugin_config/__tests__/schema.js | 16 +- .../plugin_pack/__tests__/create_pack.js | 16 +- .../fixtures/plugins/broken_code/index.js | 2 +- .../__tests__/fixtures/plugins/foo/index.js | 2 +- .../__tests__/package_json_at_path.js | 22 +- .../__tests__/package_jsons_in_directory.js | 24 +- .../plugin_pack/__tests__/plugin_pack.js | 8 +- .../plugin_pack/create_pack.js | 4 +- .../plugin_discovery/plugin_pack/lib/fs.js | 16 +- .../plugin_pack/package_json_at_path.js | 8 +- .../plugin_pack/package_jsons_in_directory.js | 4 +- .../plugin_pack/plugin_pack.js | 2 +- .../plugin_spec/__tests__/plugin_spec.js | 26 +- .../server/capabilities/capabilities_mixin.ts | 8 +- src/legacy/server/config/complete.js | 4 +- src/legacy/server/config/complete.test.js | 2 +- src/legacy/server/config/config.js | 6 +- src/legacy/server/config/config.test.js | 122 +- src/legacy/server/config/override.test.ts | 4 +- src/legacy/server/config/schema.js | 47 +- src/legacy/server/config/schema.test.js | 28 +- src/legacy/server/http/index.js | 6 +- .../max_payload_size.test.js | 10 +- .../server/http/setup_base_path_provider.js | 2 +- .../server/i18n/get_translations_path.ts | 2 +- src/legacy/server/i18n/index.ts | 6 +- .../localization/file_integrity.test.mocks.ts | 2 +- src/legacy/server/keystore/keystore.test.js | 4 +- .../server/logging/apply_filters_to_keys.js | 2 +- .../logging/apply_filters_to_keys.test.js | 4 +- src/legacy/server/logging/configuration.js | 2 +- src/legacy/server/logging/log_format.js | 4 +- src/legacy/server/logging/log_format_json.js | 2 +- .../server/logging/log_format_json.test.js | 2 +- .../server/logging/log_format_string.js | 8 +- src/legacy/server/logging/log_reporter.js | 5 +- .../server/logging/rotate/log_rotator.ts | 6 +- src/legacy/server/pid/index.js | 12 +- src/legacy/server/plugins/initialize_mixin.js | 2 +- .../server/plugins/lib/call_plugin_hook.js | 2 +- src/legacy/server/plugins/scan_mixin.js | 2 +- .../server/plugins/wait_for_plugins_init.js | 2 +- src/legacy/server/sass/build.js | 8 +- src/legacy/server/sass/build_all.js | 4 +- src/legacy/server/sass/index.js | 18 +- .../saved_objects/saved_objects_mixin.js | 10 +- .../saved_objects/saved_objects_mixin.test.js | 4 +- .../add_memoized_factory_to_request.test.js | 2 +- .../server_extensions_mixin.js | 2 +- src/legacy/server/status/index.js | 4 +- .../server/status/lib/__mocks__/_fs_stubs.js | 6 +- src/legacy/server/status/lib/cgroup.js | 16 +- src/legacy/server/status/lib/cgroup.test.js | 2 +- .../server/status/lib/get_os_info.test.js | 2 +- src/legacy/server/status/lib/metrics.test.js | 4 +- .../status/routes/api/register_stats.js | 6 +- .../status/routes/page/register_status.js | 2 +- src/legacy/server/status/samples.js | 6 +- src/legacy/server/status/server_status.js | 6 +- .../server/status/server_status.test.js | 34 +- src/legacy/server/status/status.js | 6 +- src/legacy/server/status/status.test.js | 32 +- src/legacy/server/status/wrap_auth_config.js | 4 +- .../server/status/wrap_auth_config.test.js | 2 +- src/legacy/server/utils/prompt.js | 10 +- src/legacy/server/warnings/index.js | 4 +- .../fixtures/plugin_async_foo/index.js | 2 +- .../ui/__tests__/fixtures/plugin_bar/index.js | 2 +- .../ui/__tests__/fixtures/plugin_foo/index.js | 2 +- .../ui/__tests__/fixtures/test_app/index.js | 2 +- src/legacy/ui/public/__tests__/events.js | 56 +- .../__tests__/kbn_accessible_click.js | 4 +- .../ui/public/accessibility/angular_aria.js | 2 +- .../accessibility/kbn_ui_ace_keyboard_mode.js | 6 +- .../scrollto_activedescendant.js | 2 +- .../ui/public/binder/__tests__/binder.js | 18 +- src/legacy/ui/public/binder/binder.js | 2 +- src/legacy/ui/public/bound_to_config_obj.js | 2 +- .../react/ui_capabilities_provider.tsx | 2 +- .../ui/public/chrome/__mocks__/index.js | 8 +- .../ui/public/chrome/api/__tests__/apps.js | 38 +- .../ui/public/chrome/api/__tests__/nav.js | 20 +- .../api/__tests__/sub_url_route_filter.js | 6 +- .../ui/public/chrome/api/__tests__/xsrf.js | 8 +- src/legacy/ui/public/chrome/api/angular.js | 2 +- src/legacy/ui/public/chrome/api/apps.js | 18 +- src/legacy/ui/public/chrome/api/nav.ts | 14 +- .../public/chrome/api/saved_object_client.ts | 2 +- src/legacy/ui/public/chrome/api/template.js | 6 +- .../ui/public/chrome/api/ui_settings.js | 2 +- src/legacy/ui/public/chrome/api/xsrf.js | 2 +- src/legacy/ui/public/chrome/chrome.js | 6 +- .../ui/public/chrome/directives/kbn_chrome.js | 4 +- .../ui/public/config/__tests__/config.js | 6 +- src/legacy/ui/public/config/config.js | 12 +- .../directives/__tests__/input_focus.js | 14 +- .../public/directives/bind/__tests__/bind.js | 14 +- src/legacy/ui/public/directives/bind/bind.js | 18 +- .../ui/public/directives/input_focus.js | 6 +- src/legacy/ui/public/directives/kbn_href.js | 6 +- .../directives/listen/__tests__/listen.js | 12 +- .../__tests__/render_directive.js | 20 +- .../render_directive/apply_scope_bindings.js | 6 +- .../render_directive/render_directive.js | 6 +- .../ui/public/directives/storage/index.js | 4 +- .../watch_multi/__tests__/watch_multi.js | 46 +- .../public/doc_title/__tests__/doc_title.js | 26 +- src/legacy/ui/public/doc_title/doc_title.js | 2 +- .../__tests__/documentation_links.js | 4 +- src/legacy/ui/public/dom_location.js | 2 +- src/legacy/ui/public/events.js | 18 +- src/legacy/ui/public/i18n/index.tsx | 2 +- .../indexed_array/__tests__/indexed_array.js | 40 +- .../indexed_array/__tests__/inflector.js | 16 +- .../ui/public/indexed_array/indexed_array.js | 14 +- .../ui/public/indexed_array/inflector.js | 2 +- src/legacy/ui/public/kfetch/kfetch.test.ts | 16 +- src/legacy/ui/public/kfetch/kfetch.ts | 2 +- .../ui/public/legacy_compat/__tests__/xsrf.js | 36 +- src/legacy/ui/public/modules.js | 4 +- .../new_platform/new_platform.karma_mock.js | 12 +- .../public/new_platform/new_platform.test.ts | 2 +- .../public/new_platform/set_services.test.ts | 4 +- .../ui/public/private/__tests__/private.js | 24 +- .../ui/public/promises/__tests__/promises.js | 18 +- src/legacy/ui/public/react_components.js | 4 +- .../ui/public/registry/__tests__/registry.js | 46 +- src/legacy/ui/public/registry/_registry.js | 8 +- .../public/routes/__tests__/_route_manager.js | 30 +- .../ui/public/routes/__tests__/_work_queue.js | 32 +- .../routes/__tests__/_wrap_route_with_prep.js | 28 +- .../ui/public/routes/__tests__/index.js | 2 +- src/legacy/ui/public/routes/route_manager.js | 16 +- .../ui/public/routes/route_setup_manager.js | 12 +- src/legacy/ui/public/routes/work_queue.js | 16 +- .../ui/public/routes/wrap_route_with_prep.js | 8 +- .../state_management/__tests__/app_state.js | 18 +- .../__tests__/config_provider.js | 8 +- .../__tests__/global_state.js | 8 +- .../state_management/__tests__/state.js | 44 +- .../__tests__/state_monitor_factory.js | 62 +- .../ui/public/state_management/app_state.js | 24 +- .../public/state_management/global_state.js | 2 +- .../ui/public/state_management/state.js | 30 +- .../state_management/state_monitor_factory.ts | 4 +- .../ui/public/test_harness/test_harness.js | 2 +- .../test_sharding/find_test_bundle_url.js | 4 +- .../test_sharding/setup_test_sharding.js | 2 +- .../setup_top_level_describe_filter.js | 2 +- .../url/__tests__/extract_app_path_and_id.js | 50 +- .../public/url/__tests__/kibana_parsed_url.js | 50 +- .../ui/public/url/__tests__/prepend_path.js | 30 +- src/legacy/ui/public/url/__tests__/url.js | 166 +- src/legacy/ui/public/url/kibana_parsed_url.ts | 6 +- .../ui/public/url/redirect_when_missing.js | 6 +- src/legacy/ui/public/url/url.js | 30 +- src/legacy/ui/public/utils/legacy_class.js | 2 +- src/legacy/ui/ui_apps/__tests__/ui_app.js | 7 +- src/legacy/ui/ui_apps/ui_app.js | 2 +- src/legacy/ui/ui_apps/ui_apps_mixin.js | 8 +- .../ui/ui_bundles/app_entry_template.js | 2 +- src/legacy/ui/ui_bundles/ui_bundle.js | 12 +- .../ui/ui_bundles/ui_bundles_controller.js | 4 +- .../__tests__/collect_ui_exports.js | 4 +- .../ui/ui_exports/ui_export_defaults.js | 2 +- .../ui_export_types/modify_reduce/alias.js | 2 +- .../ui_export_types/modify_reduce/map_spec.js | 2 +- .../modify_reduce/unique_keys.js | 6 +- .../reduce/lib/create_type_reducer.js | 2 +- .../ui_export_types/saved_object.js | 6 +- .../ui_export_types/style_sheet_paths.test.js | 4 +- .../ui_export_types/webpack_customizations.js | 2 +- src/legacy/ui/ui_render/ui_render_mixin.js | 21 +- .../ui_settings_mixin.test.ts | 22 +- .../ui/ui_settings/ui_exports_consumer.js | 2 +- .../ui/ui_settings/ui_settings_mixin.js | 2 +- src/legacy/utils/__tests__/unset.js | 34 +- .../utils/__tests__/watch_stdio_for_line.js | 6 +- src/legacy/utils/binder.ts | 2 +- .../utils/streams/concat_stream_providers.js | 2 +- .../utils/streams/filter_stream.test.ts | 2 +- src/legacy/utils/streams/list_stream.js | 2 +- src/legacy/utils/streams/list_stream.test.js | 4 +- src/legacy/utils/streams/map_stream.test.js | 2 +- .../utils/streams/promise_from_streams.js | 2 +- .../streams/promise_from_streams.test.js | 6 +- .../utils/streams/reduce_stream.test.js | 4 +- .../utils/streams/replace_stream.test.js | 6 +- src/legacy/utils/streams/split_stream.test.js | 2 +- src/legacy/utils/watch_stdio_for_line.js | 2 +- src/optimize/base_optimizer.js | 22 +- src/optimize/bundles_route/file_hash.ts | 6 +- src/optimize/create_ui_exports_module.js | 4 +- .../dynamic_dll_plugin/dll_compiler.js | 22 +- .../dynamic_dll_plugin/dll_entry_template.js | 8 +- .../dynamic_dll_plugin/dynamic_dll_plugin.js | 14 +- src/optimize/fs_optimizer.js | 2 +- src/optimize/np_ui_plugin_public_dirs.ts | 2 +- src/optimize/public_path_placeholder.ts | 2 +- src/optimize/watch/optmzr_role.js | 2 +- src/optimize/watch/proxy_role.js | 4 +- src/optimize/watch/watch.js | 2 +- src/optimize/watch/watch_cache.ts | 2 +- src/optimize/watch/watch_optimizer.js | 4 +- .../management_app/advanced_settings.tsx | 4 +- .../advanced_settings_voice_announcement.tsx | 4 +- .../components/field/field.test.tsx | 6 +- .../management_app/components/field/field.tsx | 4 +- .../management_app/components/form/form.tsx | 16 +- .../components/search/search.tsx | 2 +- .../management_app/lib/get_aria_name.test.ts | 10 +- .../management_app/lib/get_aria_name.ts | 2 +- .../lib/get_category_name.test.ts | 10 +- .../management_app/lib/get_category_name.ts | 2 +- .../management_app/lib/get_val_type.test.ts | 14 +- .../lib/is_default_value.test.ts | 24 +- .../lib/to_editable_config.test.ts | 48 +- .../instructions/apm_agent_instructions.ts | 5 +- .../tests/create_batched_function.test.ts | 2 +- .../create_streaming_batched_function.test.ts | 48 +- .../create_streaming_batched_function.ts | 4 +- src/plugins/bfetch/public/plugin.ts | 4 +- .../public/streaming/fetch_streaming.test.ts | 2 +- .../bfetch/public/streaming/split.test.ts | 4 +- src/plugins/bfetch/public/streaming/split.ts | 2 +- src/plugins/bfetch/server/plugin.ts | 4 +- .../server/streaming/create_ndjson_stream.ts | 2 +- .../public/services/colors/color_palette.ts | 6 +- .../public/services/colors/colors.test.ts | 2 +- .../charts/public/services/colors/colors.ts | 2 +- .../services/colors/mapped_colors.test.ts | 37 +- .../public/services/colors/mapped_colors.ts | 8 +- .../services/colors/seed_colors.test.ts | 4 +- .../charts/public/services/theme/theme.ts | 2 +- .../public/static/color_maps/heatmap_color.ts | 2 +- .../public/static/components/number_input.tsx | 2 +- .../public/static/components/select.tsx | 2 +- .../public/static/components/switch.tsx | 2 +- .../public/static/components/text_input.tsx | 2 +- .../application/components/console_menu.tsx | 4 +- .../application/components/settings_modal.tsx | 16 +- .../editor/legacy/console_editor/editor.tsx | 7 +- .../legacy/console_editor/editor_output.tsx | 4 +- .../editor/legacy/console_menu_actions.ts | 7 +- .../subscribe_console_resize_checker.ts | 2 +- .../application/containers/settings.tsx | 2 +- .../editor_context/editor_context.tsx | 2 +- .../__tests__/input.test.js | 4 +- .../__tests__/output_tokenization.test.js | 4 +- .../legacy_core_editor.test.mocks.ts | 2 +- .../legacy_core_editor/legacy_core_editor.ts | 10 +- .../models/legacy_core_editor/mode/input.js | 16 +- .../models/legacy_core_editor/mode/output.js | 4 +- .../models/legacy_core_editor/mode/script.js | 8 +- .../models/legacy_core_editor/smart_resize.ts | 2 +- .../legacy_core_editor/theme_sense_dark.js | 2 +- .../__tests__/integration.test.js | 16 +- .../__tests__/sense_editor.test.js | 16 +- .../models/sense_editor/sense_editor.ts | 6 +- .../public/application/stores/editor.ts | 2 +- .../public/application/stores/request.ts | 2 +- .../ace_token_provider/token_provider.test.ts | 16 +- .../lib/ace_token_provider/token_provider.ts | 2 +- .../__jest__/url_autocomplete.test.js | 26 +- .../autocomplete/__jest__/url_params.test.js | 8 +- .../public/lib/autocomplete/autocomplete.ts | 8 +- .../public/lib/autocomplete/body_completer.js | 16 +- .../field_autocomplete_component.js | 4 +- .../components/id_autocomplete_component.js | 2 +- .../autocomplete/components/list_component.js | 6 +- .../components/object_component.js | 8 +- .../components/url_pattern_matcher.js | 8 +- .../console/public/lib/autocomplete/engine.js | 24 +- .../public/lib/autocomplete/url_params.js | 2 +- .../__tests__/curl_parsing.test.js | 8 +- .../public/lib/kb/__tests__/kb.test.js | 6 +- src/plugins/console/public/lib/kb/api.js | 18 +- src/plugins/console/public/lib/kb/kb.js | 44 +- .../local_storage_object_client.ts | 2 +- .../lib/mappings/__tests__/mapping.test.js | 16 +- .../console/public/lib/mappings/mappings.js | 34 +- .../lib/token_iterator/token_iterator.ts | 2 +- .../public/lib/utils/__tests__/utils.test.js | 6 +- src/plugins/console/public/lib/utils/index.ts | 2 +- .../console/public/services/history.ts | 6 +- .../__tests__/elasticsearch_proxy_config.js | 38 +- .../console/server/__tests__/proxy_config.js | 62 +- .../__tests__/proxy_config_collection.js | 52 +- .../server/__tests__/proxy_route/body.test.ts | 4 +- .../console/server/__tests__/set_headers.js | 12 +- .../server/__tests__/wildcard_matcher.js | 10 +- .../server/lib/proxy_config_collection.ts | 4 +- .../console/server/lib/proxy_request.ts | 4 +- .../lib/spec_definitions/js/mappings.ts | 2 +- src/plugins/console/server/plugin.ts | 5 +- .../api/console/proxy/create_handler.ts | 4 +- .../api/console/proxy/validation_config.ts | 6 +- .../services/spec_definitions_service.ts | 10 +- .../common/migrate_to_730_panels.test.ts | 6 +- .../dashboard/common/migrate_to_730_panels.ts | 4 +- .../actions/clone_panel_action.test.tsx | 2 +- .../actions/clone_panel_action.tsx | 5 +- .../actions/replace_panel_flyout.tsx | 2 +- .../public/application/application.ts | 2 +- .../application/dashboard_app_controller.tsx | 28 +- .../application/dashboard_state.test.ts | 12 +- .../application/dashboard_state_manager.ts | 12 +- .../embeddable/dashboard_container.test.tsx | 4 +- .../embeddable/grid/dashboard_grid.test.tsx | 2 +- .../embeddable/grid/dashboard_grid.tsx | 6 +- .../panel/dashboard_panel_placement.ts | 4 +- .../viewport/dashboard_viewport.test.tsx | 38 +- .../public/application/legacy_app.js | 31 +- .../public/application/lib/filter_utils.ts | 6 +- .../application/lib/migrate_app_state.ts | 2 +- .../application/lib/update_saved_dashboard.ts | 2 +- .../listing/dashboard_listing.test.js | 14 +- src/plugins/dashboard/public/plugin.tsx | 6 +- .../saved_dashboard_references.ts | 4 +- src/plugins/dashboard/public/url_generator.ts | 8 +- .../saved_objects/migrate_match_all_query.ts | 2 +- .../saved_objects/move_filters_to_query.ts | 2 +- .../es_query/es_query/build_es_query.ts | 2 +- .../common/es_query/es_query/from_filters.ts | 10 +- .../es_query/es_query/from_kuery.test.ts | 6 +- .../common/es_query/es_query/from_kuery.ts | 2 +- .../es_query/es_query/from_lucene.test.ts | 4 +- .../common/es_query/es_query/from_lucene.ts | 2 +- .../es_query/handle_nested_filter.test.ts | 4 +- .../es_query/es_query/handle_nested_filter.ts | 4 +- .../es_query/es_query/migrate_filter.test.ts | 8 +- .../es_query/es_query/migrate_filter.ts | 2 +- .../es_query/filters/exists_filter.test.ts | 6 +- .../filters/geo_bounding_box_filter.test.ts | 4 +- .../filters/geo_bounding_box_filter.ts | 2 +- .../filters/geo_polygon_filter.test.ts | 4 +- .../es_query/filters/geo_polygon_filter.ts | 2 +- .../es_query/filters/get_filter_field.test.ts | 4 +- .../filters/get_index_pattern_from_filter.ts | 2 +- .../es_query/filters/missing_filter.test.ts | 4 +- .../es_query/filters/phrase_filter.test.ts | 4 +- .../es_query/filters/phrases_filter.test.ts | 6 +- .../es_query/filters/range_filter.test.ts | 4 +- .../common/es_query/filters/range_filter.ts | 2 +- .../es_query/kuery/functions/and.test.ts | 2 +- .../es_query/kuery/functions/geo_polygon.ts | 2 +- .../es_query/kuery/functions/or.test.ts | 2 +- .../kuery/functions/utils/get_fields.ts | 4 +- .../utils/get_full_field_name_node.test.ts | 2 +- .../es_query/kuery/kuery_syntax_error.ts | 2 +- .../es_query/kuery/node_types/wildcard.ts | 10 +- .../content_types/text_content_type.ts | 2 +- .../field_formats/converters/boolean.test.ts | 2 +- .../field_formats/converters/boolean.ts | 2 +- .../common/field_formats/converters/color.ts | 2 +- .../converters/date_nanos.test.ts | 2 +- .../field_formats/converters/date_nanos.ts | 2 +- .../field_formats/converters/duration.ts | 2 +- .../common/field_formats/converters/ip.ts | 2 +- .../field_formats/converters/numeral.ts | 2 +- .../field_formats/converters/percent.ts | 2 +- .../field_formats/converters/relative_date.ts | 2 +- .../common/field_formats/converters/source.ts | 4 +- .../field_formats/converters/static_lookup.ts | 2 +- .../common/field_formats/converters/string.ts | 4 +- .../field_formats/converters/truncate.ts | 2 +- .../common/field_formats/converters/url.ts | 6 +- .../field_formats/field_formats_registry.ts | 6 +- .../utils/highlight/highlight_html.test.ts | 14 +- .../utils/highlight/highlight_html.ts | 2 +- .../index_patterns/fields/fields.mocks.ts.ts | 2 +- .../data/common/index_patterns/utils.test.ts | 6 +- .../common/kbn_field_types/kbn_field_types.ts | 8 +- .../least_common_interval.ts | 2 +- .../parse_es_interval.test.ts | 4 +- .../date_interval_utils/parse_es_interval.ts | 4 +- .../date_interval_utils/parse_interval.ts | 6 +- .../data/common/utils/abort_utils.test.ts | 2 +- src/plugins/data/common/utils/abort_utils.ts | 2 +- .../public/actions/apply_filter_action.ts | 4 +- .../create_filters_from_value_click.ts | 12 +- .../data/public/actions/value_click_action.ts | 4 +- .../autocomplete/autocomplete_service.ts | 2 +- .../public/field_formats/converters/date.ts | 2 +- .../public/field_formats/utils/deserialize.ts | 2 +- .../index_patterns/fields/field_list.ts | 4 +- .../index_patterns/fields/obj_define.js | 20 +- .../index_patterns/fields/obj_define.test.js | 36 +- .../index_patterns/flatten_hit.ts | 10 +- .../index_patterns/format_hit.ts | 4 +- .../index_patterns/index_pattern.test.ts | 20 +- .../index_patterns/index_pattern.ts | 16 +- .../index_patterns/index_patterns.ts | 4 +- .../index_patterns_api_client.test.mock.ts | 2 +- .../index_patterns_api_client.test.ts | 6 +- .../index_patterns_api_client.ts | 8 +- .../lib/validate_index_pattern.test.ts | 2 +- .../filter_manager/filter_manager.test.ts | 66 +- .../query/filter_manager/filter_manager.ts | 6 +- .../filter_manager/lib/generate_filters.ts | 4 +- .../lib/generate_mapping_chain.test.ts | 2 +- .../filter_manager/lib/map_filter.test.ts | 2 +- .../filter_manager/lib/mappers/map_default.ts | 2 +- .../lib/mappers/map_exists.test.ts | 2 +- .../lib/mappers/map_geo_bounding_box.test.ts | 2 +- .../lib/mappers/map_geo_bounding_box.ts | 2 +- .../lib/mappers/map_geo_polygon.test.ts | 2 +- .../lib/mappers/map_geo_polygon.ts | 2 +- .../lib/mappers/map_match_all.test.ts | 2 +- .../lib/mappers/map_missing.test.ts | 2 +- .../lib/mappers/map_phrase.test.ts | 2 +- .../lib/mappers/map_query_string.test.ts | 2 +- .../lib/mappers/map_range.test.ts | 2 +- .../lib/mappers/map_spatial_filter.test.ts | 2 +- .../data/public/query/lib/from_user.test.ts | 12 +- .../data/public/query/lib/match_pairs.ts | 4 +- .../query/persisted_log/persisted_log.ts | 2 +- .../saved_query/saved_query_service.test.ts | 12 +- .../state_sync/connect_to_query_state.ts | 8 +- .../create_global_query_observable.ts | 10 +- .../query/state_sync/sync_state_with_url.ts | 2 +- .../data/public/query/timefilter/get_time.ts | 4 +- .../timefilter/lib/diff_time_picker_vals.ts | 2 +- .../public/search/aggs/agg_config.test.ts | 11 +- .../data/public/search/aggs/agg_config.ts | 12 +- .../public/search/aggs/agg_configs.test.ts | 12 +- .../data/public/search/aggs/agg_configs.ts | 20 +- .../public/search/aggs/agg_params.test.ts | 4 +- .../data/public/search/aggs/agg_params.ts | 2 +- .../data/public/search/aggs/agg_type.test.ts | 2 +- .../buckets/_terms_other_bucket_helper.ts | 14 +- .../create_filter/date_histogram.test.ts | 9 +- .../search/aggs/buckets/date_histogram.ts | 4 +- .../public/search/aggs/buckets/date_range.ts | 2 +- .../public/search/aggs/buckets/filters.ts | 4 +- .../public/search/aggs/buckets/ip_range.ts | 2 +- .../buckets/migrate_include_exclude_format.ts | 2 +- .../data/public/search/aggs/buckets/terms.ts | 4 +- .../data/public/search/aggs/index.test.ts | 4 +- .../data/public/search/aggs/metrics/avg.ts | 2 +- .../public/search/aggs/metrics/bucket_avg.ts | 2 +- .../public/search/aggs/metrics/bucket_max.ts | 2 +- .../public/search/aggs/metrics/bucket_min.ts | 2 +- .../public/search/aggs/metrics/bucket_sum.ts | 2 +- .../public/search/aggs/metrics/cardinality.ts | 2 +- .../search/aggs/metrics/cumulative_sum.ts | 2 +- .../search/aggs/metrics/metric_agg_type.ts | 2 +- .../public/search/aggs/metrics/moving_avg.ts | 2 +- .../aggs/metrics/parent_pipeline.test.ts | 6 +- .../aggs/metrics/percentile_ranks.test.ts | 4 +- .../public/search/aggs/metrics/serial_diff.ts | 2 +- .../aggs/metrics/sibling_pipeline.test.ts | 6 +- .../search/aggs/metrics/top_hit.test.ts | 4 +- .../public/search/aggs/metrics/top_hit.ts | 4 +- .../public/search/aggs/param_types/base.ts | 2 +- .../search/aggs/param_types/json.test.ts | 4 +- .../public/search/aggs/param_types/json.ts | 4 +- .../search/aggs/param_types/string.test.ts | 2 +- .../aggs/test_helpers/function_wrapper.ts | 2 +- .../test_helpers/mock_agg_types_registry.ts | 6 +- .../public/search/aggs/utils/prop_filter.ts | 4 +- .../build_tabular_inspector_data.ts | 10 +- .../search/expressions/create_filter.ts | 6 +- .../data/public/search/expressions/esaggs.ts | 4 +- .../search/fetch/get_search_params.test.ts | 2 +- .../public/search/legacy/call_client.test.ts | 2 +- .../data/public/search/legacy/call_client.ts | 4 +- .../legacy/default_search_strategy.test.ts | 6 +- .../search/legacy/default_search_strategy.ts | 2 +- .../public/search/legacy/fetch_soon.test.ts | 12 +- .../data/public/search/legacy/fetch_soon.ts | 2 +- .../search/legacy/get_msearch_params.test.ts | 2 +- .../data/public/search/search_interceptor.ts | 2 +- .../data/public/search/search_service.ts | 6 +- .../search_source/filter_docvalue_fields.ts | 2 +- .../search/search_source/inject_references.ts | 2 +- .../normalize_sort_request.test.ts | 14 +- .../search_source/normalize_sort_request.ts | 2 +- .../search_source/search_source.test.ts | 2 +- .../search/search_source/search_source.ts | 2 +- .../search/sync_search_strategy.test.ts | 4 +- .../data/public/search/tabify/buckets.test.ts | 6 +- .../data/public/search/tabify/buckets.ts | 2 +- .../public/search/tabify/get_columns.test.ts | 2 +- .../data/public/search/tabify/get_columns.ts | 6 +- .../public/search/tabify/response_writer.ts | 6 +- .../data/public/search/tabify/tabify.test.ts | 4 +- .../data/public/ui/filter_bar/filter_bar.tsx | 2 +- .../filter_editor/generic_combo_box.tsx | 6 +- .../ui/filter_bar/filter_editor/index.tsx | 6 +- .../lib/filter_editor_utils.test.ts | 6 +- .../filter_editor/lib/filter_editor_utils.ts | 8 +- .../filter_editor/phrase_value_input.tsx | 2 +- .../filter_editor/phrases_values_input.tsx | 2 +- .../public/ui/filter_bar/filter_options.tsx | 2 +- .../fetch_index_patterns.ts | 4 +- .../query_string_input.test.tsx | 5 +- .../query_string_input/query_string_input.tsx | 10 +- .../ui/saved_query_form/save_query_form.tsx | 6 +- .../saved_query_management_component.tsx | 10 +- .../data/public/ui/search_bar/search_bar.tsx | 6 +- .../shard_failure_description_header.tsx | 6 +- .../shard_failure_modal.tsx | 2 +- .../typeahead/suggestions_component.test.tsx | 10 +- .../ui/typeahead/suggestions_component.tsx | 4 +- .../autocomplete/value_suggestions_route.ts | 2 +- .../field_formats/converters/date_server.ts | 2 +- .../field_formats/field_formats_service.ts | 2 +- .../field_capabilities.test.js | 12 +- .../field_capabilities/field_capabilities.ts | 4 +- .../field_caps_response.test.js | 32 +- .../field_capabilities/field_caps_response.ts | 98 +- .../fetcher/lib/resolve_time_pattern.ts | 8 +- .../data/server/index_patterns/utils.ts | 2 +- .../kql_telemetry/kql_telemetry_service.ts | 4 +- .../saved_objects/index_pattern_migrations.ts | 6 +- .../saved_objects/search_migrations.test.ts | 2 +- .../server/saved_objects/search_migrations.ts | 6 +- .../data/server/search/search_service.ts | 2 +- src/plugins/dev_tools/public/application.tsx | 10 +- .../public/application/angular/context.js | 6 +- .../application/angular/context/api/_stubs.js | 6 +- .../angular/context/api/anchor.test.js | 26 +- .../context/api/context.predecessors.test.js | 24 +- .../context/api/context.successors.test.js | 24 +- .../angular/context/api/context.ts | 2 +- .../context/api/utils/date_conversion.test.ts | 8 +- .../context/api/utils/generate_intervals.ts | 2 +- .../angular/context/api/utils/sorting.test.ts | 4 +- .../angular/context/api/utils/sorting.ts | 2 +- .../components/action_bar/action_bar.test.tsx | 2 +- .../components/action_bar/action_bar.tsx | 2 +- .../action_bar/action_bar_directive.ts | 2 +- .../angular/context/query/actions.js | 30 +- .../context/query_parameters/actions.js | 10 +- .../context/query_parameters/actions.test.ts | 10 +- .../public/application/angular/context_app.js | 8 +- .../collapsible_sidebar.ts | 4 +- .../angular/directives/debounce/debounce.js | 6 +- .../directives/debounce/debounce.test.ts | 18 +- .../angular/directives/fixed_scroll.js | 8 +- .../angular/directives/histogram.tsx | 10 +- .../application/angular/directives/index.js | 6 +- .../public/application/angular/discover.js | 82 +- .../public/application/angular/doc.ts | 4 +- .../angular/doc_table/actions/columns.ts | 4 +- .../components/table_header/table_header.tsx | 2 +- .../table_header/table_header_column.tsx | 8 +- .../angular/doc_table/components/table_row.ts | 6 +- .../angular/doc_table/doc_table.ts | 2 +- .../angular/doc_table/infinite_scroll.ts | 6 +- .../angular/doc_table/lib/get_sort.test.ts | 22 +- .../angular/doc_table/lib/get_sort.ts | 4 +- .../angular/helpers/point_series.ts | 6 +- .../application/angular/response_handler.js | 4 +- .../application/components/doc/doc.test.tsx | 2 +- .../hits_counter/hits_counter.test.tsx | 8 +- .../sidebar/change_indexpattern.tsx | 4 +- .../sidebar/discover_field.test.tsx | 8 +- .../sidebar/discover_field_search.tsx | 6 +- .../sidebar/discover_index_pattern.test.tsx | 11 +- .../sidebar/discover_index_pattern.tsx | 6 +- .../sidebar/discover_sidebar.test.tsx | 12 +- .../components/sidebar/discover_sidebar.tsx | 2 +- .../sidebar/lib/field_calculator.js | 25 +- .../sidebar/lib/field_calculator.test.ts | 58 +- .../sidebar/lib/field_filter.test.ts | 12 +- .../lib/get_index_pattern_field_list.ts | 2 +- .../components/sidebar/lib/get_warnings.ts | 2 +- .../sidebar/lib/group_fields.test.ts | 4 +- .../components/sidebar/lib/group_fields.tsx | 4 +- .../components/table/table.test.tsx | 10 +- .../application/components/table/table.tsx | 8 +- .../components/table/table_helper.tsx | 2 +- .../timechart_header.test.tsx | 10 +- .../timechart_header/timechart_header.tsx | 4 +- .../components/top_nav/open_search_panel.js | 2 +- .../doc_views/doc_views_helpers.tsx | 4 +- .../doc_views/doc_views_registry.ts | 2 +- .../embeddable/search_embeddable.ts | 4 +- .../helpers/get_index_pattern_id.ts | 2 +- .../discover/public/get_inner_angular.ts | 10 +- .../components/panel_options_menu/index.tsx | 2 +- .../public/lib/containers/container.ts | 10 +- .../lib/embeddables/embeddable.test.tsx | 4 +- .../embeddable_factory_renderer.tsx | 2 +- .../lib/panel/embeddable_panel.test.tsx | 2 +- .../public/lib/panel/embeddable_panel.tsx | 8 +- .../add_panel/add_panel_flyout.test.tsx | 4 +- .../add_panel/add_panel_flyout.tsx | 11 +- .../saved_object_finder_create_new.test.tsx | 16 +- .../customize_panel_action.test.ts | 2 +- .../customize_title/customize_panel_modal.tsx | 4 +- .../lib/panel/panel_header/panel_header.tsx | 4 +- .../panel/panel_header/panel_options_menu.tsx | 4 +- .../actions/get_message_modal.tsx | 2 +- .../actions/send_message_action.tsx | 2 +- .../contact_card/contact_card_embeddable.tsx | 2 +- .../contact_card_embeddable_factory.tsx | 2 +- .../contact_card/contact_card_initializer.tsx | 4 +- .../hello_world_container_component.tsx | 4 +- src/plugins/embeddable/public/plugin.test.ts | 6 +- src/plugins/embeddable/public/plugin.tsx | 4 +- .../embeddable/public/tests/container.test.ts | 32 +- .../public/tests/explicit_input.test.ts | 2 +- .../embeddable/public/tests/helpers.ts | 2 +- .../components/with_privileges.tsx | 4 +- .../helpers/enzyme_helpers.tsx | 6 +- .../helpers/router_helpers.tsx | 4 +- .../test_utils_temp/lib/utils.ts | 2 +- .../test_utils_temp/testbed/testbed.ts | 20 +- .../components/cron_editor/cron_daily.js | 4 +- .../components/cron_editor/cron_editor.js | 16 +- .../components/cron_editor/cron_hourly.js | 2 +- .../components/cron_editor/cron_monthly.js | 6 +- .../components/cron_editor/cron_weekly.js | 6 +- .../components/cron_editor/cron_yearly.js | 8 +- .../elasticsearch_sql_highlight_rules.ts | 2 +- .../lexer_rules/x_json_highlight_rules.ts | 2 +- .../console_lang/ace/modes/x_json/x_json.ts | 6 +- .../json_xjson_translation_tools.test.ts | 8 +- .../indices/validate/validate_index.test.ts | 2 +- .../public/request/request.test.js | 4 +- .../components/fields/combobox_field.tsx | 4 +- .../components/fields/json_editor_field.tsx | 2 +- .../components/fields/multi_select_field.tsx | 2 +- .../forms/components/fields/select_field.tsx | 2 +- .../components/fields/super_select_field.tsx | 2 +- .../static/forms/helpers/de_serializers.ts | 4 +- .../static/forms/helpers/serializers.ts | 2 +- .../components/form_data_provider.test.tsx | 6 +- .../components/form_data_provider.ts | 2 +- .../hook_form_lib/components/use_array.ts | 6 +- .../hook_form_lib/components/use_field.tsx | 2 +- .../components/use_multi_fields.tsx | 2 +- .../forms/hook_form_lib/form_context.tsx | 2 +- .../forms/hook_form_lib/hooks/use_field.ts | 14 +- .../forms/hook_form_lib/hooks/use_form.ts | 36 +- .../static/forms/hook_form_lib/lib/subject.ts | 2 +- .../expressions/common/execution/container.ts | 6 +- .../common/execution/execution.test.ts | 4 +- .../expressions/common/execution/execution.ts | 8 +- .../expressions/common/executor/container.ts | 10 +- .../common/executor/executor.test.ts | 4 +- .../common/expression_functions/specs/font.ts | 6 +- .../expression_functions/specs/tests/utils.ts | 2 +- .../expression_types/expression_type.test.ts | 4 +- .../common/expression_types/specs/boolean.ts | 4 +- .../expression_types/specs/datatable.ts | 16 +- .../specs/kibana_datatable.ts | 2 +- .../common/expression_types/specs/num.ts | 6 +- .../common/expression_types/specs/number.ts | 4 +- .../common/expression_types/specs/shape.ts | 2 +- .../common/expression_types/specs/string.ts | 4 +- .../expression_functions/sleep.ts | 2 +- .../expressions/common/util/get_by_alias.ts | 2 +- src/plugins/expressions/public/loader.ts | 6 +- src/plugins/expressions/public/mocks.tsx | 2 +- src/plugins/expressions/public/plugin.ts | 2 +- .../public/react_expression_renderer.test.tsx | 2 +- .../public/react_expression_renderer.tsx | 8 +- src/plugins/expressions/public/render.test.ts | 4 +- src/plugins/expressions/public/render.ts | 6 +- src/plugins/expressions/server/legacy.ts | 2 +- .../components/feature_directory.js | 8 +- .../public/application/components/home.js | 6 +- .../application/components/home.test.js | 6 +- .../public/application/components/home_app.js | 4 +- .../components/recently_accessed.test.js | 2 +- .../components/sample_data_set_cards.js | 28 +- .../sample_data_view_data_button.js | 2 +- .../sample_data_view_data_button.test.js | 2 +- .../components/tutorial/instruction.js | 4 +- .../components/tutorial/instruction_set.js | 8 +- .../components/tutorial/number_parameter.js | 2 +- .../components/tutorial/parameter_form.js | 2 +- .../tutorial/saved_objects_installer.js | 4 +- .../tutorial/saved_objects_installer.test.js | 4 +- .../components/tutorial/string_parameter.js | 2 +- .../components/tutorial/tutorial.js | 20 +- .../components/tutorial/tutorial.test.js | 10 +- .../components/tutorial_directory.js | 12 +- .../home/public/application/load_tutorials.js | 2 +- src/plugins/home/public/plugin.ts | 2 +- .../feature_catalogue_registry.ts | 2 +- .../sample_data/data_sets/ecommerce/index.ts | 2 +- .../sample_data/data_sets/flights/index.ts | 2 +- .../sample_data/data_sets/logs/index.ts | 2 +- .../sample_data/lib/create_index_name.ts | 2 +- .../services/sample_data/lib/load_data.ts | 2 +- .../sample_data/lib/sample_dataset_schema.ts | 20 +- .../services/sample_data/routes/install.ts | 2 +- .../services/sample_data/routes/list.ts | 4 +- .../sample_data/sample_data_registry.ts | 8 +- .../services/sample_data/usage/usage.ts | 2 +- .../services/tutorials/lib/tutorial_schema.ts | 28 +- .../services/tutorials/tutorials_registry.ts | 4 +- .../create_button/create_button.tsx | 2 +- .../empty_state/empty_state.test.tsx | 4 +- .../components/indices_list/indices_list.tsx | 2 +- .../step_index_pattern.test.tsx | 10 +- .../step_index_pattern/step_index_pattern.tsx | 2 +- .../step_time_field/step_time_field.tsx | 2 +- .../create_index_pattern_wizard.tsx | 8 +- .../lib/contains_illegal_characters.ts | 2 +- .../lib/ensure_minimum_time.test.ts | 14 +- .../lib/ensure_minimum_time.ts | 2 +- .../lib/extract_time_fields.ts | 4 +- .../lib/get_indices.test.ts | 6 +- .../lib/get_matched_indices.ts | 2 +- .../edit_index_pattern/edit_index_pattern.tsx | 12 +- .../edit_index_pattern_state_container.ts | 2 +- .../indexed_fields_table.test.tsx | 6 +- .../indexed_fields_table.tsx | 8 +- .../scripted_fields_table.tsx | 6 +- .../components/add_filter/add_filter.tsx | 2 +- .../components/table/table.test.tsx | 35 +- .../source_filters_table.tsx | 6 +- .../edit_index_pattern/tabs/tabs.tsx | 12 +- .../edit_index_pattern/tabs/utils.ts | 8 +- .../editors/color/color.tsx | 8 +- .../field_format_editor/editors/date/date.tsx | 10 +- .../editors/date_nanos/date_nanos.tsx | 2 +- .../editors/default/default.tsx | 2 +- .../editors/duration/duration.tsx | 6 +- .../editors/number/number.tsx | 2 +- .../editors/static_lookup/static_lookup.tsx | 6 +- .../editors/string/string.tsx | 2 +- .../editors/truncate/truncate.tsx | 2 +- .../field_format_editor/editors/url/url.tsx | 12 +- .../components/scripting_help/test_script.tsx | 8 +- .../field_editor/field_editor.test.tsx | 18 +- .../components/field_editor/field_editor.tsx | 22 +- .../index_pattern_table.tsx | 2 +- .../public/components/utils.ts | 4 +- .../index_pattern_management/public/plugin.ts | 6 +- .../public/service/creation/manager.ts | 6 +- .../field_format_editors.ts | 2 +- .../public/service/list/manager.ts | 4 +- .../public/components/editor/controls_tab.tsx | 2 +- .../public/components/editor/field_select.tsx | 2 +- .../components/editor/list_control_editor.tsx | 8 +- .../editor/range_control_editor.tsx | 4 +- .../components/vis/input_control_vis.tsx | 2 +- .../public/components/vis/list_control.tsx | 4 +- .../public/control/control.test.ts | 14 +- .../public/control/control.ts | 4 +- .../filter_manager/filter_manager.test.ts | 10 +- .../control/filter_manager/filter_manager.ts | 2 +- .../phrase_filter_manager.test.ts | 18 +- .../filter_manager/phrase_filter_manager.ts | 8 +- .../range_filter_manager.test.ts | 12 +- .../public/control/list_control_factory.ts | 2 +- .../public/lineage/lineage_map.ts | 4 +- .../public/lineage/parent_candidates.ts | 2 +- .../public/test_utils/update_component.ts | 2 +- .../public/vis_controller.tsx | 30 +- .../common/adapters/data/data_adapter.ts | 2 +- .../adapters/request/request_adapter.test.ts | 2 +- src/plugins/inspector/public/plugin.tsx | 2 +- .../inspector/public/ui/inspector_panel.tsx | 2 +- .../public/ui/inspector_view_chooser.tsx | 2 +- .../inspector/public/view_registry.test.ts | 6 +- src/plugins/inspector/public/view_registry.ts | 2 +- .../data/components/download_options.tsx | 2 +- .../public/views/data/lib/export_csv.ts | 10 +- .../components/details/req_details_stats.tsx | 2 +- .../public/angular/angular_config.tsx | 4 +- .../public/angular/kbn_top_nav.js | 8 +- .../kibana_legacy/public/angular/promises.js | 34 +- .../public/angular/watch_multi.js | 18 +- .../navigate_to_legacy_kibana_url.ts | 2 +- .../public/navigate_to_default_app.ts | 2 +- .../public/notify/lib/format_msg.ts | 2 +- .../notify/toasts/toast_notifications.ts | 2 +- .../kibana_legacy/public/paginate/paginate.js | 20 +- src/plugins/kibana_legacy/public/plugin.ts | 4 +- .../public/utils/kbn_accessible_click.js | 6 +- .../kibana_legacy/public/utils/private.js | 14 +- .../utils/register_listen_event_listener.js | 4 +- .../public/adapters/ui_to_react_component.ts | 2 +- .../kibana_react/public/code_editor/index.tsx | 2 +- .../kibana_react/public/context/context.tsx | 5 +- .../public/field_icon/field_icon.test.tsx | 2 +- .../public/markdown/markdown.test.tsx | 37 +- .../kibana_react/public/markdown/markdown.tsx | 4 +- .../notifications/create_notifications.tsx | 6 +- .../containers/panel_container.tsx | 2 +- .../public/split_panel/split_panel.test.tsx | 5 +- .../table_list_view/table_list_view.tsx | 4 +- .../application_usage/index.test.ts | 4 +- .../server/collectors/find_all.test.ts | 2 +- .../server/collectors/kibana/index.test.ts | 2 +- .../kibana/kibana_usage_collector.ts | 2 +- .../collectors/management/index.test.ts | 2 +- .../server/collectors/ops_stats/index.test.ts | 2 +- .../ops_stats/ops_stats_collector.ts | 2 +- .../server/collectors/ui_metric/index.test.ts | 2 +- .../server/index.test.ts | 4 +- .../kibana_usage_collection/server/plugin.ts | 4 +- .../common/calculate_object_hash.ts | 4 +- .../common/create_getter_setter.ts | 2 +- src/plugins/kibana_utils/common/defer.test.ts | 2 +- ...t_until_changed_with_initial_value.test.ts | 2 +- ...stinct_until_changed_with_initial_value.ts | 2 +- src/plugins/kibana_utils/common/of.test.ts | 4 +- .../create_state_container.test.ts | 2 +- .../create_state_container.ts | 6 +- ...ate_state_container_react_helpers.test.tsx | 18 +- .../create_state_container_react_helpers.ts | 2 +- .../demos/state_containers/todomvc.ts | 22 +- .../kibana_utils/demos/state_sync/url.ts | 2 +- .../core/create_start_service_getter.test.ts | 8 +- .../core/create_start_service_getter.ts | 2 +- .../kibana_utils/public/errors/errors.test.ts | 2 +- .../field_wildcard/field_wildcard.test.ts | 22 +- .../public/field_wildcard/field_wildcard.ts | 7 +- .../resize_checker/resize_checker.test.ts | 22 +- .../state_management/url/format.test.ts | 2 +- .../state_management/url/hash_unhash_url.ts | 2 +- .../state_management/url/kbn_url_storage.ts | 2 +- .../url/kbn_url_tracker.test.ts | 4 +- .../state_management/url/kbn_url_tracker.ts | 6 +- .../state_management/utils/diff_object.ts | 8 +- .../public/state_sync/state_sync.test.ts | 2 +- .../public/state_sync/state_sync.ts | 8 +- .../create_kbn_url_state_storage.test.ts | 12 +- .../create_kbn_url_state_storage.ts | 6 +- .../public/storage/__tests__/storage.js | 34 +- .../hashed_item_store/hashed_item_store.ts | 2 +- .../management_sidebar_nav.tsx | 10 +- .../management/public/legacy/section.js | 8 +- .../management/public/legacy/section.test.js | 10 +- .../public/legacy/sections_register.js | 2 +- .../management/public/management_app.tsx | 2 +- .../management/public/management_section.ts | 4 +- .../management/public/management_service.ts | 4 +- .../public/__tests__/map/kibana_map.js | 68 +- .../public/__tests__/map/service_settings.js | 36 +- .../maps_legacy/public/kibana_services.js | 6 +- .../public/map/base_maps_visualization.js | 6 +- .../public/map/convert_to_geojson.js | 4 +- .../maps_legacy/public/map/kibana_map.js | 56 +- .../maps_legacy/public/map/map_messages.js | 4 +- .../public/map/service_settings.js | 14 +- .../top_nav_menu/create_top_nav_menu.tsx | 2 +- .../components/newsfeed_header_nav_button.tsx | 2 +- src/plugins/newsfeed/public/lib/api.test.ts | 22 +- src/plugins/newsfeed/public/lib/api.ts | 4 +- src/plugins/newsfeed/public/plugin.tsx | 2 +- .../__tests__/region_map_visualization.js | 30 +- .../region_map/public/choropleth_layer.js | 34 +- .../public/components/region_map_options.tsx | 2 +- .../region_map/public/region_map_type.js | 8 +- .../public/region_map_visualization.js | 8 +- .../finder/saved_object_finder.test.tsx | 59 +- .../public/finder/saved_object_finder.tsx | 30 +- .../saved_object_save_modal_origin.tsx | 2 +- .../helpers/find_object_by_title.ts | 4 +- .../public/saved_object/saved_object.test.ts | 70 +- .../saved_object/saved_object_loader.ts | 16 +- .../public/lib/create_field_list.ts | 2 +- .../public/lib/extract_export_details.ts | 6 +- .../public/lib/import_legacy_file.ts | 2 +- .../public/lib/process_import_response.ts | 4 +- .../public/lib/resolve_import_errors.ts | 12 +- .../public/lib/resolve_saved_objects.ts | 14 +- .../object_view/components/field.tsx | 6 +- .../object_view/components/form.tsx | 6 +- .../object_view/saved_object_view.tsx | 2 +- .../objects_table/components/flyout.test.tsx | 34 +- .../objects_table/components/flyout.tsx | 22 +- .../components/relationships.test.tsx | 10 +- .../components/relationships.tsx | 2 +- .../objects_table/components/table.tsx | 14 +- .../saved_objects_table.test.tsx | 34 +- .../objects_table/saved_objects_table.tsx | 22 +- .../saved_objects_table_page.tsx | 4 +- .../saved_objects_management/public/plugin.ts | 2 +- .../public/services/action_service.ts | 4 +- .../public/services/types.ts | 2 +- .../server/lib/find_all.test.ts | 2 +- .../server/lib/find_relationships.test.ts | 2 +- .../server/lib/find_relationships.ts | 10 +- .../server/routes/find.ts | 8 +- .../server/routes/get_allowed_types.ts | 2 +- .../server/routes/scroll_export.ts | 2 +- .../public/components/share_context_menu.tsx | 2 +- .../public/components/url_panel_content.tsx | 4 +- .../public/services/share_menu_registry.ts | 2 +- .../services/short_url_redirect_app.test.ts | 2 +- src/plugins/share/server/routes/get.ts | 2 +- src/plugins/share/server/routes/goto.ts | 4 +- .../routes/lib/short_url_assert_valid.test.ts | 2 +- .../server/routes/lib/short_url_lookup.ts | 5 +- .../share/server/routes/shorten_url.ts | 2 +- .../saved_objects/kibana_app_migration.ts | 2 +- .../get_telemetry_opt_in.test.ts | 8 +- .../public/components/opt_in_banner.test.tsx | 4 +- .../opted_in_notice_banner.test.tsx | 2 +- src/plugins/telemetry/public/mocks.ts | 2 +- .../public/services/telemetry_sender.ts | 2 +- .../collectors/usage/ensure_deep_object.ts | 2 +- .../usage/telemetry_usage_collector.test.ts | 4 +- src/plugins/telemetry/server/fetcher.ts | 4 +- src/plugins/telemetry/server/plugin.ts | 2 +- .../server/routes/telemetry_opt_in.ts | 4 +- .../server/routes/telemetry_opt_in_stats.ts | 4 +- .../server/routes/telemetry_usage_stats.ts | 2 +- .../__tests__/get_local_stats.js | 2 +- .../telemetry_collection/get_local_license.ts | 2 +- .../telemetry_collection/get_local_stats.ts | 2 +- .../server/plugin.ts | 2 +- .../telemetry_management_section.tsx | 2 +- src/plugins/testbed/server/index.ts | 2 +- .../coordinate_maps_visualization.js | 30 +- .../public/__tests__/geohash_layer.js | 16 +- src/plugins/tile_map/public/css_filters.js | 8 +- src/plugins/tile_map/public/geohash_layer.js | 4 +- .../tile_map/public/markers/geohash_grid.js | 2 +- .../tile_map/public/markers/heatmap.js | 16 +- .../tile_map/public/markers/scaled_circles.js | 33 +- src/plugins/tile_map/public/tile_map_type.js | 4 +- .../tile_map/public/tile_map_visualization.js | 8 +- .../build_eui_context_menu_panels.tsx | 2 +- .../public/service/ui_actions_service.ts | 8 +- .../tests/execute_trigger_actions.test.ts | 2 +- src/plugins/usage_collection/public/plugin.ts | 2 +- .../public/services/application_usage.ts | 4 +- .../server/collector/collector_set.test.ts | 2 +- .../server/collector/collector_set.ts | 4 +- .../agg_filters/agg_type_field_filters.ts | 4 +- .../public/agg_filters/agg_type_filters.ts | 4 +- .../public/components/agg.test.tsx | 15 +- .../public/components/agg.tsx | 2 +- .../public/components/agg_add.tsx | 4 +- .../public/components/agg_group.tsx | 6 +- .../public/components/agg_group_helper.tsx | 4 +- .../public/components/agg_params.tsx | 8 +- .../public/components/agg_params_helper.ts | 6 +- .../public/components/agg_select.tsx | 4 +- .../components/controls/auto_precision.tsx | 2 +- .../controls/components/from_to_list.tsx | 4 +- .../controls/components/input_list.tsx | 6 +- .../controls/components/mask_list.tsx | 2 +- .../number_list/number_list.test.tsx | 12 +- .../components/number_list/number_list.tsx | 6 +- .../components/number_list/range.test.ts | 8 +- .../controls/components/number_list/utils.ts | 2 +- .../components/simple_number_list.tsx | 6 +- .../components/controls/date_ranges.test.tsx | 2 +- .../components/controls/date_ranges.tsx | 16 +- .../components/controls/extended_bounds.tsx | 4 +- .../public/components/controls/field.tsx | 2 +- .../public/components/controls/filter.tsx | 2 +- .../public/components/controls/filters.tsx | 13 +- .../components/controls/include_exclude.tsx | 6 +- .../public/components/controls/metric_agg.tsx | 4 +- .../public/components/controls/order.tsx | 2 +- .../public/components/controls/order_by.tsx | 2 +- .../public/components/controls/ranges.tsx | 16 +- .../components/controls/rows_or_columns.tsx | 2 +- .../public/components/controls/size.tsx | 2 +- .../public/components/controls/string.tsx | 2 +- .../public/components/controls/switch.tsx | 2 +- .../components/controls/top_aggregate.tsx | 6 +- .../components/controls/use_geocentroid.tsx | 2 +- .../components/controls/utils/agg_utils.ts | 4 +- .../utils/strings/comma_separated_list.ts | 2 +- .../public/components/sidebar/controls.tsx | 2 +- .../public/components/sidebar/data_tab.tsx | 4 +- .../public/components/sidebar/sidebar.tsx | 10 +- .../components/sidebar/sidebar_title.tsx | 2 +- .../components/sidebar/state/actions.ts | 6 +- .../sidebar/state/editor_form_state.ts | 6 +- .../components/sidebar/state/reducers.ts | 12 +- .../public/default_editor.tsx | 2 +- .../vis_default_editor/public/schemas.ts | 4 +- .../vis_default_editor/public/utils.ts | 4 +- .../components/metric_vis_component.test.tsx | 6 +- .../public/components/metric_vis_options.tsx | 2 +- .../public/agg_table/agg_table.js | 44 +- .../public/agg_table/agg_table_group.js | 6 +- .../public/components/table_vis_options.tsx | 2 +- .../public/get_inner_angular.ts | 2 +- .../public/paginated_table/paginated_table.js | 4 +- .../paginated_table/paginated_table.test.ts | 338 +---- .../public/paginated_table/rows.js | 14 +- .../public/table_vis_controller.js | 4 +- .../public/components/tag_cloud.js | 22 +- .../components/tag_cloud_visualization.js | 2 +- .../common/lib/calculate_interval.test.ts | 4 +- .../common/lib/to_milliseconds.ts | 2 +- .../public/components/panel.tsx | 32 +- .../components/timelion_expression_input.tsx | 2 +- .../timelion_expression_input_helpers.ts | 16 +- .../public/components/timelion_interval.tsx | 4 +- .../public/helpers/arg_value_suggestions.ts | 18 +- .../public/helpers/tick_formatters.test.ts | 72 +- .../public/helpers/tick_generator.test.ts | 14 +- .../helpers/timelion_request_handler.ts | 2 +- .../server/fit_functions/average.js | 4 +- .../server/fit_functions/average.test.js | 12 +- .../server/fit_functions/carry.js | 2 +- .../server/fit_functions/carry.test.js | 10 +- .../server/fit_functions/nearest.js | 2 +- .../server/fit_functions/scale.js | 2 +- .../server/handlers/chain_runner.js | 35 +- .../server/handlers/lib/arg_type.js | 5 +- .../server/handlers/lib/index_arguments.js | 4 +- .../server/handlers/lib/parse_sheet.js | 2 +- .../server/handlers/lib/parse_sheet.test.js | 8 +- .../server/handlers/lib/preprocess_chain.js | 2 +- .../handlers/lib/reposition_arguments.js | 4 +- .../server/handlers/lib/tl_config.js | 10 +- .../server/handlers/lib/validate_arg.js | 2 +- .../vis_type_timelion/server/lib/alter.js | 6 +- .../server/lib/build_target.js | 2 +- .../server/lib/classes/datasource.js | 10 +- .../server/lib/classes/timelion_function.js | 8 +- .../server/lib/config_manager.ts | 4 +- .../server/lib/functions_md.js | 18 +- .../server/lib/get_namespaced_settings.js | 4 +- .../server/lib/load_functions.js | 10 +- .../server/lib/process_function_definition.js | 4 +- .../vis_type_timelion/server/lib/reduce.js | 12 +- .../server/lib/unzip_pairs.js | 4 +- .../server/routes/functions.ts | 2 +- .../server/routes/validate_es.ts | 2 +- .../server/series_functions/abs.js | 4 +- .../server/series_functions/abs.test.js | 10 +- .../aggregate/aggregate.test.js | 14 +- .../server/series_functions/aggregate/avg.js | 2 +- .../series_functions/aggregate/cardinality.js | 2 +- .../series_functions/aggregate/first.js | 2 +- .../series_functions/aggregate/index.js | 2 +- .../server/series_functions/aggregate/last.js | 2 +- .../server/series_functions/aggregate/max.js | 2 +- .../server/series_functions/aggregate/min.js | 2 +- .../server/series_functions/aggregate/sum.js | 2 +- .../server/series_functions/bars.js | 2 +- .../server/series_functions/bars.test.js | 12 +- .../server/series_functions/color.js | 2 +- .../server/series_functions/color.test.js | 8 +- .../server/series_functions/condition.js | 6 +- .../server/series_functions/condition.test.js | 52 +- .../server/series_functions/cusum.js | 4 +- .../server/series_functions/cusum.test.js | 2 +- .../server/series_functions/derivative.js | 4 +- .../series_functions/derivative.test.js | 2 +- .../server/series_functions/divide.js | 2 +- .../server/series_functions/divide.test.js | 2 +- .../server/series_functions/es/es.test.js | 8 +- .../server/series_functions/es/index.js | 4 +- .../series_functions/es/lib/agg_body.js | 2 +- .../es/lib/agg_response_to_series_list.js | 16 +- .../series_functions/es/lib/build_request.js | 4 +- .../es/lib/create_date_agg.js | 4 +- .../server/series_functions/first.js | 2 +- .../server/series_functions/first.test.js | 6 +- .../server/series_functions/fit.js | 6 +- .../server/series_functions/fit.test.js | 46 +- .../series_functions/fixtures/series_list.js | 2 +- .../series_functions/fixtures/tl_config.js | 6 +- .../server/series_functions/graphite.js | 10 +- .../server/series_functions/graphite.test.js | 16 +- .../series_functions/helpers/get_series.js | 2 +- .../helpers/get_series_list.js | 2 +- .../helpers/get_single_series_list.js | 2 +- .../helpers/invoke_series_fn.js | 4 +- .../server/series_functions/hide.js | 2 +- .../server/series_functions/hide.test.js | 8 +- .../server/series_functions/holt/index.js | 2 +- .../server/series_functions/holt/lib/tes.js | 6 +- .../server/series_functions/label.js | 2 +- .../server/series_functions/label.test.js | 6 +- .../server/series_functions/legend.js | 2 +- .../server/series_functions/legend.test.js | 8 +- .../server/series_functions/lines.js | 2 +- .../server/series_functions/lines.test.js | 4 +- .../server/series_functions/log.js | 4 +- .../server/series_functions/log.test.js | 2 +- .../server/series_functions/max.js | 2 +- .../server/series_functions/max.test.js | 2 +- .../server/series_functions/min.js | 2 +- .../server/series_functions/min.test.js | 2 +- .../server/series_functions/movingaverage.js | 12 +- .../series_functions/movingaverage.test.js | 10 +- .../server/series_functions/movingstd.js | 14 +- .../server/series_functions/movingstd.test.js | 2 +- .../server/series_functions/multiply.js | 2 +- .../server/series_functions/multiply.test.js | 2 +- .../server/series_functions/points.js | 4 +- .../server/series_functions/points.test.js | 16 +- .../server/series_functions/precision.js | 4 +- .../server/series_functions/precision.test.js | 4 +- .../server/series_functions/props.js | 4 +- .../server/series_functions/quandl.js | 6 +- .../server/series_functions/quandl.test.js | 28 +- .../server/series_functions/range.js | 4 +- .../server/series_functions/range.test.js | 2 +- .../server/series_functions/scale_interval.js | 4 +- .../series_functions/scale_interval.test.js | 2 +- .../server/series_functions/static.js | 4 +- .../server/series_functions/static.test.js | 6 +- .../server/series_functions/subtract.js | 2 +- .../server/series_functions/sum.js | 2 +- .../server/series_functions/sum.test.js | 2 +- .../server/series_functions/title.js | 2 +- .../server/series_functions/title.test.js | 4 +- .../server/series_functions/trend/index.js | 8 +- .../series_functions/trend/lib/regress.js | 26 +- .../server/series_functions/trim.js | 6 +- .../server/series_functions/trim.test.js | 10 +- .../server/series_functions/worldbank.js | 10 +- .../series_functions/worldbank_indicators.js | 6 +- .../server/series_functions/yaxis.js | 4 +- .../server/series_functions/yaxis.test.js | 32 +- .../common/calculate_label.js | 2 +- .../common/extract_index_patterns.js | 4 +- .../common/get_last_value.js | 2 +- .../common/to_percentile_number.js | 2 +- .../components/add_delete_buttons.test.js | 15 +- .../application/components/aggs/agg_select.js | 12 +- .../application/components/aggs/aggs.js | 2 +- .../components/aggs/calculation.js | 2 +- .../application/components/aggs/derivative.js | 2 +- .../components/aggs/filter_ratio.js | 2 +- .../application/components/aggs/math.js | 2 +- .../components/aggs/metric_select.js | 14 +- .../components/aggs/moving_average.js | 2 +- .../application/components/aggs/percentile.js | 2 +- .../aggs/percentile_rank/multi_value_row.js | 2 +- .../aggs/percentile_rank/percentile_rank.js | 4 +- .../percentile_rank/percentile_rank_values.js | 2 +- .../components/aggs/percentile_ui.js | 6 +- .../components/aggs/positive_only.js | 2 +- .../components/aggs/positive_rate.js | 4 +- .../components/aggs/serial_diff.js | 2 +- .../application/components/aggs/series_agg.js | 2 +- .../application/components/aggs/static.js | 2 +- .../components/aggs/std_deviation.js | 4 +- .../components/aggs/std_sibling.js | 4 +- .../application/components/aggs/top_hit.js | 8 +- .../application/components/aggs/vars.js | 4 +- .../components/annotations_editor.js | 6 +- .../application/components/color_picker.js | 2 +- .../components/color_picker.test.js | 5 +- .../application/components/color_rules.js | 6 +- .../components/color_rules.test.js | 5 +- .../components/custom_color_picker.js | 4 +- .../components/data_format_picker.js | 14 +- .../components/icon_select/icon_select.js | 2 +- .../application/components/index_pattern.js | 2 +- .../components/lib/calculate_siblings.js | 4 +- .../application/components/lib/charts.js | 2 +- .../components/lib/collection_actions.js | 4 +- .../components/lib/convert_series_to_vars.js | 10 +- .../components/lib/create_change_handler.js | 2 +- .../components/lib/create_number_handler.js | 4 +- .../components/lib/create_select_handler.js | 4 +- .../components/lib/create_text_handler.js | 4 +- .../components/lib/create_xaxis_formatter.js | 2 +- .../application/components/lib/durations.js | 2 +- .../components/lib/get_interval.js | 6 +- .../components/lib/re_id_series.js | 14 +- .../components/lib/series_change_handler.js | 2 +- .../application/components/lib/stacked.js | 2 +- .../components/lib/tick_formatter.js | 2 +- .../components/lib/tick_formatter.test.js | 10 +- .../application/components/markdown_editor.js | 8 +- .../application/components/panel_config.js | 4 +- .../components/panel_config/gauge.js | 4 +- .../components/panel_config/gauge.test.js | 5 +- .../components/panel_config/markdown.js | 6 +- .../components/panel_config/metric.js | 2 +- .../components/panel_config/table.js | 6 +- .../components/panel_config/timeseries.js | 8 +- .../components/panel_config/top_n.js | 2 +- .../public/application/components/series.js | 8 +- .../application/components/series_config.js | 4 +- .../application/components/series_editor.js | 6 +- .../components/splits/everything.js | 2 +- .../application/components/splits/filter.js | 4 +- .../components/splits/filter_items.js | 6 +- .../application/components/splits/filters.js | 2 +- .../components/splits/group_by_select.js | 4 +- .../application/components/splits/terms.js | 2 +- .../components/splits/unsupported_split.js | 2 +- .../application/components/vis_editor.js | 8 +- .../components/vis_editor_visualization.js | 10 +- .../application/components/vis_picker.js | 6 +- .../components/vis_types/gauge/series.test.js | 5 +- .../components/vis_types/gauge/vis.js | 8 +- .../components/vis_types/markdown/vis.js | 2 +- .../vis_types/metric/series.test.js | 10 +- .../components/vis_types/metric/vis.js | 8 +- .../components/vis_types/table/config.js | 4 +- .../components/vis_types/table/vis.js | 14 +- .../components/vis_types/timeseries/config.js | 12 +- .../components/vis_types/timeseries/series.js | 2 +- .../components/vis_types/timeseries/vis.js | 20 +- .../components/vis_types/top_n/series.js | 2 +- .../components/vis_types/top_n/vis.js | 12 +- .../application/components/vis_with_splits.js | 12 +- .../public/application/components/yes_no.js | 2 +- .../application/components/yes_no.test.js | 10 +- .../application/lib/create_brush_handler.js | 2 +- .../lib/create_brush_handler.test.js | 2 +- .../public/application/lib/fetch_fields.js | 2 +- .../public/application/lib/set_is_reversed.js | 4 +- .../visualizations/lib/get_value_by.js | 2 +- .../application/visualizations/views/gauge.js | 8 +- .../visualizations/views/gauge_vis.js | 4 +- .../visualizations/views/metric.js | 8 +- .../visualizations/views/timeseries/index.js | 4 +- .../views/timeseries/utils/stack_format.js | 2 +- .../application/visualizations/views/top_n.js | 6 +- .../server/lib/get_fields.ts | 6 +- .../server/lib/get_vis_data.ts | 4 +- .../default_search_capabilities.js | 2 +- .../strategies/abstract_search_strategy.ts | 4 +- .../server/lib/vis_data/get_annotations.js | 2 +- .../server/lib/vis_data/get_panel_data.js | 2 +- .../server/lib/vis_data/get_series_data.js | 2 +- .../lib/vis_data/handle_error_response.js | 2 +- .../lib/vis_data/helpers/bucket_transform.js | 18 +- .../vis_data/helpers/bucket_transform.test.js | 4 +- .../lib/vis_data/helpers/get_active_series.js | 4 +- .../lib/vis_data/helpers/get_agg_value.js | 6 +- .../lib/vis_data/helpers/get_bucket_size.js | 2 +- .../lib/vis_data/helpers/get_buckets_path.js | 2 +- .../helpers/get_default_decoration.js | 2 +- .../lib/vis_data/helpers/get_index_pattern.js | 4 +- .../lib/vis_data/helpers/get_last_metric.js | 2 +- .../server/lib/vis_data/helpers/get_splits.js | 8 +- .../lib/vis_data/helpers/get_timerange.js | 4 +- .../vis_data/helpers/get_timerange_mode.js | 6 +- .../server/lib/vis_data/helpers/map_bucket.js | 2 +- .../lib/vis_data/helpers/parse_interval.js | 6 +- .../lib/vis_data/helpers/parse_settings.js | 2 +- .../server/lib/vis_data/helpers/timestamp.js | 2 +- .../lib/vis_data/helpers/unit_to_seconds.js | 8 +- .../server/lib/vis_data/offset_time.test.js | 14 +- .../annotations/date_histogram.js | 2 +- .../request_processors/annotations/query.js | 4 +- .../annotations/top_hits.js | 2 +- .../series/date_histogram.js | 2 +- .../series/date_histogram.test.js | 10 +- .../series/filter_ratios.js | 6 +- .../series/filter_ratios.test.js | 4 +- .../series/metric_buckets.js | 6 +- .../series/metric_buckets.test.js | 2 +- .../series/normalize_query.js | 2 +- .../series/normalize_query.test.js | 2 +- .../series/positive_rate.js | 6 +- .../series/positive_rate.test.js | 2 +- .../request_processors/series/query.js | 2 +- .../request_processors/series/query.test.js | 12 +- .../series/sibling_buckets.js | 6 +- .../series/sibling_buckets.test.js | 2 +- .../series/split_by_everything.js | 2 +- .../series/split_by_everything.test.js | 4 +- .../series/split_by_filter.js | 2 +- .../series/split_by_filter.test.js | 4 +- .../series/split_by_filters.js | 4 +- .../series/split_by_filters.test.js | 4 +- .../series/split_by_terms.js | 4 +- .../series/split_by_terms.test.js | 8 +- .../table/date_histogram.js | 6 +- .../request_processors/table/filter_ratios.js | 8 +- .../table/metric_buckets.js | 8 +- .../table/normalize_query.js | 2 +- .../table/normalize_query.test.js | 2 +- .../request_processors/table/pivot.js | 4 +- .../request_processors/table/positive_rate.js | 4 +- .../request_processors/table/query.js | 2 +- .../table/sibling_buckets.js | 8 +- .../table/split_by_everything.js | 6 +- .../table/split_by_terms.js | 6 +- .../annotations/buckets.js | 6 +- .../response_processors/annotations/filter.js | 6 +- .../response_processors/annotations/index.js | 2 +- .../response_processors/series/_series_agg.js | 20 +- .../series/drop_last_bucket.js | 4 +- .../response_processors/series/math.js | 20 +- .../response_processors/series/percentile.js | 8 +- .../series/percentile.test.js | 2 +- .../series/percentile_rank.js | 8 +- .../response_processors/series/series_agg.js | 8 +- .../series/series_agg.test.js | 2 +- .../series/std_deviation_bands.js | 4 +- .../series/std_deviation_bands.test.js | 2 +- .../series/std_deviation_sibling.js | 6 +- .../series/std_deviation_sibling.test.js | 2 +- .../response_processors/series/std_metric.js | 4 +- .../series/std_metric.test.js | 6 +- .../response_processors/series/std_sibling.js | 6 +- .../series/std_sibling.test.js | 4 +- .../response_processors/series/time_shift.js | 4 +- .../series/time_shift.test.js | 2 +- .../response_processors/table/_series_agg.js | 28 +- .../table/drop_last_bucket.js | 2 +- .../response_processors/table/math.js | 2 +- .../response_processors/table/percentile.js | 6 +- .../table/percentile_rank.js | 6 +- .../response_processors/table/series_agg.js | 4 +- .../response_processors/table/std_metric.js | 4 +- .../response_processors/table/std_sibling.js | 6 +- .../vis_data/series/handle_response_body.js | 4 +- .../lib/vis_data/table/process_bucket.js | 4 +- .../server/routes/post_vis_schema.ts | 2 +- .../server/saved_objects/tsvb_telemetry.ts | 2 +- .../validation_telemetry_service.ts | 2 +- .../public/components/vega_actions_menu.tsx | 2 +- .../public/data_model/ems_file_parser.js | 2 +- .../public/data_model/es_query_parser.js | 2 +- .../public/data_model/vega_parser.js | 6 +- .../public/data_model/vega_parser.test.js | 2 +- .../public/vega_view/vega_base_view.js | 9 +- .../public/vega_view/vega_map_view.js | 2 +- .../public/vega_view/vega_tooltip.js | 2 +- .../components/common/validation_wrapper.tsx | 4 +- .../options/heatmap/labels_panel.tsx | 2 +- .../components/options/metrics_axes/index.tsx | 8 +- .../metrics_axes/value_axes_panel.test.tsx | 20 +- .../options/metrics_axes/value_axes_panel.tsx | 4 +- .../options/metrics_axes/y_extents.test.tsx | 10 +- .../options/point_series/point_series.tsx | 2 +- .../mock_data/date_histogram/_columns.js | 12 +- .../mock_data/date_histogram/_rows.js | 8 +- .../date_histogram/_rows_series_with_holes.js | 4 +- .../mock_data/date_histogram/_series.js | 4 +- .../_series_monthly_interval.js | 4 +- .../mock_data/date_histogram/_series_neg.js | 4 +- .../date_histogram/_series_pos_neg.js | 4 +- .../date_histogram/_stacked_series.js | 4 +- .../fixtures/mock_data/filters/_columns.js | 12 +- .../fixtures/mock_data/filters/_rows.js | 12 +- .../fixtures/mock_data/filters/_series.js | 4 +- .../fixtures/mock_data/histogram/_columns.js | 12 +- .../fixtures/mock_data/histogram/_rows.js | 12 +- .../fixtures/mock_data/histogram/_series.js | 4 +- .../fixtures/mock_data/histogram/_slices.js | 2 +- .../mock_data/not_enough_data/_one_point.js | 4 +- .../fixtures/mock_data/range/_columns.js | 4 +- .../public/fixtures/mock_data/range/_rows.js | 4 +- .../fixtures/mock_data/range/_series.js | 4 +- .../mock_data/significant_terms/_columns.js | 20 +- .../mock_data/significant_terms/_rows.js | 20 +- .../mock_data/significant_terms/_series.js | 4 +- .../fixtures/mock_data/stacked/_stacked.js | 4 +- .../fixtures/mock_data/terms/_columns.js | 12 +- .../public/fixtures/mock_data/terms/_rows.js | 8 +- .../fixtures/mock_data/terms/_series.js | 4 +- .../mock_data/terms/_series_multiple.js | 6 +- .../vis_type_vislib/public/fixtures/mocks.js | 2 +- src/plugins/vis_type_vislib/public/plugin.ts | 4 +- .../vis_type_vislib/public/vis_controller.tsx | 2 +- .../components/labels/flatten_series.js | 5 +- .../vislib/components/labels/labels.test.js | 120 +- .../components/labels/truncate_labels.js | 2 +- .../vislib/components/labels/uniq_labels.js | 5 +- .../vislib/components/legend/legend.tsx | 10 +- .../vislib/components/legend/legend_item.tsx | 2 +- .../vislib/components/legend/pie_utils.ts | 12 +- .../_hierarchical_tooltip_formatter.js | 4 +- .../tooltip/_pointseries_tooltip_formatter.js | 5 +- .../_pointseries_tooltip_formatter.test.js | 11 +- .../components/tooltip/position_tooltip.js | 8 +- .../tooltip/position_tooltip.test.js | 62 +- .../vislib/components/tooltip/tooltip.js | 36 +- .../components/zero_injection/inject_zeros.js | 2 +- .../zero_injection/ordered_x_keys.js | 4 +- .../components/zero_injection/uniq_keys.js | 6 +- .../zero_injection/zero_fill_data_array.js | 2 +- .../zero_injection/zero_filled_array.js | 2 +- .../zero_injection/zero_injection.test.js | 118 +- .../build_hierarchical_data.test.ts | 4 +- .../hierarchical/build_hierarchical_data.ts | 4 +- .../helpers/point_series/_add_to_siri.test.ts | 10 +- .../point_series/_fake_x_aspect.test.ts | 4 +- .../helpers/point_series/_get_aspects.test.ts | 6 +- .../helpers/point_series/_get_aspects.ts | 4 +- .../helpers/point_series/_get_point.test.ts | 20 +- .../vislib/helpers/point_series/_get_point.ts | 2 +- .../helpers/point_series/_get_series.test.ts | 34 +- .../helpers/point_series/_get_series.ts | 2 +- .../helpers/point_series/_init_x_axis.test.ts | 22 +- .../helpers/point_series/_init_x_axis.ts | 2 +- .../helpers/point_series/_init_y_axis.test.ts | 14 +- .../point_series/_ordered_date_axis.test.ts | 14 +- .../helpers/point_series/point_series.test.ts | 16 +- .../public/vislib/lib/_error_handler.test.js | 16 +- .../public/vislib/lib/alerts.js | 28 +- .../public/vislib/lib/axis/axis.js | 51 +- .../public/vislib/lib/axis/axis.test.js | 24 +- .../public/vislib/lib/axis/axis_labels.js | 20 +- .../public/vislib/lib/axis/axis_scale.js | 8 +- .../public/vislib/lib/axis/axis_title.js | 15 +- .../public/vislib/lib/axis/axis_title.test.js | 59 +- .../public/vislib/lib/axis/time_ticks.js | 8 +- .../public/vislib/lib/axis/time_ticks.test.js | 2 +- .../public/vislib/lib/axis/x_axis.test.js | 62 +- .../public/vislib/lib/axis/y_axis.test.js | 110 +- .../public/vislib/lib/binder.ts | 2 +- .../public/vislib/lib/chart_grid.js | 14 +- .../public/vislib/lib/chart_title.js | 24 +- .../vis_type_vislib/public/vislib/lib/data.js | 63 +- .../public/vislib/lib/data.test.js | 44 +- .../public/vislib/lib/dispatch.js | 22 +- .../public/vislib/lib/handler.js | 27 +- .../public/vislib/lib/layout/layout.js | 18 +- .../vislib/lib/layout/layout_types.test.js | 6 +- .../layout/splits/column_chart/chart_split.js | 8 +- .../splits/column_chart/chart_title_split.js | 4 +- .../layout/splits/column_chart/splits.test.js | 56 +- .../splits/column_chart/x_axis_split.js | 4 +- .../splits/column_chart/y_axis_split.js | 4 +- .../layout/splits/gauge_chart/chart_split.js | 8 +- .../splits/gauge_chart/chart_title_split.js | 12 +- .../layout/splits/gauge_chart/splits.test.js | 32 +- .../layout/splits/pie_chart/chart_split.js | 8 +- .../splits/pie_chart/chart_title_split.js | 12 +- .../lib/layout/types/column_layout.test.js | 17 +- .../public/vislib/lib/types/point_series.js | 22 +- .../vislib/lib/types/point_series.test.js | 20 +- .../public/vislib/lib/vis_config.test.js | 26 +- .../public/vislib/response_handler.js | 6 +- .../public/vislib/response_handler.test.ts | 2 +- .../public/vislib/visualizations/_chart.js | 4 +- .../vislib/visualizations/gauge_chart.js | 6 +- .../vislib/visualizations/gauges/meter.js | 38 +- .../public/vislib/visualizations/pie_chart.js | 49 +- .../vislib/visualizations/point_series.js | 23 +- .../point_series/_point_series.js | 4 +- .../visualizations/point_series/area_chart.js | 30 +- .../point_series/column_chart.js | 10 +- .../point_series/heatmap_chart.js | 31 +- .../visualizations/point_series/line_chart.js | 8 +- .../vislib/visualizations/time_marker.js | 18 +- .../vislib/visualizations/time_marker.test.js | 54 +- .../vislib/visualizations/vis_types.test.js | 8 +- .../public/components/visualization.test.js | 6 +- .../components/visualization_chart.test.js | 2 +- .../public/embeddable/visualize_embeddable.ts | 12 +- .../visualize_embeddable_factory.tsx | 6 +- .../expression_functions/vis_dimension.ts | 2 +- .../expressions/visualization_function.ts | 2 +- .../public/legacy/build_pipeline.ts | 26 +- .../visualizations/public/legacy/memoize.ts | 2 +- .../public/legacy/vis_update_state.js | 6 +- .../public/persisted_state/persisted_state.ts | 4 +- .../saved_visualizations/find_list_items.ts | 12 +- .../saved_visualization_references.ts | 6 +- src/plugins/visualizations/public/vis.test.ts | 22 +- src/plugins/visualizations/public/vis.ts | 6 +- .../vis_types/vis_type_alias_registry.ts | 4 +- .../public/wizard/new_vis_modal.test.tsx | 2 +- .../wizard/type_selection/new_vis_help.tsx | 2 +- .../wizard/type_selection/type_selection.tsx | 12 +- .../saved_objects/visualization_migrations.ts | 44 +- .../public/application/editor/editor.js | 46 +- .../application/editor/lib/make_stateful.ts | 4 +- .../editor/lib/visualize_app_state.ts | 14 +- .../application/editor/visualization.js | 6 +- .../editor/visualization_editor.js | 6 +- .../public/application/legacy_app.js | 34 +- .../application/listing/visualize_listing.js | 14 +- .../listing/visualize_listing_table.js | 4 +- src/setup_node_env/exit_on_warning.js | 4 +- src/setup_node_env/harden.js | 2 +- .../node_version_validator.test.js | 10 +- src/setup_node_env/patches/child_process.js | 2 +- src/setup_node_env/root/force.js | 2 +- src/setup_node_env/root/force.test.js | 8 +- src/setup_node_env/root/is_root.js | 2 +- src/setup_node_env/root/is_root.test.js | 6 +- src/test_utils/__tests__/get_url.js | 8 +- src/test_utils/get_url.js | 2 +- src/test_utils/public/enzyme_helpers.tsx | 2 +- src/test_utils/public/image_comparator.js | 4 +- src/test_utils/public/mocks/intl.js | 10 +- src/test_utils/public/no_digest_promises.js | 6 +- src/test_utils/public/simulate_keys.js | 6 +- .../public/stub_get_active_injector.js | 2 +- src/test_utils/public/stub_index_pattern.js | 10 +- tasks/check_plugins.js | 4 +- tasks/config/availabletasks.js | 2 +- tasks/config/karma.js | 10 +- tasks/config/run.js | 4 +- tasks/docker_docs.js | 4 +- tasks/function_test_groups.js | 10 +- tasks/jenkins.js | 2 +- tasks/licenses_csv_report.js | 6 +- tasks/test.js | 12 +- tasks/test_jest.js | 6 +- tasks/verify_dependency_versions.js | 4 +- test/accessibility/apps/console.ts | 2 +- test/accessibility/apps/dashboard.ts | 2 +- test/accessibility/apps/dashboard_panel.ts | 2 +- test/accessibility/apps/discover.ts | 2 +- test/accessibility/apps/home.ts | 2 +- test/accessibility/apps/management.ts | 2 +- test/accessibility/apps/visualize.ts | 2 +- test/accessibility/config.ts | 2 +- test/accessibility/services/a11y/a11y.ts | 2 +- .../services/a11y/analyze_with_axe.js | 4 +- .../accessibility/services/a11y/axe_report.ts | 2 +- test/api_integration/apis/core/index.js | 8 +- .../apis/elasticsearch/index.js | 2 +- test/api_integration/apis/general/cookies.js | 6 +- test/api_integration/apis/general/csp.js | 4 +- test/api_integration/apis/general/index.js | 2 +- test/api_integration/apis/home/index.js | 2 +- test/api_integration/apis/home/sample_data.js | 17 +- test/api_integration/apis/index.js | 2 +- .../apis/index_patterns/es_errors/errors.js | 2 +- .../apis/index_patterns/es_errors/index.js | 2 +- .../fields_for_time_pattern_route/errors.js | 2 +- .../fields_for_time_pattern_route/index.js | 2 +- .../fields_for_time_pattern_route/pattern.js | 8 +- .../query_params.js | 10 +- .../fields_for_wildcard_route/conflicts.js | 4 +- .../fields_for_wildcard_route/index.js | 2 +- .../fields_for_wildcard_route/params.js | 7 +- .../fields_for_wildcard_route/response.js | 4 +- .../apis/index_patterns/index.js | 2 +- .../apis/kql_telemetry/index.js | 2 +- .../apis/kql_telemetry/kql_telemetry.js | 8 +- .../apis/saved_objects/bulk_create.js | 8 +- .../apis/saved_objects/bulk_get.js | 6 +- .../apis/saved_objects/bulk_update.js | 2 +- .../apis/saved_objects/create.js | 6 +- .../apis/saved_objects/delete.js | 8 +- .../apis/saved_objects/export.js | 34 +- .../apis/saved_objects/find.js | 30 +- .../api_integration/apis/saved_objects/get.js | 8 +- .../apis/saved_objects/import.js | 16 +- .../apis/saved_objects/index.js | 2 +- .../apis/saved_objects/migrations.js | 28 +- .../saved_objects/resolve_import_errors.js | 24 +- .../apis/saved_objects/update.js | 8 +- .../apis/saved_objects_management/find.ts | 2 +- .../apis/saved_objects_management/index.ts | 2 +- .../saved_objects_management/relationships.ts | 4 +- .../saved_objects_management/scroll_count.ts | 2 +- test/api_integration/apis/scripts/index.js | 2 +- .../api_integration/apis/scripts/languages.js | 6 +- test/api_integration/apis/shorten/index.js | 2 +- test/api_integration/apis/stats/index.js | 2 +- test/api_integration/apis/stats/stats.js | 4 +- test/api_integration/apis/status/index.js | 2 +- test/api_integration/apis/status/status.js | 4 +- .../api_integration/apis/suggestions/index.js | 2 +- .../apis/suggestions/suggestions.js | 4 +- test/api_integration/apis/telemetry/index.js | 2 +- test/api_integration/apis/telemetry/opt_in.ts | 2 +- .../apis/telemetry/telemetry_local.js | 4 +- .../telemetry/telemetry_optin_notice_seen.ts | 5 +- test/api_integration/apis/ui_metric/index.js | 2 +- .../apis/ui_metric/ui_metric.js | 6 +- test/api_integration/config.js | 2 +- test/common/config.js | 2 +- .../kibana_server/extend_es_archiver.js | 2 +- .../services/retry/retry_for_success.ts | 2 +- .../common/services/retry/retry_for_truthy.ts | 4 +- test/examples/config.js | 2 +- test/examples/embeddables/adding_children.ts | 2 +- .../embeddables/hello_world_embeddable.ts | 2 +- test/examples/embeddables/index.ts | 4 +- test/examples/embeddables/list_container.ts | 2 +- test/examples/embeddables/todo_embeddable.ts | 2 +- test/examples/search/demo_data.ts | 2 +- test/examples/search/es_search.ts | 2 +- test/examples/search/index.ts | 6 +- test/examples/state_sync/index.ts | 4 +- test/examples/state_sync/todo_app.ts | 2 +- test/examples/ui_actions/index.ts | 4 +- test/examples/ui_actions/ui_actions.ts | 2 +- test/functional/apps/bundles/index.js | 4 +- test/functional/apps/console/_console.ts | 2 +- test/functional/apps/console/index.js | 6 +- .../apps/context/_context_navigation.js | 10 +- test/functional/apps/context/_date_nanos.js | 8 +- .../context/_date_nanos_custom_timestamp.js | 8 +- .../apps/context/_discover_navigation.js | 14 +- test/functional/apps/context/_filters.js | 18 +- test/functional/apps/context/_size.js | 20 +- test/functional/apps/context/index.js | 6 +- .../apps/dashboard/bwc_shared_urls.js | 10 +- .../dashboard/create_and_add_embeddables.js | 2 +- .../apps/dashboard/dashboard_back_button.ts | 2 +- .../apps/dashboard/dashboard_clone.js | 12 +- .../apps/dashboard/dashboard_filter_bar.js | 18 +- .../apps/dashboard/dashboard_filtering.js | 6 +- .../apps/dashboard/dashboard_grid.js | 4 +- .../apps/dashboard/dashboard_listing.js | 48 +- .../apps/dashboard/dashboard_options.js | 2 +- .../apps/dashboard/dashboard_query_bar.js | 2 +- .../apps/dashboard/dashboard_save.js | 20 +- .../apps/dashboard/dashboard_saved_query.js | 6 +- .../apps/dashboard/dashboard_snapshots.js | 6 +- .../apps/dashboard/dashboard_state.js | 22 +- .../apps/dashboard/dashboard_time.js | 20 +- .../apps/dashboard/dashboard_time_picker.js | 4 +- .../apps/dashboard/data_shared_attributes.js | 12 +- .../dashboard/edit_embeddable_redirects.js | 2 +- test/functional/apps/dashboard/embed_mode.js | 4 +- .../apps/dashboard/embeddable_rendering.js | 2 +- .../apps/dashboard/empty_dashboard.js | 2 +- .../apps/dashboard/full_screen_mode.js | 2 +- test/functional/apps/dashboard/index.js | 12 +- .../apps/dashboard/panel_controls.js | 28 +- .../apps/dashboard/panel_expand_toggle.js | 2 +- test/functional/apps/dashboard/time_zones.js | 4 +- test/functional/apps/dashboard/view_edit.js | 40 +- test/functional/apps/discover/_date_nanos.js | 8 +- .../apps/discover/_date_nanos_mixed.js | 8 +- test/functional/apps/discover/_discover.js | 46 +- .../apps/discover/_discover_histogram.js | 4 +- .../apps/discover/_doc_navigation.js | 6 +- test/functional/apps/discover/_errors.js | 6 +- test/functional/apps/discover/_field_data.js | 20 +- .../apps/discover/_field_visualize.ts | 4 +- .../apps/discover/_filter_editor.js | 12 +- .../_indexpattern_without_timefield.ts | 12 +- test/functional/apps/discover/_inspector.js | 4 +- .../functional/apps/discover/_large_string.js | 14 +- .../apps/discover/_saved_queries.js | 8 +- .../functional/apps/discover/_shared_links.js | 22 +- test/functional/apps/discover/_sidebar.js | 16 +- .../apps/discover/_source_filters.js | 8 +- test/functional/apps/discover/index.js | 6 +- .../apps/getting_started/_shakespeare.js | 18 +- test/functional/apps/getting_started/index.js | 6 +- test/functional/apps/home/_add_data.js | 2 +- test/functional/apps/home/_home.js | 2 +- test/functional/apps/home/_navigation.ts | 2 +- test/functional/apps/home/_newsfeed.ts | 2 +- test/functional/apps/home/_sample_data.ts | 2 +- test/functional/apps/home/index.js | 6 +- .../_create_index_pattern_wizard.js | 12 +- .../apps/management/_handle_alias.js | 18 +- .../management/_handle_version_conflict.js | 12 +- .../apps/management/_import_objects.js | 38 +- .../_index_pattern_create_delete.js | 26 +- .../apps/management/_index_pattern_filter.js | 14 +- .../management/_index_pattern_popularity.js | 10 +- .../management/_index_pattern_results_sort.js | 28 +- .../apps/management/_kibana_settings.js | 14 +- .../management/_mgmt_import_saved_objects.js | 8 +- .../apps/management/_scripted_fields.js | 76 +- .../management/_scripted_fields_filter.js | 14 +- .../management/_scripted_fields_preview.js | 10 +- .../apps/management/_test_huge_fields.js | 8 +- test/functional/apps/management/index.js | 8 +- .../edit_saved_object.ts | 4 +- test/functional/apps/status_page/index.js | 6 +- .../apps/timelion/_expression_typeahead.js | 2 +- test/functional/apps/timelion/index.js | 6 +- test/functional/apps/visualize/_area_chart.js | 23 +- .../functional/apps/visualize/_chart_types.ts | 12 +- test/functional/apps/visualize/_data_table.js | 12 +- .../visualize/_data_table_nontimeindex.js | 12 +- .../_data_table_notimeindex_filters.ts | 8 +- .../apps/visualize/_embedding_chart.js | 4 +- .../apps/visualize/_experimental_vis.js | 2 +- .../functional/apps/visualize/_gauge_chart.js | 12 +- .../apps/visualize/_heatmap_chart.js | 16 +- .../visualize/_histogram_request_start.js | 12 +- test/functional/apps/visualize/_inspector.js | 22 +- test/functional/apps/visualize/_lab_mode.js | 2 +- test/functional/apps/visualize/_line_chart.js | 22 +- .../apps/visualize/_linked_saved_searches.ts | 2 +- .../apps/visualize/_markdown_vis.js | 14 +- .../apps/visualize/_metric_chart.js | 32 +- test/functional/apps/visualize/_pie_chart.js | 20 +- .../apps/visualize/_point_series_options.js | 42 +- test/functional/apps/visualize/_region_map.js | 14 +- .../functional/apps/visualize/_shared_item.js | 8 +- test/functional/apps/visualize/_tag_cloud.js | 34 +- test/functional/apps/visualize/_tile_map.js | 24 +- test/functional/apps/visualize/_tsvb_chart.ts | 2 +- .../apps/visualize/_tsvb_markdown.ts | 8 +- test/functional/apps/visualize/_tsvb_table.ts | 2 +- .../apps/visualize/_tsvb_time_series.ts | 2 +- test/functional/apps/visualize/_vega_chart.js | 18 +- .../apps/visualize/_vertical_bar_chart.js | 36 +- .../_vertical_bar_chart_nontimeindex.js | 26 +- .../apps/visualize/_visualize_listing.js | 26 +- test/functional/apps/visualize/index.ts | 10 +- .../input_control_vis/chained_controls.js | 20 +- .../input_control_vis/dynamic_options.js | 48 +- .../apps/visualize/input_control_vis/index.js | 4 +- .../input_control_options.js | 18 +- .../input_control_vis/input_control_range.ts | 2 +- test/functional/config.coverage.js | 2 +- test/functional/config.edge.js | 2 +- test/functional/config.firefox.js | 2 +- test/functional/config.ie.js | 2 +- test/functional/config.js | 2 +- test/functional/page_objects/console_page.ts | 2 +- .../functional/page_objects/dashboard_page.ts | 16 +- test/functional/page_objects/discover_page.ts | 14 +- test/functional/page_objects/settings_page.ts | 10 +- .../functional/page_objects/tag_cloud_page.ts | 2 +- test/functional/page_objects/tile_map_page.ts | 2 +- test/functional/page_objects/time_picker.ts | 2 +- test/functional/page_objects/timelion_page.ts | 2 +- .../page_objects/vega_chart_page.ts | 2 +- .../page_objects/visual_builder_page.ts | 2 +- .../page_objects/visualize_chart_page.ts | 41 +- .../page_objects/visualize_editor_page.ts | 2 +- .../functional/page_objects/visualize_page.ts | 7 +- test/functional/services/apps_menu.ts | 6 +- test/functional/services/combo_box.ts | 4 +- test/functional/services/common/browser.ts | 49 +- test/functional/services/common/find.ts | 12 +- .../services/common/test_subjects.ts | 4 +- .../services/dashboard/expectations.js | 18 +- test/functional/services/doc_table.ts | 12 +- test/functional/services/filter_bar.ts | 5 +- test/functional/services/inspector.ts | 24 +- .../web_element_wrapper.ts | 17 +- .../config.js | 2 +- .../test.js | 2 +- .../test2.js | 2 +- .../test3.1.js | 2 +- .../test3.js | 2 +- .../__tests__/remote_default_window_size.js | 4 +- .../services/remote/create_stdout_stream.ts | 8 +- .../services/remote/poll_for_log_entry.ts | 8 +- .../remote/prevent_parallel_calls.test.js | 4 +- .../services/remote/prevent_parallel_calls.ts | 2 +- test/functional/services/remote/remote.ts | 21 +- test/functional/services/remote/webdriver.ts | 4 +- test/functional/services/table.ts | 4 +- .../services/visualizations/pie_chart.js | 6 +- test/harden/child_process.js | 220 +-- test/interpreter_functional/config.ts | 6 +- .../test_suites/run_pipeline/basic.ts | 2 +- .../test_suites/run_pipeline/esaggs.ts | 2 +- .../test_suites/run_pipeline/index.ts | 4 +- .../test_suites/run_pipeline/metric.ts | 2 +- .../test_suites/run_pipeline/tag_cloud.ts | 2 +- test/plugin_functional/config.js | 6 +- .../plugins/core_plugin_a/server/plugin.ts | 2 +- .../core_plugin_appleave/public/plugin.tsx | 4 +- .../plugins/core_plugin_legacy/index.ts | 2 +- .../core_provider_plugin/public/index.ts | 2 +- .../doc_views_plugin/public/plugin.tsx | 2 +- .../plugins/legacy_plugin/index.ts | 2 +- .../bfetch_explorer/batched_function.ts | 8 +- .../test_suites/bfetch_explorer/index.ts | 4 +- .../core_plugins/application_leave_confirm.ts | 2 +- .../core_plugins/application_status.ts | 2 +- .../test_suites/core_plugins/applications.ts | 2 +- .../test_suites/core_plugins/index.ts | 2 +- .../core_plugins/legacy_plugins.ts | 2 +- .../test_suites/core_plugins/rendering.ts | 2 +- .../core_plugins/server_plugins.ts | 7 +- .../test_suites/core_plugins/top_nav.js | 2 +- .../test_suites/core_plugins/ui_plugins.ts | 18 +- .../test_suites/core_plugins/ui_settings.ts | 11 +- .../custom_visualizations/index.js | 4 +- .../self_changing_vis.js | 2 +- .../test_suites/doc_views/doc_views.ts | 4 +- .../test_suites/doc_views/index.ts | 4 +- .../dashboard_container.js | 2 +- .../test_suites/embeddable_explorer/index.js | 4 +- .../test_suites/management/index.js | 2 +- .../management/management_plugin.js | 2 +- .../test_suites/panel_actions/index.js | 6 +- .../panel_actions/panel_actions.js | 2 +- test/server_integration/config.js | 2 +- test/server_integration/http/cache/config.js | 2 +- test/server_integration/http/cache/index.js | 2 +- test/server_integration/http/ssl/config.js | 2 +- test/server_integration/http/ssl/index.js | 2 +- .../http/ssl_redirect/config.js | 2 +- .../http/ssl_redirect/index.js | 13 +- .../http/ssl_with_p12/config.js | 2 +- .../http/ssl_with_p12/index.js | 2 +- .../http/ssl_with_p12_intermediate/config.js | 2 +- .../http/ssl_with_p12_intermediate/index.js | 2 +- test/server_integration/services/supertest.js | 2 +- test/ui_capabilities/newsfeed_err/test.ts | 2 +- test/visual_regression/config.ts | 2 +- .../services/visual_testing/visual_testing.ts | 2 +- test/visual_regression/tests/console_app.ts | 2 +- .../tests/discover/chart_visualization.ts | 24 +- .../visual_regression/tests/discover/index.ts | 6 +- utilities/visual_regression.js | 8 +- x-pack/dev-tools/api_debug/index.js | 4 +- x-pack/dev-tools/jest/setup/polyfills.js | 2 +- .../dashboard_hello_world_drilldown/index.tsx | 2 +- .../collect_config_container.tsx | 4 +- .../discover_drilldown_config.tsx | 2 +- .../drilldown.tsx | 2 +- .../dashboard_to_url_drilldown/index.tsx | 2 +- x-pack/index.js | 2 +- x-pack/legacy/common/__tests__/poller.js | 4 +- x-pack/legacy/common/poller.js | 2 +- .../common/config_block_validation.ts | 4 +- .../beats_management/common/config_schemas.ts | 2 +- .../common/config_schemas_translations_map.ts | 4 +- .../beats_management/common/domain_types.ts | 2 +- .../beats_management/common/io_ts_types.ts | 2 +- .../legacy/plugins/beats_management/index.ts | 4 +- .../beats_management/scripts/fake_env.ts | 2 +- .../beats/elasticsearch_beats_adapter.ts | 2 +- .../adapters/beats/memory_beats_adapter.ts | 28 +- ...asticsearch_configuration_block_adapter.ts | 6 +- .../memory_tags_adapter.ts | 18 +- .../tags/elasticsearch_tags_adapter.ts | 14 +- .../lib/adapters/tags/memory_tags_adapter.ts | 8 +- .../tokens/elasticsearch_tokens_adapter.ts | 4 +- .../adapters/tokens/memory_tokens_adapter.ts | 10 +- .../server/lib/beat_events.ts | 4 +- .../beats_management/server/lib/beats.ts | 10 +- .../beats_management/server/lib/tags.ts | 4 +- .../beats_management/server/lib/tokens.ts | 4 +- .../server/rest_api/beats/tag_assignment.ts | 2 +- .../server/rest_api/beats/tag_removal.ts | 2 +- .../server/rest_api/configurations/delete.ts | 2 +- .../server/rest_api/configurations/upsert.ts | 2 +- .../server/rest_api/tags/assignable.ts | 2 +- .../server/rest_api/tokens/create.ts | 7 +- .../server/utils/helper_types.ts | 4 +- .../plugins/beats_management/wallaby.js | 4 +- .../dashboard_mode_request_interceptor.js | 13 +- .../dashboard_mode_request_interceptor.js | 9 +- .../maps/public/angular/map_controller.js | 30 +- x-pack/legacy/plugins/maps/public/plugin.ts | 2 +- x-pack/legacy/plugins/maps/public/routes.js | 14 +- x-pack/legacy/plugins/monitoring/config.ts | 34 +- .../plugins/reporting/common/validate_urls.ts | 2 +- .../get_conditional_headers.test.ts | 5 +- .../common/execute_job/get_full_urls.ts | 2 +- .../execute_job/omit_blacklisted_headers.ts | 2 +- .../common/lib/screenshots/get_time_range.ts | 2 +- .../common/lib/screenshots/inject_css.ts | 2 +- .../common/lib/screenshots/observable.ts | 4 +- .../common/lib/screenshots/wait_for_render.ts | 6 +- .../csv/server/execute_job.test.ts | 122 +- .../csv/server/lib/cell_has_formula.ts | 2 +- .../lib/check_cells_for_formulas.test.ts | 6 +- .../server/lib/check_cells_for_formulas.ts | 2 +- .../csv/server/lib/escape_value.test.ts | 38 +- .../csv/server/lib/field_format_map.test.ts | 8 +- .../csv/server/lib/field_format_map.ts | 2 +- .../csv/server/lib/flatten_hit.test.ts | 28 +- .../csv/server/lib/flatten_hit.ts | 2 +- .../csv/server/lib/format_csv_values.test.ts | 22 +- .../csv/server/lib/format_csv_values.ts | 6 +- .../csv/server/lib/hit_iterator.test.ts | 2 +- .../lib/max_size_string_builder.test.ts | 30 +- .../png/server/execute_job/index.ts | 8 +- .../printable_pdf/server/execute_job/index.ts | 10 +- .../printable_pdf/server/lib/generate_pdf.ts | 6 +- .../printable_pdf/server/lib/pdf/index.js | 8 +- .../printable_pdf/server/lib/uri_encode.js | 4 +- .../chromium/driver/chromium_driver.ts | 2 +- .../browsers/chromium/driver_factory/index.ts | 12 +- .../server/browsers/download/checksum.ts | 2 +- .../server/browsers/download/clean.ts | 2 +- .../server/browsers/download/download.test.ts | 4 +- .../browsers/download/ensure_downloaded.ts | 4 +- .../server/browsers/extract/unzip.js | 4 +- .../server/browsers/safe_child_process.ts | 6 +- .../server/lib/__tests__/check_license.js | 2 +- .../lib/__tests__/export_types_registry.js | 54 +- .../reporting/server/lib/check_license.ts | 4 +- .../server/lib/create_tagged_logger.ts | 6 +- .../esqueue/__tests__/helpers/create_index.js | 30 +- .../lib/esqueue/__tests__/helpers/errors.js | 20 +- .../__tests__/helpers/index_timestamp.js | 36 +- .../server/lib/esqueue/__tests__/index.js | 46 +- .../server/lib/esqueue/__tests__/job.js | 105 +- .../server/lib/esqueue/__tests__/worker.js | 276 ++-- .../lib/esqueue/helpers/create_index.js | 4 +- .../reporting/server/lib/esqueue/index.js | 10 +- .../reporting/server/lib/esqueue/job.js | 8 +- .../reporting/server/lib/esqueue/worker.js | 36 +- .../server/lib/export_types_registry.ts | 2 +- .../reporting/server/lib/jobs_query.ts | 6 +- .../server/routes/generate_from_jobparams.ts | 4 +- .../server/routes/generation.test.ts | 2 +- .../lib/authorized_user_pre_routing.test.js | 22 +- .../routes/lib/authorized_user_pre_routing.ts | 2 +- .../server/routes/lib/job_response_handler.ts | 9 +- .../server/usage/decorate_range_stats.ts | 2 +- .../plugins/security/public/hacks/legacy.ts | 2 +- x-pack/legacy/plugins/xpack_main/index.js | 2 +- .../public/hacks/check_xpack_info_change.js | 6 +- .../xpack_main/public/services/xpack_info.js | 8 +- .../lib/__tests__/call_cluster_factory.js | 5 +- .../__tests__/inject_xpack_info_signature.js | 4 +- .../lib/__tests__/replace_injected_vars.js | 2 +- .../server/lib/__tests__/setup_xpack_main.js | 4 +- .../server/lib/__tests__/xpack_info.js | 16 +- .../xpack_main/server/lib/xpack_info.ts | 6 +- .../server/lib/xpack_info_license.test.js | 2 +- .../server/lib/xpack_info_license.ts | 4 +- .../server/routes/api/v1/settings.js | 2 +- .../server/lib/__tests__/kibana_state.js | 46 +- .../lib/__tests__/mirror_plugin_status.js | 6 +- x-pack/legacy/server/lib/audit_logger.js | 2 +- x-pack/legacy/server/lib/audit_logger.test.js | 6 +- .../lib/check_license/check_license.test.js | 2 +- .../legacy/server/lib/create_router/index.js | 4 +- .../is_es_error_factory.js | 2 +- .../__tests__/license_pre_routing_factory.js | 2 +- .../legacy/server/lib/mirror_plugin_status.js | 2 +- .../register_license_checker.js | 2 +- .../watch_status_and_license_to_initialize.js | 2 +- ...h_status_and_license_to_initialize.test.js | 42 +- .../server/action_type_registry.test.ts | 2 +- .../actions/server/action_type_registry.ts | 2 +- .../actions/server/actions_client.test.ts | 2 +- .../plugins/actions/server/actions_client.ts | 10 +- .../plugins/actions/server/actions_config.ts | 4 +- .../builtin_action_types/case/utils.test.ts | 6 +- .../server/builtin_action_types/case/utils.ts | 13 +- .../server/builtin_action_types/email.test.ts | 2 +- .../server/builtin_action_types/index.test.ts | 2 +- .../lib/http_rersponse_retry_header.ts | 4 +- .../builtin_action_types/pagerduty.test.ts | 4 +- .../server/builtin_action_types/slack.test.ts | 4 +- .../server/builtin_action_types/slack.ts | 2 +- .../builtin_action_types/webhook.test.ts | 4 +- .../server/builtin_action_types/webhook.ts | 4 +- .../actions/server/create_execute_function.ts | 2 +- .../actions/server/lib/action_executor.ts | 2 +- .../server/lib/validate_with_schema.test.ts | 2 +- x-pack/plugins/actions/server/mocks.ts | 8 +- x-pack/plugins/actions/server/plugin.ts | 9 +- .../plugins/actions/server/routes/create.ts | 2 +- .../plugins/actions/server/routes/delete.ts | 2 +- .../plugins/actions/server/routes/execute.ts | 2 +- x-pack/plugins/actions/server/routes/get.ts | 2 +- .../plugins/actions/server/routes/get_all.ts | 2 +- .../server/routes/list_action_types.ts | 2 +- .../plugins/actions/server/routes/update.ts | 2 +- x-pack/plugins/actions/server/usage/task.ts | 7 +- .../action_wizard/action_wizard.tsx | 6 +- .../components/action_wizard/test_data.tsx | 8 +- .../public/custom_time_range_action.test.ts | 6 +- .../public/custom_time_range_badge.test.ts | 2 +- .../public/customize_time_range_modal.tsx | 2 +- .../dynamic_action_manager.test.ts | 6 +- .../dynamic_actions/dynamic_action_manager.ts | 2 +- .../dynamic_action_manager_state.ts | 16 +- .../dynamic_actions/dynamic_action_storage.ts | 6 +- .../ui_actions_service_enhancements.ts | 6 +- .../alerting/common/date_from_string.ts | 4 +- x-pack/plugins/alerting/public/alert_api.ts | 2 +- .../alerting/server/alerts_client.test.ts | 2 +- .../plugins/alerting/server/alerts_client.ts | 20 +- x-pack/plugins/alerting/server/lib/types.ts | 4 +- x-pack/plugins/alerting/server/plugin.ts | 2 +- .../plugins/alerting/server/routes/create.ts | 2 +- .../plugins/alerting/server/routes/delete.ts | 2 +- .../plugins/alerting/server/routes/disable.ts | 2 +- .../plugins/alerting/server/routes/enable.ts | 2 +- x-pack/plugins/alerting/server/routes/find.ts | 2 +- x-pack/plugins/alerting/server/routes/get.ts | 2 +- .../alerting/server/routes/get_alert_state.ts | 2 +- .../plugins/alerting/server/routes/health.ts | 2 +- .../server/routes/list_alert_types.ts | 2 +- .../alerting/server/routes/mute_all.ts | 2 +- .../alerting/server/routes/mute_instance.ts | 2 +- .../alerting/server/routes/unmute_all.ts | 2 +- .../alerting/server/routes/unmute_instance.ts | 2 +- .../plugins/alerting/server/routes/update.ts | 2 +- .../alerting/server/routes/update_api_key.ts | 2 +- .../task_runner/create_execution_handler.ts | 2 +- .../server/task_runner/task_runner.ts | 10 +- .../alerting/server/test_utils/index.ts | 2 +- x-pack/plugins/alerting/server/usage/task.ts | 7 +- .../lib/date_range_info.test.ts | 4 +- .../index_threshold/routes/indices.ts | 2 +- .../common/agent_configuration/all_option.ts | 2 +- .../agent_configuration/amount_and_unit.ts | 2 +- .../agent_configuration_intake_rt.test.ts | 16 +- .../agent_configuration_intake_rt.ts | 8 +- .../runtime_types/boolean_rt.test.ts | 4 +- .../runtime_types/bytes_rt.test.ts | 20 +- .../runtime_types/bytes_rt.ts | 23 +- .../runtime_types/capture_body_rt.test.ts | 4 +- .../runtime_types/capture_body_rt.ts | 2 +- .../runtime_types/duration_rt.test.ts | 22 +- .../runtime_types/duration_rt.ts | 25 +- .../runtime_types/float_rt.ts | 2 +- .../runtime_types/get_range_type_message.ts | 4 +- .../runtime_types/integer_rt.test.ts | 12 +- .../runtime_types/integer_rt.ts | 19 +- .../setting_definitions/general_settings.ts | 70 +- .../setting_definitions/index.test.ts | 30 +- .../setting_definitions/index.ts | 8 +- .../setting_definitions/java_settings.ts | 54 +- x-pack/plugins/apm/common/agent_name.ts | 2 +- x-pack/plugins/apm/common/alert_types.ts | 32 +- x-pack/plugins/apm/common/annotations.ts | 2 +- .../custom_link/custom_link_filter_options.ts | 4 +- .../common/custom_link/custom_link_types.d.ts | 2 +- .../common/elasticsearch_fieldnames.test.ts | 70 +- x-pack/plugins/apm/common/i18n.ts | 4 +- .../apm/common/ml_job_constants.test.ts | 2 +- x-pack/plugins/apm/common/ml_job_constants.ts | 7 +- x-pack/plugins/apm/common/processor_event.ts | 2 +- .../plugins/apm/common/projections/errors.ts | 22 +- .../plugins/apm/common/projections/metrics.ts | 16 +- .../apm/common/projections/service_nodes.ts | 16 +- .../apm/common/projections/services.ts | 24 +- .../common/projections/transaction_groups.ts | 20 +- .../apm/common/projections/transactions.ts | 16 +- .../plugins/apm/common/projections/typings.ts | 4 +- .../util/merge_projection/index.test.ts | 34 +- .../util/merge_projection/index.ts | 2 +- .../runtime_types/date_as_string_rt/index.ts | 2 +- .../apm/common/runtime_types/json_rt/index.ts | 4 +- x-pack/plugins/apm/common/service_map.test.ts | 20 +- x-pack/plugins/apm/common/service_map.ts | 4 +- x-pack/plugins/apm/common/viz_colors.ts | 2 +- .../plugins/apm/e2e/cypress/plugins/index.js | 6 +- .../cypress/support/step_definitions/apm.ts | 19 +- .../plugins/apm/e2e/cypress/webpack.config.js | 26 +- x-pack/plugins/apm/e2e/ingest-data/replay.js | 16 +- .../plugins/apm/public/application/index.tsx | 6 +- .../app/APMIndicesPermission/index.test.tsx | 32 +- .../app/APMIndicesPermission/index.tsx | 24 +- .../DetailView/ErrorTabs.tsx | 14 +- .../DetailView/ExceptionStacktrace.tsx | 2 +- .../DetailView/index.test.tsx | 30 +- .../ErrorGroupDetails/DetailView/index.tsx | 18 +- .../ErrorGroupDetails/Distribution/index.tsx | 16 +- .../app/ErrorGroupDetails/index.tsx | 36 +- .../app/ErrorGroupOverview/List/index.tsx | 38 +- .../app/ErrorGroupOverview/index.tsx | 30 +- .../apm/public/components/app/Home/index.tsx | 24 +- .../app/Main/ProvideBreadcrumbs.test.tsx | 24 +- .../app/Main/ProvideBreadcrumbs.tsx | 12 +- .../app/Main/UpdateBreadcrumbs.test.tsx | 10 +- .../components/app/Main/UpdateBreadcrumbs.tsx | 4 +- .../app/Main/route_config/index.tsx | 68 +- .../route_handlers/agent_configuration.tsx | 4 +- .../app/Main/route_config/route_names.tsx | 2 +- .../AlertIntegrations/index.tsx | 38 +- .../app/ServiceDetails/ServiceDetailTabs.tsx | 24 +- .../TransactionSelect.tsx | 10 +- .../MachineLearningFlyout/index.tsx | 22 +- .../MachineLearningFlyout/view.tsx | 34 +- .../ServiceIntegrations/WatcherFlyout.tsx | 116 +- .../__test__/createErrorGroupWatch.test.ts | 16 +- .../__test__/esResponse.ts | 82 +- .../createErrorGroupWatch.ts | 84 +- .../ServiceIntegrations/index.tsx | 32 +- .../components/app/ServiceMap/BetaBadge.tsx | 4 +- .../components/app/ServiceMap/Controls.tsx | 16 +- .../app/ServiceMap/Cytoscape.stories.tsx | 150 +- .../components/app/ServiceMap/Cytoscape.tsx | 36 +- .../app/ServiceMap/EmptyBanner.test.tsx | 4 +- .../components/app/ServiceMap/EmptyBanner.tsx | 8 +- .../app/ServiceMap/LoadingOverlay.tsx | 2 +- .../app/ServiceMap/Popover/Buttons.tsx | 6 +- .../app/ServiceMap/Popover/Contents.tsx | 12 +- .../app/ServiceMap/Popover/Info.tsx | 12 +- .../Popover/ServiceMetricFetcher.tsx | 10 +- .../ServiceMap/Popover/ServiceMetricList.tsx | 24 +- .../app/ServiceMap/Popover/index.tsx | 12 +- .../app/ServiceMap/cytoscapeOptions.ts | 36 +- .../public/components/app/ServiceMap/icons.ts | 18 +- .../components/app/ServiceMap/index.test.tsx | 6 +- .../components/app/ServiceMap/index.tsx | 8 +- .../components/app/ServiceMetrics/index.tsx | 8 +- .../app/ServiceNodeMetrics/index.tsx | 24 +- .../app/ServiceNodeOverview/index.tsx | 48 +- .../app/ServiceOverview/NoServicesMessage.tsx | 10 +- .../ServiceList/__test__/List.test.js | 6 +- .../app/ServiceOverview/ServiceList/index.tsx | 32 +- .../__test__/NoServicesMessage.test.tsx | 4 +- .../__test__/ServiceOverview.test.tsx | 34 +- .../components/app/ServiceOverview/index.tsx | 22 +- .../ServicePage/FormRowSelect.tsx | 4 +- .../ServicePage/ServicePage.tsx | 42 +- .../SettingsPage/SettingFormRow.tsx | 28 +- .../SettingsPage/SettingsPage.tsx | 30 +- .../SettingsPage/saveConfig.ts | 24 +- .../index.stories.tsx | 16 +- .../AgentConfigurationCreateEdit/index.tsx | 22 +- .../List/ConfirmDeleteModal.tsx | 24 +- .../AgentConfigurations/List/index.tsx | 24 +- .../Settings/AgentConfigurations/index.tsx | 6 +- .../app/Settings/ApmIndices/index.test.tsx | 2 +- .../app/Settings/ApmIndices/index.tsx | 50 +- .../CustomLink/CreateCustomLinkButton.tsx | 2 +- .../CustomLinkFlyout/DeleteButton.tsx | 10 +- .../CustomLinkFlyout/FiltersSection.tsx | 22 +- .../CustomLinkFlyout/FlyoutFooter.tsx | 8 +- .../CustomLinkFlyout/LinkPreview.test.tsx | 4 +- .../CustomLinkFlyout/LinkPreview.tsx | 6 +- .../CustomLinkFlyout/LinkSection.tsx | 32 +- .../CustomLinkFlyout/helper.test.ts | 26 +- .../CustomLink/CustomLinkFlyout/helper.ts | 22 +- .../CustomLink/CustomLinkFlyout/index.tsx | 12 +- .../CustomLinkFlyout/saveCustomLink.ts | 22 +- .../CustomLink/CustomLinkTable.tsx | 24 +- .../CustomizeUI/CustomLink/EmptyPrompt.tsx | 6 +- .../Settings/CustomizeUI/CustomLink/Title.tsx | 4 +- .../CustomizeUI/CustomLink/index.test.tsx | 56 +- .../Settings/CustomizeUI/CustomLink/index.tsx | 4 +- .../app/Settings/CustomizeUI/index.tsx | 2 +- .../public/components/app/Settings/index.tsx | 26 +- .../app/TraceLink/__test__/TraceLink.test.tsx | 24 +- .../public/components/app/TraceLink/index.tsx | 22 +- .../app/TraceOverview/TraceList.tsx | 30 +- .../components/app/TraceOverview/index.tsx | 10 +- .../__test__/distribution.test.ts | 28 +- .../TransactionDetails/Distribution/index.tsx | 38 +- .../WaterfallWithSummmary/ErrorCount.tsx | 2 +- .../MaybeViewTraceLink.tsx | 8 +- .../WaterfallWithSummmary/PercentOfParent.tsx | 8 +- .../WaterfallWithSummmary/TransactionTabs.tsx | 14 +- .../Marks/__test__/get_agent_marks.test.ts | 20 +- .../Marks/__test__/get_error_marks.test.ts | 24 +- .../Marks/get_agent_marks.ts | 2 +- .../Marks/get_error_marks.ts | 6 +- .../WaterfallContainer/ServiceLegends.tsx | 2 +- .../Waterfall/FlyoutTopLevelProperties.tsx | 12 +- .../Waterfall/SpanFlyout/DatabaseContext.tsx | 8 +- .../Waterfall/SpanFlyout/HttpContext.tsx | 2 +- .../SpanFlyout/StickySpanProperties.tsx | 18 +- .../SpanFlyout/TruncateHeightSection.tsx | 10 +- .../Waterfall/SpanFlyout/index.tsx | 24 +- .../Waterfall/SyncBadge.stories.tsx | 12 +- .../Waterfall/SyncBadge.tsx | 4 +- .../TransactionFlyout/DroppedSpansWarning.tsx | 6 +- .../Waterfall/TransactionFlyout/index.tsx | 8 +- .../Waterfall/WaterfallFlyout.tsx | 6 +- .../Waterfall/WaterfallItem.tsx | 16 +- .../WaterfallContainer/Waterfall/index.tsx | 16 +- .../waterfall_helpers.test.ts | 212 +-- .../waterfall_helpers/waterfall_helpers.ts | 42 +- .../WaterfallContainer.stories.tsx | 2 +- .../WaterfallContainer/index.tsx | 2 +- .../waterfallContainer.stories.data.ts | 1172 +++++++------- .../__tests__/ErrorCount.test.tsx | 2 +- .../WaterfallWithSummmary/index.tsx | 12 +- .../app/TransactionDetails/index.tsx | 12 +- .../app/TransactionOverview/List/index.tsx | 32 +- .../__jest__/TransactionOverview.test.tsx | 28 +- .../app/TransactionOverview/index.tsx | 18 +- .../DatePicker/__test__/DatePicker.test.tsx | 23 +- .../components/shared/DatePicker/index.tsx | 40 +- .../public/components/shared/EmptyMessage.tsx | 6 +- .../shared/EnvironmentBadge/index.tsx | 6 +- .../shared/EnvironmentFilter/index.tsx | 26 +- .../ErrorRateAlertTrigger/index.stories.tsx | 4 +- .../shared/ErrorRateAlertTrigger/index.tsx | 22 +- .../components/shared/ErrorStatePrompt.tsx | 4 +- .../public/components/shared/EuiTabLink.tsx | 2 +- .../shared/HeightRetainer/index.tsx | 2 +- .../shared/KeyValueTable/FormattedValue.tsx | 2 +- .../__test__/KeyValueTable.test.tsx | 10 +- .../components/shared/KeyValueTable/index.tsx | 4 +- .../shared/KueryBar/Typeahead/ClickOutside.js | 6 +- .../shared/KueryBar/Typeahead/Suggestion.js | 12 +- .../shared/KueryBar/Typeahead/Suggestions.js | 6 +- .../shared/KueryBar/Typeahead/index.js | 36 +- .../shared/KueryBar/get_bool_filter.ts | 30 +- .../components/shared/KueryBar/index.tsx | 18 +- .../LicensePrompt/LicensePrompt.stories.tsx | 8 +- .../components/shared/LicensePrompt/index.tsx | 8 +- .../Links/DiscoverLinks/DiscoverErrorLink.tsx | 8 +- .../Links/DiscoverLinks/DiscoverLink.tsx | 10 +- .../Links/DiscoverLinks/DiscoverSpanLink.tsx | 6 +- .../DiscoverLinks/DiscoverTransactionLink.tsx | 8 +- .../__test__/DiscoverErrorButton.test.tsx | 4 +- .../__test__/DiscoverErrorLink.test.tsx | 4 +- .../DiscoverLinks.integration.test.tsx | 30 +- .../DiscoverTransactionButton.test.tsx | 2 +- .../__test__/DiscoverTransactionLink.test.tsx | 6 +- .../shared/Links/InfraLink.test.tsx | 2 +- .../components/shared/Links/InfraLink.tsx | 4 +- .../shared/Links/KibanaLink.test.tsx | 2 +- .../components/shared/Links/KibanaLink.tsx | 2 +- .../Links/MachineLearningLinks/MLJobLink.tsx | 4 +- .../MachineLearningLinks/MLLink.test.tsx | 2 +- .../Links/MachineLearningLinks/MLLink.tsx | 2 +- .../shared/Links/SetupInstructionsLink.tsx | 4 +- .../shared/Links/apm/APMLink.test.tsx | 6 +- .../components/shared/Links/apm/APMLink.tsx | 6 +- .../shared/Links/apm/ErrorOverviewLink.tsx | 2 +- .../shared/Links/apm/ExternalLinks.test.ts | 6 +- .../shared/Links/apm/ExternalLinks.ts | 4 +- .../Links/apm/TransactionDetailLink.tsx | 2 +- .../Links/apm/agentConfigurationLinks.tsx | 2 +- .../components/shared/Links/rison_helpers.ts | 8 +- .../shared/Links/url_helpers.test.tsx | 16 +- .../components/shared/Links/url_helpers.ts | 2 +- .../LocalUIFilters/Filter/FilterBadgeList.tsx | 2 +- .../Filter/FilterTitleButton.tsx | 4 +- .../shared/LocalUIFilters/Filter/index.tsx | 26 +- .../TransactionTypeFilter/index.tsx | 16 +- .../shared/LocalUIFilters/index.tsx | 16 +- .../__test__/ManagedTable.test.js | 6 +- .../components/shared/ManagedTable/index.tsx | 16 +- .../__test__/ErrorMetadata.test.tsx | 20 +- .../MetadataTable/ErrorMetadata/sections.ts | 4 +- .../__test__/SpanMetadata.test.tsx | 36 +- .../MetadataTable/SpanMetadata/sections.ts | 4 +- .../__test__/TransactionMetadata.test.tsx | 24 +- .../TransactionMetadata/sections.ts | 4 +- .../__test__/MetadataTable.test.tsx | 14 +- .../MetadataTable/__test__/helper.test.ts | 28 +- .../components/shared/MetadataTable/helper.ts | 4 +- .../components/shared/MetadataTable/index.tsx | 14 +- .../shared/MetadataTable/sections.ts | 76 +- .../shared/SelectWithPlaceholder/index.tsx | 12 +- .../shared/ServiceAlertTrigger/index.tsx | 8 +- .../Stacktrace/CauseStacktrace.test.tsx | 4 +- .../shared/Stacktrace/CauseStacktrace.tsx | 4 +- .../components/shared/Stacktrace/Context.tsx | 6 +- .../Stacktrace/LibraryStacktrace.test.tsx | 2 +- .../shared/Stacktrace/LibraryStacktrace.tsx | 2 +- .../shared/Stacktrace/Stackframe.tsx | 8 +- .../shared/Stacktrace/__test__/index.test.ts | 70 +- .../components/shared/Stacktrace/index.tsx | 4 +- .../StickyProperties/StickyProperties.test.js | 22 +- .../shared/StickyProperties/index.tsx | 12 +- .../shared/Summary/DurationSummaryItem.tsx | 4 +- .../Summary/ErrorCountSummaryItemBadge.tsx | 2 +- .../Summary/HttpInfoSummaryItem/index.tsx | 2 +- .../__test__/HttpStatusBadge.test.tsx | 2 +- .../shared/Summary/HttpStatusBadge/index.tsx | 2 +- .../Summary/HttpStatusBadge/statusCodes.ts | 2 +- .../Summary/TransactionResultSummaryItem.tsx | 2 +- .../Summary/TransactionSummary.test.tsx | 4 +- .../shared/Summary/TransactionSummary.tsx | 4 +- .../shared/Summary/UserAgentSummaryItem.tsx | 4 +- .../Summary/__fixtures__/transactions.ts | 14 +- .../CustomLink/CustomLinkPopover.test.tsx | 6 +- .../CustomLink/CustomLinkPopover.tsx | 6 +- .../CustomLink/CustomLinkSection.test.tsx | 8 +- .../CustomLink/CustomLinkSection.tsx | 4 +- .../CustomLink/ManageCustomLink.test.tsx | 2 +- .../CustomLink/ManageCustomLink.tsx | 8 +- .../CustomLink/index.test.tsx | 10 +- .../CustomLink/index.tsx | 18 +- .../TransactionActionMenu.tsx | 34 +- .../__test__/TransactionActionMenu.test.tsx | 32 +- .../__test__/mockData.ts | 56 +- .../__test__/sections.test.ts | 84 +- .../shared/TransactionActionMenu/sections.ts | 105 +- .../TransactionBreakdownGraph/index.tsx | 2 +- .../TransactionBreakdownHeader.tsx | 8 +- .../TransactionBreakdownKpiList.tsx | 4 +- .../shared/TransactionBreakdown/index.tsx | 2 +- .../index.stories.tsx | 12 +- .../TransactionDurationAlertTrigger/index.tsx | 38 +- .../charts/CustomPlot/AnnotationsPlot.tsx | 12 +- .../charts/CustomPlot/InteractivePlot.js | 24 +- .../shared/charts/CustomPlot/Legends.js | 8 +- .../charts/CustomPlot/SelectionMarker.js | 2 +- .../shared/charts/CustomPlot/StaticPlot.js | 32 +- .../shared/charts/CustomPlot/StatusText.js | 6 +- .../shared/charts/CustomPlot/VoronoiPlot.js | 14 +- .../charts/CustomPlot/getEmptySeries.ts | 8 +- .../shared/charts/CustomPlot/index.js | 60 +- .../charts/CustomPlot/plotUtils.test.ts | 8 +- .../shared/charts/CustomPlot/plotUtils.tsx | 29 +- .../charts/CustomPlot/test/CustomPlot.test.js | 74 +- .../shared/charts/Histogram/SingleRect.js | 2 +- .../Histogram/__test__/Histogram.test.js | 43 +- .../shared/charts/Histogram/index.js | 55 +- .../components/shared/charts/Legend/index.tsx | 18 +- .../shared/charts/MetricsChart/index.tsx | 6 +- .../Timeline/Marker/AgentMarker.test.tsx | 2 +- .../Timeline/Marker/ErrorMarker.test.tsx | 10 +- .../charts/Timeline/Marker/ErrorMarker.tsx | 6 +- .../charts/Timeline/Marker/index.test.tsx | 6 +- .../shared/charts/Timeline/Timeline.test.tsx | 16 +- .../shared/charts/Timeline/TimelineAxis.tsx | 12 +- .../shared/charts/Timeline/VerticalLines.tsx | 6 +- .../shared/charts/Timeline/index.tsx | 2 +- .../shared/charts/Timeline/plotUtils.ts | 4 +- .../components/shared/charts/Tooltip/index.js | 4 +- .../TransactionCharts/BrowserLineChart.tsx | 4 +- .../ChoroplethMap/ChoroplethToolTip.tsx | 4 +- .../TransactionCharts/ChoroplethMap/index.tsx | 26 +- .../DurationByCountryMap/index.tsx | 2 +- .../TransactionLineChart/index.tsx | 4 +- .../shared/charts/TransactionCharts/index.tsx | 22 +- .../charts/helper/__test__/timezone.test.ts | 8 +- .../shared/charts/helper/timezone.ts | 4 +- .../Delayed/index.test.tsx | 8 +- .../useDelayedVisibility/Delayed/index.ts | 2 +- .../useDelayedVisibility/index.test.tsx | 18 +- .../shared/useDelayedVisibility/index.ts | 4 +- .../ApmPluginContext/MockApmPluginContext.tsx | 24 +- .../apm/public/context/ChartsSyncContext.tsx | 18 +- .../InvalidLicenseNotification.tsx | 8 +- .../context/LoadingIndicatorContext.tsx | 8 +- .../public/context/MatchedRouteContext.tsx | 6 +- .../MockUrlParamsContextProvider.tsx | 6 +- .../__tests__/UrlParamsContext.test.tsx | 22 +- .../context/UrlParamsContext/constants.ts | 2 +- .../context/UrlParamsContext/helpers.ts | 16 +- .../public/context/UrlParamsContext/index.tsx | 14 +- .../UrlParamsContext/resolveUrlParams.ts | 8 +- .../apm/public/featureCatalogueEntry.ts | 4 +- .../plugins/apm/public/hooks/useAgentName.ts | 10 +- .../hooks/useAvgDurationByBrowser.test.ts | 8 +- .../public/hooks/useAvgDurationByBrowser.ts | 14 +- .../public/hooks/useAvgDurationByCountry.ts | 12 +- .../public/hooks/useDynamicIndexPattern.ts | 10 +- .../apm/public/hooks/useEnvironments.tsx | 20 +- .../hooks/useFetcher.integration.test.tsx | 12 +- .../apm/public/hooks/useFetcher.test.tsx | 32 +- .../plugins/apm/public/hooks/useFetcher.tsx | 26 +- .../plugins/apm/public/hooks/useKibanaUrl.ts | 2 +- .../apm/public/hooks/useLoadingIndicator.ts | 2 +- .../apm/public/hooks/useLocalUIFilters.ts | 26 +- .../public/hooks/useServiceMetricCharts.ts | 12 +- .../hooks/useServiceTransactionTypes.tsx | 6 +- .../public/hooks/useTransactionBreakdown.ts | 12 +- .../apm/public/hooks/useTransactionCharts.ts | 12 +- .../hooks/useTransactionDistribution.ts | 14 +- .../apm/public/hooks/useTransactionList.ts | 16 +- .../plugins/apm/public/hooks/useWaterfall.ts | 12 +- x-pack/plugins/apm/public/index.ts | 2 +- x-pack/plugins/apm/public/plugin.ts | 24 +- .../__tests__/chartSelectors.test.ts | 74 +- .../__tests__/mockData/anomalyData.ts | 66 +- .../apm/public/selectors/chartSelectors.ts | 46 +- .../public/services/__test__/callApi.test.ts | 48 +- .../services/__test__/callApmApi.test.ts | 28 +- .../apm/public/services/rest/callApi.ts | 4 +- .../public/services/rest/createCallApmApi.ts | 2 +- .../apm/public/services/rest/index_pattern.ts | 4 +- x-pack/plugins/apm/public/services/rest/ml.ts | 24 +- .../apm/public/services/rest/watcher.ts | 4 +- x-pack/plugins/apm/public/setHelpExtension.ts | 14 +- x-pack/plugins/apm/public/style/variables.ts | 4 +- x-pack/plugins/apm/public/updateBadge.ts | 6 +- .../utils/__test__/flattenObject.test.ts | 8 +- .../formatters/__test__/datetime.test.ts | 2 +- .../formatters/__test__/duration.test.ts | 16 +- .../apm/public/utils/formatters/datetime.ts | 6 +- .../apm/public/utils/formatters/duration.ts | 26 +- .../apm/public/utils/formatters/formatters.ts | 4 +- .../public/utils/getRangeFromTimeSeries.ts | 4 +- .../apm/public/utils/httpStatusCodeToColor.ts | 2 +- .../plugins/apm/public/utils/testHelpers.tsx | 30 +- .../setup-custom-kibana-user-role.ts | 32 +- .../plugins/apm/scripts/optimize-tsconfig.js | 2 +- .../apm/scripts/optimize-tsconfig/optimize.js | 10 +- .../apm/scripts/optimize-tsconfig/paths.js | 4 +- .../scripts/optimize-tsconfig/unoptimize.js | 2 +- .../apm/scripts/setup-kibana-security.js | 4 +- x-pack/plugins/apm/scripts/storybook.js | 4 +- .../apm/scripts/unoptimize-tsconfig.js | 2 +- .../apm/scripts/upload-telemetry-data.js | 6 +- .../download-telemetry-template.ts | 4 +- .../generate-sample-documents.ts | 30 +- .../scripts/upload-telemetry-data/index.ts | 42 +- x-pack/plugins/apm/server/feature.ts | 22 +- x-pack/plugins/apm/server/index.ts | 13 +- .../server/lib/alerts/register_apm_alerts.ts | 4 +- .../alerts/register_error_rate_alert_type.ts | 48 +- ...egister_transaction_duration_alert_type.ts | 68 +- .../collect_data_telemetry/index.ts | 16 +- .../collect_data_telemetry/tasks.ts | 416 ++--- .../apm/server/lib/apm_telemetry/index.ts | 24 +- .../__tests__/get_buckets.test.ts | 24 +- .../lib/errors/distribution/get_buckets.ts | 30 +- .../errors/distribution/get_distribution.ts | 8 +- .../lib/errors/distribution/queries.test.ts | 10 +- .../apm/server/lib/errors/get_error_group.ts | 20 +- .../apm/server/lib/errors/get_error_groups.ts | 36 +- .../apm/server/lib/errors/queries.test.ts | 14 +- .../get_environment_ui_filter_es.ts | 4 +- .../convert_ui_filters/get_ui_filters_es.ts | 16 +- .../apm/server/lib/helpers/es_client.test.ts | 4 +- .../apm/server/lib/helpers/es_client.ts | 28 +- .../helpers/get_bucket_size/calculate_auto.js | 4 +- .../lib/helpers/get_bucket_size/index.ts | 2 +- .../get_bucket_size/unit_to_seconds.js | 2 +- .../server/lib/helpers/input_validation.ts | 2 +- .../plugins/apm/server/lib/helpers/metrics.ts | 2 +- .../apm/server/lib/helpers/range_filter.ts | 4 +- .../round_to_nearest_five_or_ten.test.ts | 20 +- .../server/lib/helpers/setup_request.test.ts | 80 +- .../apm/server/lib/helpers/setup_request.ts | 12 +- .../create_static_index_pattern.test.ts | 16 +- .../create_static_index_pattern.ts | 2 +- .../get_dynamic_index_pattern.ts | 14 +- .../server/lib/metrics/by_agent/default.ts | 4 +- .../java/gc/fetch_and_transform_gc_metrics.ts | 56 +- .../by_agent/java/gc/get_gc_rate_chart.ts | 14 +- .../by_agent/java/gc/get_gc_time_chart.ts | 14 +- .../by_agent/java/heap_memory/index.ts | 28 +- .../server/lib/metrics/by_agent/java/index.ts | 4 +- .../by_agent/java/non_heap_memory/index.ts | 26 +- .../by_agent/java/thread_count/index.ts | 22 +- .../lib/metrics/by_agent/shared/cpu/index.ts | 30 +- .../metrics/by_agent/shared/memory/index.ts | 34 +- .../metrics/fetch_and_transform_metrics.ts | 18 +- .../get_metrics_chart_data_by_agent.ts | 4 +- .../apm/server/lib/metrics/queries.test.ts | 12 +- .../metrics/transform_metrics_chart.test.ts | 18 +- .../lib/metrics/transform_metrics_chart.ts | 10 +- .../security/get_indices_privileges.test.ts | 64 +- .../lib/security/get_indices_privileges.ts | 10 +- .../server/lib/service_map/get_service_map.ts | 64 +- .../get_service_map_from_trace_ids.ts | 50 +- .../get_service_map_service_node_info.ts | 114 +- .../lib/service_map/get_trace_sample_ids.ts | 68 +- .../server/lib/service_map/ml_helpers.test.ts | 44 +- .../apm/server/lib/service_map/ml_helpers.ts | 10 +- .../transform_service_map_responses.test.ts | 68 +- .../transform_service_map_responses.ts | 62 +- .../apm/server/lib/service_nodes/index.ts | 38 +- .../server/lib/service_nodes/queries.test.ts | 12 +- .../get_derived_service_annotations.ts | 44 +- .../annotations/get_stored_annotations.ts | 22 +- .../lib/services/annotations/index.test.ts | 28 +- .../server/lib/services/annotations/index.ts | 10 +- .../lib/services/get_service_agent_name.ts | 20 +- .../lib/services/get_service_node_metadata.ts | 24 +- .../services/get_service_transaction_types.ts | 18 +- .../get_services/get_legacy_data_status.ts | 12 +- .../get_services/get_services_items.ts | 34 +- .../get_services/has_historical_agent_data.ts | 18 +- .../server/lib/services/get_services/index.ts | 6 +- .../apm/server/lib/services/queries.test.ts | 12 +- .../create_agent_config_index.ts | 36 +- .../create_or_update_configuration.ts | 10 +- .../delete_configuration.ts | 4 +- .../find_exact_configuration.ts | 10 +- .../get_agent_name_by_service.ts | 22 +- .../get_environments/get_all_environments.ts | 26 +- .../get_existing_environments_for_service.ts | 16 +- .../get_environments/index.ts | 8 +- .../agent_configuration/get_service_names.ts | 24 +- .../list_configurations.ts | 4 +- .../mark_applied_by_agent.ts | 6 +- .../agent_configuration/queries.test.ts | 42 +- .../search_configurations.ts | 28 +- .../settings/apm_indices/get_apm_indices.ts | 14 +- .../apm_indices/save_apm_indices.test.ts | 4 +- .../settings/apm_indices/save_apm_indices.ts | 4 +- .../custom_link/create_custom_link_index.ts | 36 +- .../create_or_update_custom_link.test.ts | 20 +- .../create_or_update_custom_link.ts | 8 +- .../settings/custom_link/custom_link_types.ts | 12 +- .../custom_link/delete_custom_link.ts | 4 +- .../custom_link/get_transaction.test.ts | 14 +- .../settings/custom_link/get_transaction.ts | 14 +- .../lib/settings/custom_link/helper.test.ts | 34 +- .../server/lib/settings/custom_link/helper.ts | 10 +- .../custom_link/list_custom_links.test.ts | 14 +- .../settings/custom_link/list_custom_links.ts | 28 +- .../apm/server/lib/traces/get_trace.ts | 2 +- .../apm/server/lib/traces/get_trace_items.ts | 42 +- .../apm/server/lib/traces/queries.test.ts | 4 +- .../lib/transaction_groups/fetcher.test.ts | 12 +- .../server/lib/transaction_groups/fetcher.ts | 30 +- .../server/lib/transaction_groups/index.ts | 4 +- .../transaction_groups_response.ts | 1012 ++++++------- .../lib/transaction_groups/queries.test.ts | 10 +- .../lib/transaction_groups/transform.test.ts | 28 +- .../lib/transaction_groups/transform.ts | 12 +- .../__fixtures__/responses.ts | 34 +- .../avg_duration_by_browser/fetcher.test.ts | 4 +- .../avg_duration_by_browser/fetcher.ts | 32 +- .../avg_duration_by_browser/index.test.ts | 4 +- .../avg_duration_by_browser/index.ts | 2 +- .../transformer.test.ts | 10 +- .../avg_duration_by_browser/transformer.ts | 8 +- .../avg_duration_by_country/index.ts | 28 +- .../lib/transactions/breakdown/index.test.ts | 28 +- .../lib/transactions/breakdown/index.ts | 80 +- .../charts/get_anomaly_data/fetcher.test.ts | 8 +- .../charts/get_anomaly_data/fetcher.ts | 28 +- .../get_anomaly_data/get_ml_bucket_size.ts | 18 +- .../charts/get_anomaly_data/index.test.ts | 14 +- .../charts/get_anomaly_data/index.ts | 8 +- .../mock_responses/ml_anomaly_response.ts | 68 +- .../mock_responses/ml_bucket_span_response.ts | 12 +- .../charts/get_anomaly_data/transform.test.ts | 86 +- .../charts/get_anomaly_data/transform.ts | 22 +- .../get_timeseries_data/fetcher.test.ts | 18 +- .../charts/get_timeseries_data/fetcher.ts | 32 +- .../charts/get_timeseries_data/index.ts | 4 +- .../mock_responses/timeseries_response.ts | 1340 ++++++++--------- .../get_timeseries_data/transform.test.ts | 48 +- .../charts/get_timeseries_data/transform.ts | 14 +- .../server/lib/transactions/charts/index.ts | 8 +- .../distribution/get_buckets/fetcher.ts | 36 +- .../distribution/get_buckets/index.ts | 2 +- .../distribution/get_buckets/transform.ts | 6 +- .../distribution/get_distribution_max.ts | 26 +- .../lib/transactions/distribution/index.ts | 6 +- .../lib/transactions/get_transaction/index.ts | 16 +- .../get_transaction_by_trace/index.ts | 24 +- .../server/lib/transactions/queries.test.ts | 28 +- .../server/lib/ui_filters/get_environments.ts | 24 +- .../lib/ui_filters/local_ui_filters/config.ts | 32 +- .../get_local_filter_query.ts | 26 +- .../lib/ui_filters/local_ui_filters/index.ts | 12 +- .../local_ui_filters/queries.test.ts | 8 +- .../apm/server/lib/ui_filters/queries.test.ts | 6 +- x-pack/plugins/apm/server/plugin.ts | 24 +- .../server/routes/create_api/index.test.ts | 108 +- .../apm/server/routes/create_api/index.ts | 28 +- .../apm/server/routes/create_apm_api.ts | 16 +- .../apm/server/routes/default_api_types.ts | 2 +- x-pack/plugins/apm/server/routes/errors.ts | 30 +- .../apm/server/routes/index_pattern.ts | 14 +- x-pack/plugins/apm/server/routes/metrics.ts | 14 +- x-pack/plugins/apm/server/routes/security.ts | 4 +- .../plugins/apm/server/routes/service_map.ts | 26 +- .../apm/server/routes/service_nodes.ts | 10 +- x-pack/plugins/apm/server/routes/services.ts | 62 +- .../routes/settings/agent_configuration.ts | 54 +- .../apm/server/routes/settings/apm_indices.ts | 18 +- .../apm/server/routes/settings/custom_link.ts | 40 +- x-pack/plugins/apm/server/routes/traces.ts | 10 +- .../plugins/apm/server/routes/transaction.ts | 6 +- .../apm/server/routes/transaction_groups.ts | 76 +- x-pack/plugins/apm/server/routes/typings.ts | 2 +- .../plugins/apm/server/routes/ui_filters.ts | 78 +- .../apm/server/saved_objects/apm_indices.ts | 18 +- .../apm/server/saved_objects/apm_telemetry.ts | 692 ++++----- .../apm/server/tutorial/elastic_cloud.ts | 42 +- .../components/autocomplete_field/index.tsx | 12 +- .../autocomplete_field/suggestion_item.tsx | 22 +- .../public/components/config_list.tsx | 4 +- .../public/components/enroll_beats.tsx | 2 +- .../public/components/layouts/walkthrough.tsx | 2 +- .../navigation/breadcrumb/breadcrumb.tsx | 2 +- .../navigation/breadcrumb/provider.tsx | 2 +- .../components/navigation/child_routes.tsx | 4 +- .../table/controls/tag_badge_list.tsx | 2 +- .../public/components/table/table.tsx | 2 +- .../components/table/table_type_configs.tsx | 2 +- .../tag/config_view/config_form.tsx | 2 +- .../components/tag/config_view/index.tsx | 8 +- .../public/containers/beats.ts | 4 +- .../public/containers/tags.ts | 2 +- .../containers/with_kuery_autocompletion.tsx | 2 +- .../adapters/beats/memory_beats_adapter.ts | 26 +- .../memory_config_blocks_adapter.ts | 6 +- .../lib/adapters/framework/adapter_types.ts | 2 +- .../framework/kibana_framework_adapter.ts | 2 +- .../rest_api/axios_rest_api_adapter.ts | 16 +- .../rest_api/node_axios_api_adapter.ts | 16 +- .../lib/adapters/tags/memory_tags_adapter.ts | 6 +- .../lib/adapters/tags/rest_tags_adapter.ts | 2 +- .../adapters/tokens/rest_tokens_adapter.ts | 2 +- .../public/lib/configuration_blocks.ts | 12 +- .../public/lib/elasticsearch.ts | 2 +- .../public/pages/beat/details.tsx | 8 +- .../pages/overview/configuration_tags.tsx | 2 +- .../public/pages/overview/enrolled_beats.tsx | 10 +- .../public/pages/tag/create.tsx | 12 +- .../public/pages/tag/edit.tsx | 10 +- .../pages/walkthrough/initial/index.tsx | 2 +- .../public/pages/walkthrough/initial/tag.tsx | 10 +- .../beats_management/public/router.tsx | 8 +- .../public/utils/random_eui_color.ts | 4 +- .../__tests__/fixtures/function_specs.ts | 2 +- .../canvas/__tests__/fixtures/kibana.js | 6 +- .../__tests__/helpers/function_wrapper.js | 2 +- .../canvas_plugin_src/elements/index.ts | 2 +- .../functions/browser/location.ts | 2 +- .../functions/browser/markdown.test.js | 2 +- .../functions/browser/markdown.ts | 4 +- .../functions/common/__tests__/progress.js | 4 +- .../functions/common/alterColumn.ts | 4 +- .../functions/common/columns.ts | 12 +- .../functions/common/context.ts | 2 +- .../canvas_plugin_src/functions/common/do.ts | 2 +- .../functions/common/dropdownControl.ts | 2 +- .../functions/common/filterrows.test.js | 10 +- .../functions/common/filterrows.ts | 6 +- .../functions/common/join_rows.ts | 2 +- .../functions/common/mapColumn.test.js | 10 +- .../functions/common/mapColumn.ts | 6 +- .../functions/common/math.ts | 2 +- .../functions/common/pie.test.js | 2 +- .../canvas_plugin_src/functions/common/pie.ts | 2 +- .../functions/common/plot.test.js | 2 +- .../functions/common/plot/get_tick_hash.ts | 4 +- .../functions/common/plot/index.ts | 2 +- .../functions/common/ply.test.js | 18 +- .../canvas_plugin_src/functions/common/ply.ts | 22 +- .../functions/common/rowCount.ts | 2 +- .../functions/common/staticColumn.test.js | 10 +- .../functions/common/staticColumn.ts | 2 +- .../functions/common/switch.test.js | 6 +- .../functions/common/timefilter.test.js | 4 +- .../functions/server/esdocs.ts | 6 +- .../functions/server/pointseries/index.ts | 16 +- .../component/advanced_filter.tsx | 4 +- .../component/dropdown_filter.tsx | 4 +- .../renderers/embeddable/embeddable.tsx | 4 +- .../visualization.test.ts | 4 +- .../renderers/error/index.js | 2 +- .../component/__examples__/metric.stories.tsx | 2 +- .../canvas_plugin_src/renderers/pie/index.js | 2 +- .../renderers/pie/plugins/pie.js | 24 +- .../canvas_plugin_src/renderers/plot/index.js | 2 +- .../renderers/plot/plugins/size.js | 4 +- .../renderers/plot/plugins/text.js | 15 +- .../renderers/progress/index.js | 2 +- .../renderers/repeat_image.js | 4 +- .../renderers/reveal_image/index.js | 2 +- .../renderers/shape/index.js | 2 +- .../__examples__/time_filter.stories.tsx | 2 +- .../extended_template.stories.tsx | 6 +- .../__examples__/simple_template.stories.tsx | 6 +- .../datacolumn/__tests__/get_form_object.js | 4 +- .../uis/arguments/datacolumn/index.js | 17 +- .../uis/arguments/date_format/index.ts | 2 +- .../uis/arguments/filter_group.js | 8 +- .../uis/arguments/image_upload/index.js | 12 +- .../canvas_plugin_src/uis/arguments/index.ts | 2 +- .../canvas_plugin_src/uis/arguments/number.js | 2 +- .../uis/arguments/palette.js | 2 +- .../uis/arguments/percentage.js | 2 +- .../canvas_plugin_src/uis/arguments/range.js | 2 +- .../canvas_plugin_src/uis/arguments/select.js | 2 +- .../canvas_plugin_src/uis/arguments/string.js | 2 +- .../uis/arguments/textarea.js | 2 +- .../uis/datasources/esdocs.js | 14 +- .../uis/datasources/essql.js | 2 +- .../uis/datasources/timelion.js | 4 +- .../canvas_plugin_src/uis/views/index.ts | 2 +- .../canvas/canvas_plugin_src/uis/views/pie.js | 2 +- .../canvas_plugin_src/uis/views/plot.js | 2 +- .../canvas_plugin_src/uis/views/progress.js | 2 +- .../canvas_plugin_src/uis/views/table.js | 2 +- .../canvas/common/lib/autocomplete.test.ts | 32 +- .../plugins/canvas/common/lib/autocomplete.ts | 12 +- .../canvas/common/lib/datatable/query.js | 8 +- x-pack/plugins/canvas/common/lib/dataurl.ts | 2 +- .../canvas/common/lib/get_field_type.ts | 2 +- .../plugins/canvas/common/lib/hex_to_rgb.ts | 4 +- .../canvas/common/lib/pivot_object_array.ts | 2 +- .../canvas/i18n/elements/apply_strings.ts | 2 +- .../i18n/elements/element_strings.test.ts | 10 +- .../i18n/functions/dict/alter_column.ts | 2 +- .../canvas/i18n/functions/dict/axis_config.ts | 2 +- .../plugins/canvas/i18n/functions/dict/pie.ts | 2 +- .../canvas/i18n/functions/dict/plot.ts | 2 +- .../canvas/i18n/functions/dict/progress.ts | 2 +- .../i18n/functions/dict/reveal_image.ts | 2 +- .../canvas/i18n/templates/apply_strings.ts | 4 +- .../i18n/templates/template_strings.test.ts | 10 +- x-pack/plugins/canvas/public/application.tsx | 2 +- .../canvas/public/apps/export/export/index.js | 4 +- .../canvas/public/apps/export/routes.js | 2 +- .../canvas/public/apps/home/home_app/index.js | 2 +- .../canvas/public/apps/workpad/routes.js | 2 +- .../public/apps/workpad/workpad_app/index.js | 4 +- .../workpad/workpad_app/workpad_telemetry.tsx | 4 +- .../canvas/public/components/app/app.js | 2 +- .../canvas/public/components/app/index.js | 8 +- .../arg_add_popover/arg_add_popover.tsx | 2 +- .../components/arg_form/advanced_failure.js | 10 +- .../public/components/arg_form/arg_form.js | 2 +- .../public/components/arg_form/arg_label.js | 2 +- .../components/arg_form/arg_template_form.js | 4 +- .../public/components/arg_form/index.js | 2 +- .../components/arg_form/pending_arg_value.js | 2 +- .../__examples__/asset.examples.tsx | 2 +- .../public/components/asset_manager/asset.tsx | 2 +- .../asset_manager/asset_manager.tsx | 2 +- .../components/asset_manager/asset_modal.tsx | 4 +- .../public/components/asset_manager/index.ts | 2 +- .../components/asset_picker/asset_picker.tsx | 2 +- .../components/autocomplete/autocomplete.js | 6 +- .../__examples__/color_manager.stories.tsx | 2 +- .../color_manager/color_manager.tsx | 2 +- .../__examples__/color_palette.stories.tsx | 2 +- .../color_palette/color_palette.tsx | 4 +- .../__examples__/color_picker.stories.tsx | 8 +- .../components/color_picker/color_picker.tsx | 4 +- .../color_picker_popover.stories.tsx | 2 +- .../confirm_modal/confirm_modal.tsx | 2 +- .../custom_element_modal.tsx | 4 +- .../datasource/datasource_component.js | 6 +- .../datasource/datasource_selector.js | 2 +- .../public/components/datasource/index.js | 12 +- .../public/components/datatable/datatable.js | 10 +- .../components/dom_preview/dom_preview.js | 4 +- .../__examples__/element_card.stories.tsx | 2 +- .../public/components/element_config/index.js | 2 +- .../components/element_content/index.js | 2 +- .../element_share_container.js | 2 +- .../element_wrapper/element_wrapper.js | 2 +- .../components/element_wrapper/index.js | 4 +- .../element_wrapper/lib/handlers.js | 4 +- .../components/embeddable_flyout/flyout.tsx | 8 +- .../components/enhance/error_boundary.tsx | 4 +- .../components/enhance/stateful_prop.js | 6 +- .../es_field_select/es_field_select.js | 4 +- .../components/es_field_select/index.js | 2 +- .../es_fields_select/es_fields_select.js | 6 +- .../components/es_fields_select/index.js | 2 +- .../es_index_select/es_index_select.js | 6 +- .../components/expression/expression.js | 2 +- .../public/components/expression/index.js | 16 +- .../components/file_upload/file_upload.tsx | 2 +- .../components/font_picker/font_picker.tsx | 6 +- .../public/components/fullscreen/index.js | 2 +- .../components/function_form/function_form.js | 2 +- .../function_form/function_form_component.js | 2 +- .../public/components/function_form/index.js | 4 +- .../function_form_list/function_form_list.js | 2 +- .../components/function_form_list/index.js | 4 +- .../__examples__/item_grid.stories.tsx | 8 +- .../keyboard_shortcuts_doc.tsx | 4 +- .../canvas/public/components/link/link.js | 4 +- .../public/components/page_config/index.js | 6 +- .../components/page_config/page_config.js | 2 +- .../public/components/page_manager/index.js | 8 +- .../components/page_manager/page_manager.js | 10 +- .../components/page_preview/page_controls.js | 4 +- .../public/components/paginate/paginate.js | 4 +- .../palette_picker/palette_picker.js | 2 +- .../palette_swatch/palette_swatch.js | 2 +- .../components/positionable/positionable.js | 2 +- .../components/render_to_dom/render_to_dom.js | 2 +- .../public/components/render_with_fn/index.js | 2 +- .../render_with_fn/render_with_fn.js | 6 +- .../canvas/public/components/router/router.js | 4 +- .../__examples__/element_controls.stories.tsx | 2 +- .../__examples__/element_grid.stories.tsx | 2 +- .../components/shape_picker/shape_picker.tsx | 2 +- .../shape_picker_popover.stories.tsx | 2 +- .../sidebar/element_settings/index.tsx | 2 +- .../components/sidebar/sidebar_content.js | 2 +- .../__examples__/sidebar_header.stories.tsx | 2 +- .../public/components/sidebar_header/index.js | 20 +- .../text_style_picker/text_style_picker.js | 12 +- .../tool_tip_shortcut.stories.tsx | 2 +- .../canvas/public/components/toolbar/index.js | 8 +- .../canvas/public/components/workpad/index.js | 10 +- .../public/components/workpad_config/index.js | 8 +- .../workpad_config/workpad_config.js | 8 +- .../workpad_header/edit_menu/index.ts | 8 +- .../fullscreen_control/index.js | 16 +- .../workpad_header/share_menu/flyout/index.ts | 6 +- .../workpad_header/share_menu/index.ts | 6 +- .../workpad_header/share_menu/utils.test.ts | 2 +- .../view_menu/auto_refresh_controls.tsx | 2 +- .../view_menu/custom_interval.tsx | 2 +- .../view_menu/kiosk_controls.tsx | 2 +- .../workpad_header/view_menu/view_menu.tsx | 2 +- .../public/components/workpad_loader/index.js | 22 +- .../workpad_loader/workpad_loader.js | 18 +- .../workpad_loader/workpad_search.js | 2 +- .../workpad_page/integration_utils.js | 49 +- .../public/components/workpad_page/utils.js | 4 +- .../event_handlers.js | 11 +- .../workpad_interactive_page/index.js | 36 +- .../interactive_workpad_page.js | 6 +- .../static_workpad_page.js | 4 +- .../components/workpad_templates/index.js | 4 +- .../workpad_templates/workpad_templates.js | 8 +- .../extended_template.examples.tsx | 8 +- .../__examples__/simple_template.examples.tsx | 8 +- .../arg_types/container_style/border_form.tsx | 6 +- .../container_style/simple_template.tsx | 2 +- .../public/expression_types/arg_types/font.js | 4 +- .../extended_template.examples.tsx | 6 +- .../__examples__/simple_template.examples.tsx | 6 +- .../series_style/extended_template.tsx | 14 +- .../series_style/simple_template.tsx | 4 +- .../public/expression_types/datasource.js | 2 +- .../public/expression_types/function_form.js | 14 +- .../canvas/public/expression_types/model.js | 2 +- .../public/functions/__tests__/asset.js | 2 +- .../canvas/public/functions/filters.ts | 2 +- .../canvas/public/functions/timelion.ts | 10 +- .../public/lib/__tests__/history_provider.js | 12 +- .../__fixtures__/typescript/typespec_tests.ts | 2 +- .../canvas/public/lib/aeroelastic/common.js | 6 +- .../public/lib/aeroelastic/functional.js | 20 +- .../canvas/public/lib/aeroelastic/geometry.js | 6 +- .../canvas/public/lib/aeroelastic/gestures.js | 24 +- .../lib/aeroelastic/layout_functions.js | 254 ++-- .../canvas/public/lib/aeroelastic/select.ts | 2 +- .../plugins/canvas/public/lib/arg_helpers.js | 4 +- .../canvas/public/lib/build_bool_array.js | 4 +- .../public/lib/build_embeddable_filters.ts | 4 +- .../canvas/public/lib/clone_subgraphs.js | 8 +- .../public/lib/custom_element_service.ts | 2 +- x-pack/plugins/canvas/public/lib/doc_title.js | 2 +- .../public/lib/element_handler_creators.ts | 21 +- .../plugins/canvas/public/lib/es_service.ts | 16 +- .../canvas/public/lib/extract_search.js | 4 +- .../canvas/public/lib/find_existing_asset.js | 2 +- .../canvas/public/lib/find_expression_type.js | 2 +- .../canvas/public/lib/history_provider.js | 4 +- x-pack/plugins/canvas/public/lib/keymap.ts | 12 +- .../public/lib/load_expression_types.js | 2 +- .../canvas/public/lib/load_transitions.js | 2 +- .../canvas/public/lib/monaco_language_def.ts | 2 +- .../public/lib/parse_single_function_chain.js | 2 +- .../canvas/public/lib/router_provider.js | 6 +- .../canvas/public/lib/run_interpreter.ts | 4 +- x-pack/plugins/canvas/public/lib/template.js | 2 +- .../lib/template_from_react_component.tsx | 2 +- .../canvas/public/lib/window_error_handler.js | 10 +- .../canvas/public/lib/workpad_service.js | 8 +- x-pack/plugins/canvas/public/plugin_api.ts | 28 +- .../canvas/public/state/actions/elements.js | 42 +- .../canvas/public/state/actions/embeddable.ts | 6 +- .../canvas/public/state/initial_state.js | 2 +- .../public/state/middleware/app_ready.js | 2 +- .../public/state/middleware/breadcrumbs.js | 2 +- .../public/state/middleware/element_stats.js | 2 +- .../public/state/middleware/es_persist.js | 6 +- .../public/state/middleware/fullscreen.js | 2 +- .../canvas/public/state/middleware/history.js | 6 +- .../public/state/middleware/resolved_args.js | 8 +- .../state/middleware/workpad_autoplay.ts | 4 +- .../state/middleware/workpad_refresh.ts | 4 +- .../public/state/middleware/workpad_update.js | 2 +- .../__tests__/fixtures/action_creator.js | 2 +- .../canvas/public/state/reducers/app.js | 2 +- .../canvas/public/state/reducers/elements.js | 22 +- .../public/state/reducers/embeddable.ts | 8 +- .../canvas/public/state/reducers/pages.js | 14 +- .../public/state/reducers/resolved_args.js | 4 +- .../canvas/public/state/reducers/transient.js | 10 +- .../state/selectors/__tests__/workpad.js | 2 +- .../canvas/public/state/selectors/workpad.ts | 28 +- x-pack/plugins/canvas/public/state/store.js | 2 +- x-pack/plugins/canvas/scripts/_helpers.js | 6 +- .../canvas/server/collectors/collector.ts | 2 +- .../server/collectors/collector_helpers.ts | 4 +- .../custom_element_collector.test.ts | 2 +- .../collectors/custom_element_collector.ts | 8 +- .../server/collectors/workpad_collector.ts | 10 +- .../canvas/server/lib/build_bool_array.js | 4 +- .../canvas/server/lib/format_response.js | 2 +- .../canvas/server/lib/normalize_type.js | 2 +- .../plugins/canvas/server/lib/query_es_sql.js | 8 +- .../canvas/server/lib/sanitize_name.js | 2 +- .../server/routes/catch_error_handler.ts | 2 +- .../server/routes/custom_elements/find.ts | 2 +- .../server/routes/es_fields/es_fields.ts | 4 +- .../canvas/server/routes/workpad/find.ts | 2 +- .../canvas/server/routes/workpad/get.ts | 2 +- .../server/sample_data/load_sample_data.ts | 2 +- .../migrations/remove_attributes_id.ts | 2 +- .../__mocks__/supported_renderers.js | 4 +- .../api/__tests__/shareable.test.tsx | 2 +- .../shareable_runtime/api/shareable.tsx | 4 +- .../shareable_runtime/components/app.tsx | 2 +- .../shareable_runtime/components/canvas.tsx | 5 +- .../settings/__tests__/settings.test.tsx | 4 +- .../plugins/canvas/shareable_runtime/index.ts | 4 +- .../shareable_runtime/postcss.config.js | 2 +- .../shareable_runtime/supported_renderers.js | 2 +- .../canvas/shareable_runtime/test/context.tsx | 2 +- .../shareable_runtime/test/interactions.ts | 12 +- .../shareable_runtime/test/selectors.ts | 12 +- .../canvas/shareable_runtime/test/utils.ts | 2 +- .../canvas/tasks/mocks/downloadWorkpad.js | 8 +- x-pack/plugins/canvas/tasks/mocks/uiNotify.js | 6 +- .../canvas/tasks/mocks/uiNotifyFormatMsg.js | 2 +- .../plugins/case/common/api/saved_object.ts | 2 +- x-pack/plugins/case/server/plugin.ts | 6 +- .../__fixtures__/create_mock_so_repository.ts | 24 +- .../api/cases/comments/delete_all_comments.ts | 4 +- .../api/cases/comments/delete_comment.ts | 2 +- .../api/cases/comments/get_comment.test.ts | 2 +- .../api/cases/comments/patch_comment.ts | 2 +- .../cases/configure/get_connectors.test.ts | 2 +- .../api/cases/configure/get_connectors.ts | 2 +- .../api/cases/configure/post_configure.ts | 2 +- .../server/routes/api/cases/delete_cases.ts | 10 +- .../server/routes/api/cases/find_cases.ts | 10 +- .../server/routes/api/cases/get_case.test.ts | 2 +- .../case/server/routes/api/cases/helpers.ts | 4 +- .../server/routes/api/cases/patch_cases.ts | 26 +- .../case/server/routes/api/cases/push_case.ts | 10 +- .../user_actions/get_all_user_actions.ts | 7 +- .../plugins/case/server/routes/api/utils.ts | 2 +- x-pack/plugins/case/server/services/index.ts | 14 +- .../services/reporters/read_reporters.ts | 2 +- .../server/services/user_actions/helpers.ts | 4 +- .../server/services/user_actions/index.ts | 2 +- .../console_extensions/server/plugin.ts | 2 +- .../common/services/utils.ts | 2 +- .../auto_follow_pattern_add.test.js | 2 +- .../auto_follow_pattern_list.test.js | 8 +- .../follower_index_add.test.js | 8 +- .../follower_indices_list.test.js | 14 +- .../auto_follow_pattern_add.helpers.js | 4 +- .../auto_follow_pattern_edit.helpers.js | 4 +- .../auto_follow_pattern_list.helpers.js | 4 +- .../helpers/follower_index_add.helpers.js | 4 +- .../helpers/follower_index_edit.helpers.js | 4 +- .../helpers/follower_index_list.helpers.js | 9 +- .../helpers/home.helpers.js | 2 +- .../helpers/http_requests.js | 14 +- .../mocks/track_ui_metric.mock.ts | 2 +- .../auto_follow_pattern_delete_provider.js | 10 +- .../components/auto_follow_pattern_form.js | 34 +- .../advanced_settings_fields.js | 2 +- .../follower_index_form.js | 26 +- .../follower_index_pause_provider.js | 14 +- .../follower_index_resume_provider.js | 10 +- .../follower_index_unfollow_provider.js | 10 +- .../public/app/components/form_entry_row.js | 10 +- .../components/remote_clusters_form_field.js | 14 +- .../components/remote_clusters_provider.js | 6 +- .../auto_follow_pattern_add.container.js | 4 +- .../auto_follow_pattern_edit.container.js | 8 +- .../follower_index_add.container.js | 4 +- .../follower_index_edit.container.js | 8 +- .../auto_follow_pattern_list.container.js | 8 +- .../auto_follow_pattern_table.container.js | 10 +- .../auto_follow_pattern_table.js | 22 +- .../detail_panel/detail_panel.container.js | 2 +- .../components/context_menu/context_menu.js | 14 +- .../detail_panel/detail_panel.container.js | 2 +- .../follower_indices_table.container.js | 6 +- .../follower_indices_table.js | 22 +- .../follower_indices_list.container.js | 8 +- .../app/sections/home/home.container.js | 2 +- .../public/app/sections/home/home.js | 4 +- .../public/app/services/api.js | 34 +- .../public/app/services/auto_follow_errors.js | 4 +- .../app/services/auto_follow_pattern.js | 18 +- .../app/services/auto_follow_pattern.test.js | 26 +- .../auto_follow_pattern_validators.js | 10 +- .../follower_index_default_settings.js | 6 +- .../app/services/get_remote_cluster_name.js | 4 +- .../public/app/services/input_validation.js | 12 +- .../public/app/services/routing.js | 6 +- .../public/app/services/track_ui_metric.ts | 2 +- .../public/app/services/utils.js | 2 +- .../public/app/store/actions/api.js | 5 +- .../app/store/actions/auto_follow_pattern.js | 16 +- .../app/store/actions/follower_index.js | 12 +- .../app/store/reducers/auto_follow_pattern.js | 8 +- .../app/store/reducers/follower_index.js | 6 +- .../public/app/store/reducers/stats.js | 2 +- .../public/app/store/selectors/index.js | 38 +- .../public/plugin.ts | 2 +- .../server/plugin.ts | 4 +- .../register_delete_route.ts | 2 +- .../register_pause_route.ts | 4 +- .../register_resume_route.ts | 2 +- .../follower_index/register_pause_route.ts | 2 +- .../follower_index/register_resume_route.ts | 2 +- .../server/services/license.ts | 2 +- .../components/collect_config_container.tsx | 2 +- .../dashboard_drilldown_config.story.tsx | 10 +- .../dashboard_drilldown_config.tsx | 2 +- .../drilldown.tsx | 4 +- .../kql_query_suggestion/conjunction.test.ts | 8 +- .../kql_query_suggestion/conjunction.tsx | 2 +- .../kql_query_suggestion/field.test.ts | 2 +- .../providers/kql_query_suggestion/field.tsx | 14 +- .../providers/kql_query_suggestion/index.ts | 4 +- .../kql_query_suggestion/lib/escape_kuery.ts | 5 +- .../kql_query_suggestion/operator.test.ts | 2 +- .../kql_query_suggestion/operator.tsx | 10 +- .../kql_query_suggestion/sort_prefix_first.ts | 2 +- .../providers/kql_query_suggestion/value.ts | 18 +- .../public/search/search_interceptor.test.ts | 2 +- .../public/search/search_interceptor.ts | 2 +- .../server/search/es_search_strategy.ts | 2 +- ...onnected_flyout_manage_drilldowns.test.tsx | 2 +- .../connected_flyout_manage_drilldowns.tsx | 8 +- .../test_data.ts | 6 +- .../form_drilldown_wizard.tsx | 6 +- .../list_manage_drilldowns.tsx | 4 +- .../embeddables/embeddable_action_storage.ts | 4 +- .../embeddable_enhanced/public/plugin.ts | 4 +- .../server/config.test.ts | 8 +- .../encrypted_saved_objects/server/config.ts | 2 +- .../server/crypto/index.mock.ts | 4 +- .../encrypted_saved_objects/server/mocks.ts | 2 +- ...ypted_saved_objects_client_wrapper.test.ts | 6 +- .../encrypted_saved_objects_client_wrapper.ts | 4 +- .../server/saved_objects/index.ts | 2 +- .../server/es/cluster_client_adapter.test.ts | 12 +- .../server/es/cluster_client_adapter.ts | 2 +- .../event_log/server/event_log_client.test.ts | 8 +- x-pack/plugins/event_log/server/lib/delay.ts | 2 +- .../event_log/server/lib/ready_signal.test.ts | 2 +- .../event_log/server/lib/ready_signal.ts | 2 +- .../plugins/event_log/server/routes/find.ts | 2 +- x-pack/plugins/features/common/feature.ts | 2 +- .../public/features_api_client.test.ts | 2 +- .../features/public/features_api_client.ts | 2 +- .../features/server/feature_registry.test.ts | 4 +- .../features/server/feature_registry.ts | 8 +- .../plugins/features/server/feature_schema.ts | 70 +- .../features/server/oss_features.test.ts | 8 +- x-pack/plugins/features/server/plugin.test.ts | 8 +- x-pack/plugins/features/server/plugin.ts | 4 +- .../features/server/routes/index.test.ts | 8 +- .../plugins/features/server/routes/index.ts | 4 +- .../server/ui_capabilities_for_features.ts | 8 +- .../public/components/index_settings.js | 6 +- .../components/json_index_file_picker.js | 8 +- .../components/json_upload_and_parse.js | 12 +- .../file_upload/public/util/file_parser.js | 4 +- .../public/util/file_parser.test.js | 6 +- .../util/geo_json_clean_and_validate.test.js | 6 +- .../public/util/indexing_service.js | 4 +- .../public/util/indexing_service.test.js | 4 +- .../file_upload/public/util/pattern_reader.js | 4 +- .../public/util/size_limited_chunking.test.js | 2 +- .../client/call_with_request_factory.js | 2 +- .../server/kibana_server_services.js | 4 +- .../file_upload/server/routes/file_upload.js | 2 +- .../public/angular/graph_client_workspace.js | 254 ++-- .../angular/graph_client_workspace.test.js | 22 +- x-pack/plugins/graph/public/app.js | 88 +- x-pack/plugins/graph/public/application.ts | 2 +- .../components/field_manager/field_editor.tsx | 10 +- .../field_manager/field_manager.test.tsx | 74 +- .../field_manager/field_manager.tsx | 4 +- .../components/field_manager/field_picker.tsx | 8 +- .../graph_visualization.test.tsx | 10 +- .../graph_visualization.tsx | 14 +- .../guidance_panel/guidance_panel.tsx | 2 +- .../graph/public/components/helpers.ts | 2 +- .../graph/public/components/save_modal.tsx | 6 +- .../public/components/search_bar.test.tsx | 2 +- .../graph/public/components/search_bar.tsx | 4 +- .../settings/advanced_settings_form.tsx | 6 +- .../components/settings/blacklist_form.tsx | 4 +- .../components/settings/settings.test.tsx | 39 +- .../public/components/settings/settings.tsx | 2 +- .../components/settings/url_template_form.tsx | 18 +- .../components/settings/url_template_list.tsx | 8 +- .../settings/use_list_keys.test.tsx | 6 +- .../components/settings/use_list_keys.ts | 2 +- .../graph/public/components/source_picker.tsx | 2 +- .../graph/public/helpers/as_observable.ts | 2 +- .../graph/public/helpers/kql_encoder.ts | 2 +- .../graph/public/helpers/outlink_encoders.ts | 2 +- .../public/helpers/saved_workspace_utils.ts | 4 +- .../graph/public/helpers/style_choices.ts | 6 +- x-pack/plugins/graph/public/plugin.ts | 2 +- .../graph/public/services/fetch_top_nodes.ts | 6 +- .../services/persistence/deserialize.ts | 24 +- .../persistence/saved_workspace_references.ts | 2 +- .../public/services/persistence/serialize.ts | 6 +- .../graph/public/services/save_modal.tsx | 2 +- .../graph/public/services/source_modal.tsx | 2 +- .../state_management/advanced_settings.ts | 2 +- .../state_management/datasource.sagas.ts | 2 +- .../state_management/datasource.test.ts | 2 +- .../public/state_management/datasource.ts | 4 +- .../graph/public/state_management/fields.ts | 24 +- .../graph/public/state_management/helpers.ts | 2 +- .../public/state_management/meta_data.ts | 2 +- .../graph/public/state_management/mocks.ts | 2 +- .../state_management/persistence.test.ts | 2 +- .../public/state_management/persistence.ts | 4 +- .../public/state_management/url_templates.ts | 8 +- .../public/state_management/workspace.ts | 2 +- x-pack/plugins/graph/server/routes/explore.ts | 2 +- .../sample_data/register_sample_data.ts | 2 +- .../components/grok_debugger/grok_debugger.js | 8 +- x-pack/plugins/grokdebugger/public/plugin.js | 2 +- .../grokdebugger/grokdebugger_service.js | 4 +- x-pack/plugins/grokdebugger/server/plugin.js | 2 +- .../__jest__/components/edit_policy.test.js | 12 +- .../__jest__/components/policy_table.test.js | 20 +- .../__jest__/extend_index_management.test.js | 2 +- .../cold_phase/cold_phase.container.js | 2 +- .../components/cold_phase/cold_phase.js | 6 +- .../delete_phase/delete_phase.container.js | 2 +- .../components/delete_phase/delete_phase.js | 2 +- .../hot_phase/hot_phase.container.js | 4 +- .../components/hot_phase/hot_phase.js | 12 +- .../edit_policy/components/min_age_input.js | 6 +- .../node_allocation.container.js | 2 +- .../node_allocation/node_allocation.js | 2 +- .../components/set_priority_input.js | 4 +- .../warm_phase/warm_phase.container.js | 2 +- .../components/warm_phase/warm_phase.js | 14 +- .../edit_policy/edit_policy.container.js | 2 +- .../sections/edit_policy/edit_policy.js | 10 +- .../sections/edit_policy/form_errors.js | 2 +- .../add_policy_to_template_confirm_modal.js | 6 +- .../policy_table/policy_table.container.js | 12 +- .../components/policy_table/policy_table.js | 16 +- .../public/application/services/api.js | 8 +- .../application/services/filter_items.js | 4 +- .../services/flatten_panel_tree.js | 2 +- .../public/application/services/sort_table.js | 4 +- .../public/application/services/ui_metric.ts | 2 +- .../public/application/store/actions/nodes.js | 4 +- .../application/store/actions/policies.js | 2 +- .../application/store/selectors/general.js | 6 +- .../application/store/selectors/lifecycle.js | 6 +- .../application/store/selectors/nodes.js | 14 +- .../application/store/selectors/policies.js | 40 +- .../components/add_lifecycle_confirm_modal.js | 10 +- .../remove_lifecycle_confirm_modal.js | 2 +- .../public/extend_index_management/index.js | 22 +- .../api/templates/register_fetch_route.ts | 2 +- .../server/services/license.ts | 2 +- .../helpers/home.helpers.ts | 14 +- .../helpers/template_form.helpers.ts | 16 +- .../__jest__/client_integration/home.test.ts | 10 +- .../template_create.test.tsx | 2 +- .../__jest__/components/index_table.test.js | 38 +- .../datatypes/text_datatype.test.tsx | 2 +- .../helpers/mappings_editor.helpers.tsx | 4 +- .../mappings_editor.test.tsx | 2 +- .../configuration_form/configuration_form.tsx | 2 +- .../configuration_form_schema.tsx | 2 +- .../dynamic_mapping_section.tsx | 2 +- .../source_field_section.tsx | 6 +- .../document_fields_header.tsx | 2 +- .../field_parameters/analyzer_parameter.tsx | 4 +- .../analyzer_parameter_selects.tsx | 6 +- .../field_parameters/dynamic_parameter.tsx | 2 +- .../field_parameters/format_parameter.tsx | 8 +- .../field_parameters/index_parameter.tsx | 4 +- .../field_parameters/path_parameter.tsx | 4 +- .../field_parameters/subtype_parameter.tsx | 6 +- .../term_vector_parameter.tsx | 2 +- .../field_parameters/type_parameter.tsx | 2 +- .../fields/create_field/create_field.tsx | 2 +- .../fields/delete_field_provider.tsx | 4 +- .../fields/edit_field/edit_field.tsx | 2 +- .../edit_field/edit_field_container.tsx | 2 +- .../fields/edit_field/edit_field_form_row.tsx | 4 +- .../edit_field/update_field_provider.tsx | 6 +- .../fields/field_types/numeric_type.tsx | 2 +- .../fields/field_types/range_type.tsx | 4 +- .../fields/field_types/text_type.tsx | 2 +- .../fields/fields_list_item.tsx | 2 +- .../modal_confirmation_delete_fields.tsx | 2 +- .../search_fields/search_result_item.tsx | 2 +- .../load_mappings/load_from_json_button.tsx | 2 +- .../load_mappings_provider.test.tsx | 2 +- .../load_mappings/load_mappings_provider.tsx | 2 +- .../templates_form/templates_form.tsx | 2 +- .../constants/data_types_definition.tsx | 2 +- .../constants/field_options.tsx | 2 +- .../constants/parameters_definition.tsx | 14 +- .../mappings_editor/lib/error_reporter.ts | 2 +- .../lib/extract_mappings_definition.ts | 2 +- .../lib/mappings_validator.test.ts | 10 +- .../mappings_editor/lib/mappings_validator.ts | 12 +- .../mappings_editor/lib/search_fields.tsx | 4 +- .../components/mappings_editor/lib/utils.ts | 24 +- .../mappings_editor/lib/validators.ts | 8 +- .../mappings_editor/mappings_state.tsx | 6 +- .../components/mappings_editor/reducer.ts | 16 +- .../components/template_delete_modal.tsx | 2 +- .../template_form/steps/step_review.tsx | 2 +- .../template_form/template_form.tsx | 2 +- .../template_form/template_steps.tsx | 2 +- .../public/application/lib/ace.js | 6 +- .../public/application/lib/flatten_object.js | 2 +- .../application/lib/flatten_panel_tree.js | 2 +- .../public/application/sections/home/home.tsx | 2 +- .../detail_panel/detail_panel.container.js | 18 +- .../edit_settings_json.container.js | 2 +- .../edit_settings_json/edit_settings_json.js | 6 +- .../show_json/show_json.container.js | 2 +- .../detail_panel/summary/summary.container.js | 2 +- .../index_actions_context_menu.container.js | 4 +- .../index_actions_context_menu.js | 34 +- .../index_table/index_table.container.js | 14 +- .../index_list/index_table/index_table.js | 28 +- .../template_details/template_details.tsx | 6 +- .../home/template_list/template_list.tsx | 4 +- .../template_table/template_table.tsx | 6 +- .../store/actions/clear_cache_indices.js | 2 +- .../store/actions/close_indices.js | 2 +- .../store/actions/delete_indices.js | 2 +- .../store/actions/edit_index_settings.js | 2 +- .../store/actions/extension_action.js | 8 +- .../store/actions/flush_indices.js | 2 +- .../store/actions/forcemerge_indices.js | 2 +- .../store/actions/freeze_indices.js | 2 +- .../store/actions/load_index_data.js | 2 +- .../application/store/actions/load_indices.js | 2 +- .../application/store/actions/open_indices.js | 2 +- .../store/actions/refresh_indices.js | 2 +- .../store/actions/reload_indices.js | 2 +- .../store/actions/unfreeze_indices.js | 2 +- .../store/actions/update_index_settings.js | 2 +- .../sync_url_hash_query_param.js.ts | 2 +- .../store/reducers/detail_panel.js | 2 +- .../application/store/reducers/indices.js | 10 +- .../application/store/reducers/row_status.js | 14 +- .../application/store/selectors/index.js | 58 +- .../public/application/store/store.js | 2 +- .../plugins/index_management/public/plugin.ts | 2 +- .../server/lib/fetch_indices.ts | 2 +- .../server/services/license.ts | 2 +- .../infra/common/http_api/source_api.ts | 4 +- .../infra/common/inventory_models/index.ts | 2 +- .../metrics_and_groupby_toolbar_items.tsx | 2 +- .../components/expression.tsx | 10 +- .../components/expression_chart.tsx | 4 +- .../components/expression_row.tsx | 6 +- .../alerting/inventory/expression.tsx | 14 +- .../components/alerting/inventory/metric.tsx | 6 +- .../alerting/inventory/node_type.tsx | 4 +- .../logs/expression_editor/criterion.tsx | 12 +- .../logs/expression_editor/document_count.tsx | 4 +- .../logs/expression_editor/editor.tsx | 12 +- .../infra/public/components/auto_sizer.tsx | 4 +- .../autocomplete_field/autocomplete_field.tsx | 14 +- .../autocomplete_field/suggestion_item.tsx | 22 +- .../public/components/eui/toolbar/toolbar.tsx | 2 +- .../components/loading_overlay_wrapper.tsx | 14 +- .../recreate_job_button.tsx | 2 +- .../analysis_setup_indices_form.tsx | 6 +- .../analysis_setup_timerange_form.tsx | 20 +- .../index_setup_dataset_filter.tsx | 2 +- .../index_setup_row.tsx | 2 +- .../user_management_link.tsx | 2 +- .../logging/log_customization_menu.tsx | 2 +- .../log_entry_actions_menu.tsx | 2 +- .../logging/log_highlights_menu.tsx | 8 +- .../logging/log_minimap/density_chart.tsx | 20 +- .../log_minimap/highlighted_interval.tsx | 6 +- .../logging/log_minimap/log_minimap.tsx | 10 +- .../logging/log_minimap/search_marker.tsx | 12 +- .../logging/log_minimap/search_markers.tsx | 6 +- .../logging/log_minimap/time_ruler.tsx | 10 +- .../log_search_controls/log_search_input.tsx | 6 +- .../components/logging/log_statusbar.tsx | 6 +- .../log_text_stream/column_headers.tsx | 14 +- .../logging/log_text_stream/highlighting.tsx | 12 +- .../logging/log_text_stream/jump_to_tail.tsx | 6 +- .../log_text_stream/loading_item_view.tsx | 6 +- .../log_entry_actions_column.tsx | 2 +- .../log_text_stream/log_entry_column.tsx | 19 +- .../log_entry_field_column.tsx | 2 +- .../log_entry_message_column.tsx | 4 +- .../logging/log_text_stream/log_entry_row.tsx | 8 +- .../log_entry_timestamp_column.tsx | 2 +- .../scrollable_log_text_stream_view.tsx | 8 +- .../logging/log_text_stream/text_styles.tsx | 12 +- .../log_text_stream/vertical_scroll_panel.tsx | 2 +- .../components/navigation/app_navigation.tsx | 6 +- .../components/navigation/routed_tabs.tsx | 2 +- .../plugins/infra/public/components/page.tsx | 2 +- .../components/saved_views/create_modal.tsx | 4 +- .../add_log_column_popover.tsx | 6 +- .../indices_configuration_form_state.ts | 22 +- .../log_columns_configuration_form_state.tsx | 8 +- .../log_columns_configuration_panel.tsx | 6 +- .../source_configuration_settings.tsx | 2 +- .../infra/public/components/toolbar_panel.ts | 2 +- x-pack/plugins/infra/public/compose_libs.ts | 2 +- .../logs/log_analysis/api/ml_cleanup.ts | 4 +- .../api/ml_get_jobs_summary_api.ts | 2 +- .../log_analysis_capabilities.tsx | 2 +- .../log_analysis/log_analysis_cleanup.tsx | 6 +- .../logs/log_analysis/log_analysis_module.tsx | 2 +- .../log_analysis_module_configuration.ts | 2 +- .../log_analysis_module_definition.tsx | 2 +- .../log_analysis_module_status.tsx | 12 +- .../log_analysis/log_analysis_setup_state.ts | 20 +- .../containers/logs/log_entries/index.ts | 8 +- .../logs/log_filter/log_filter_state.ts | 4 +- .../log_filter/with_log_filter_url_state.tsx | 4 +- .../public/containers/logs/log_flyout.tsx | 6 +- .../log_highlights/log_entry_highlights.tsx | 4 +- .../log_highlights/log_summary_highlights.ts | 4 +- .../logs/log_summary/log_summary.tsx | 4 +- .../containers/logs/with_log_textview.tsx | 4 +- .../containers/logs/with_stream_items.ts | 2 +- ...ith_metrics_explorer_options_url_state.tsx | 6 +- .../infra/public/containers/source/source.tsx | 8 +- .../containers/with_kuery_autocompletion.tsx | 2 +- .../hooks/use_bulk_get_saved_object.tsx | 2 +- .../public/hooks/use_find_saved_object.tsx | 2 +- .../infra/public/hooks/use_http_request.tsx | 4 +- .../infra/public/hooks/use_saved_view.ts | 2 +- x-pack/plugins/infra/public/pages/error.tsx | 2 +- .../public/pages/link_to/link_to_logs.tsx | 4 +- .../public/pages/link_to/link_to_metrics.tsx | 4 +- .../pages/link_to/use_host_ip_to_name.test.ts | 2 +- .../log_entry_categories/module_descriptor.ts | 2 +- .../page_results_content.tsx | 2 +- .../anomaly_severity_indicator_list.tsx | 2 +- .../top_categories/category_expression.tsx | 4 +- .../top_categories/datasets_action_list.tsx | 2 +- .../sections/top_categories/datasets_list.tsx | 2 +- .../top_categories/datasets_selector.tsx | 2 +- .../log_entry_count_sparkline.tsx | 4 +- .../top_categories/top_categories_table.tsx | 2 +- .../use_log_entry_categories_module.tsx | 2 +- .../use_log_entry_categories_quality.ts | 4 +- .../use_log_entry_categories_results.ts | 4 +- .../logs/log_entry_rate/module_descriptor.ts | 2 +- .../sections/anomalies/chart.tsx | 2 +- .../sections/anomalies/index.tsx | 4 +- .../sections/helpers/data_formatters.tsx | 4 +- .../sections/log_rate/bar_chart.tsx | 2 +- .../use_log_entry_rate_module.tsx | 2 +- .../logs/settings/add_log_column_popover.tsx | 6 +- .../indices_configuration_form_state.ts | 12 +- .../log_columns_configuration_form_state.tsx | 8 +- .../log_columns_configuration_panel.tsx | 6 +- .../source_configuration_settings.tsx | 2 +- .../public/pages/logs/stream/page_toolbar.tsx | 2 +- .../logs/stream/page_view_log_in_context.tsx | 2 +- .../infra/public/pages/metrics/index.tsx | 2 +- .../inventory_view/components/layout.tsx | 8 +- .../components/nodes_overview.tsx | 6 +- .../inventory_view/components/table_view.tsx | 6 +- .../components/toolbars/toolbar.tsx | 2 +- .../components/waffle/custom_field_panel.tsx | 6 +- .../components/waffle/gradient_legend.tsx | 4 +- .../components/waffle/group_name.tsx | 8 +- .../components/waffle/group_of_groups.tsx | 6 +- .../components/waffle/group_of_nodes.tsx | 4 +- .../components/waffle/legend_controls.tsx | 12 +- .../inventory_view/components/waffle/map.tsx | 2 +- .../metric_control/custom_metric_form.tsx | 10 +- .../waffle/metric_control/index.tsx | 8 +- .../metric_control/metrics_context_menu.tsx | 6 +- .../metric_control/metrics_edit_mode.tsx | 4 +- .../inventory_view/components/waffle/node.tsx | 12 +- .../components/waffle/palette_preview.tsx | 6 +- .../waffle/stepped_gradient_legend.tsx | 6 +- .../waffle/waffle_accounts_controls.tsx | 4 +- .../waffle/waffle_group_by_controls.tsx | 20 +- .../waffle/waffle_region_controls.tsx | 4 +- .../hooks/use_waffle_filters.ts | 2 +- .../hooks/use_waffle_options.ts | 29 +- .../inventory_view/hooks/use_waffle_time.ts | 6 +- .../lib/apply_wafflemap_layout.ts | 4 +- .../inventory_view/lib/color_from_value.ts | 2 +- .../inventory_view/lib/nodes_to_wafflemap.ts | 12 +- .../components/chart_section_vis.tsx | 2 +- .../components/gauges_section_vis.tsx | 4 +- .../components/metadata_details.tsx | 20 +- .../metric_detail/components/section.tsx | 4 +- .../metric_detail/components/sub_section.tsx | 4 +- .../metric_detail/hooks/use_metrics_time.ts | 6 +- .../pages/metrics/metric_detail/index.tsx | 4 +- .../metric_detail/lib/get_filtered_metrics.ts | 8 +- .../components/aggregation.tsx | 4 +- .../components/chart_options.tsx | 2 +- .../metrics_explorer/components/charts.tsx | 2 +- .../metrics_explorer/components/group_by.tsx | 8 +- .../components/helpers/calculate_domain.ts | 4 +- .../metrics_explorer/components/metrics.tsx | 8 +- .../components/series_chart.tsx | 6 +- .../hooks/use_metric_explorer_state.test.tsx | 2 +- .../hooks/use_metric_explorer_state.ts | 4 +- .../hooks/use_metrics_explorer_data.test.tsx | 2 +- .../hooks/use_metrics_explorer_data.ts | 2 +- x-pack/plugins/infra/public/utils/datemath.ts | 6 +- .../infra/public/utils/enzyme_helpers.tsx | 4 +- .../utils/loading_state/loading_result.ts | 2 +- ...picker_quickranges_to_datepicker_ranges.ts | 2 +- .../public/utils/triggers_actions_context.tsx | 2 +- .../infra/public/utils/use_kibana_space_id.ts | 2 +- .../infra/public/utils/use_tracked_promise.ts | 16 +- .../public/utils/use_visibility_state.ts | 2 +- .../infra/server/graphql/sources/resolvers.ts | 4 +- x-pack/plugins/infra/server/kibana.index.ts | 4 +- .../fields/framework_fields_adapter.ts | 2 +- .../log_entries/kibana_log_entries_adapter.ts | 8 +- .../metrics/kibana_metrics_adapter.ts | 14 +- .../elasticsearch_source_status_adapter.ts | 4 +- .../infra/server/lib/alerting/common/utils.ts | 2 +- .../inventory_metric_threshold_executor.ts | 27 +- .../log_threshold/log_threshold_executor.ts | 8 +- .../metric_threshold_executor.ts | 32 +- .../lib/alerting/register_alert_types.ts | 2 +- .../log_entries_domain/log_entries_domain.ts | 4 +- .../lib/domains/log_entries_domain/message.ts | 2 +- .../log_entry_categories_analysis.ts | 16 +- .../log_analysis/log_entry_rate_analysis.ts | 2 +- .../create_timerange_with_interval.ts | 8 +- .../server/lib/snapshot/query_helpers.ts | 2 +- .../server/lib/snapshot/response_helpers.ts | 6 +- .../infra/server/lib/snapshot/snapshot.ts | 4 +- .../infra/server/lib/sources/sources.ts | 14 +- x-pack/plugins/infra/server/plugin.ts | 4 +- .../lib/get_cloud_metadata.ts | 6 +- .../results/log_entry_categories.ts | 2 +- .../log_analysis/validation/datasets.ts | 2 +- .../routes/log_analysis/validation/indices.ts | 6 +- .../server/routes/log_entries/highlights.ts | 6 +- .../routes/log_entries/summary_highlights.ts | 2 +- .../metadata/lib/get_cloud_metric_metadata.ts | 2 +- .../routes/metadata/lib/get_node_info.ts | 4 +- .../routes/metadata/lib/pick_feature_name.ts | 2 +- .../metrics_explorer/lib/get_groupings.ts | 10 +- .../lib/populate_series_with_tsvb_data.ts | 14 +- .../infra/server/usage/usage_collector.ts | 2 +- .../server/utils/calculate_metric_interval.ts | 2 +- .../common/services/agent_status.ts | 26 +- .../datasource_to_agent_datasource.ts | 8 +- .../common/services/package_to_config.ts | 6 +- .../components/alpha_messaging.tsx | 4 +- .../enrollment_instructions/manual/index.tsx | 2 +- .../ingest_manager/components/header.tsx | 14 +- .../components/package_icon.tsx | 5 +- .../ingest_manager/components/search_bar.tsx | 4 +- .../components/settings_flyout.tsx | 4 +- .../ingest_manager/hooks/use_breadcrumbs.tsx | 4 +- .../ingest_manager/hooks/use_fleet_status.tsx | 6 +- .../ingest_manager/hooks/use_input.ts | 2 +- .../hooks/use_package_icon_type.ts | 10 +- .../ingest_manager/layouts/default.tsx | 10 +- .../ingest_manager/layouts/with_header.tsx | 2 +- .../ingest_manager/layouts/without_header.tsx | 2 +- .../agent_config/components/config_form.tsx | 12 +- .../danger_eui_context_menu_item.tsx | 2 +- .../components/datasource_delete_provider.tsx | 6 +- .../components/datasource_input_config.tsx | 6 +- .../components/datasource_input_panel.tsx | 18 +- .../datasource_input_stream_config.tsx | 8 +- .../components/datasource_input_var_field.tsx | 6 +- .../services/validate_datasource.test.ts | 6 +- .../services/validate_datasource.ts | 6 +- .../step_configure_datasource.tsx | 8 +- .../step_define_datasource.tsx | 8 +- .../step_select_config.tsx | 6 +- .../step_select_package.tsx | 4 +- .../datasources/datasources_table.tsx | 6 +- .../components/settings/index.tsx | 2 +- .../agent_config/details_page/index.tsx | 2 +- .../edit_datasource_page/index.tsx | 4 +- .../list_page/components/create_config.tsx | 2 +- .../sections/agent_config/list_page/index.tsx | 4 +- .../components/data_stream_row_actions.tsx | 2 +- .../sections/data_stream/list_page/index.tsx | 10 +- .../epm/components/assets_facet_group.tsx | 6 +- .../sections/epm/components/icon_panel.tsx | 6 +- .../sections/epm/components/icons.tsx | 2 +- .../epm/components/nav_button_back.tsx | 2 +- .../epm/components/package_list_grid.tsx | 6 +- .../sections/epm/components/requirements.tsx | 4 +- .../sections/epm/components/version.tsx | 2 +- .../sections/epm/hooks/use_local_search.tsx | 2 +- .../epm/hooks/use_package_install.tsx | 8 +- .../epm/screens/detail/content_collapse.tsx | 10 +- .../sections/epm/screens/detail/header.tsx | 2 +- .../sections/epm/screens/detail/index.tsx | 10 +- .../sections/epm/screens/detail/readme.tsx | 2 +- .../epm/screens/detail/screenshots.tsx | 6 +- .../epm/screens/detail/settings_panel.tsx | 6 +- .../epm/screens/detail/side_nav_links.tsx | 2 +- .../epm/screens/home/category_facets.tsx | 2 +- .../sections/epm/screens/home/header.tsx | 2 +- .../sections/epm/screens/home/index.tsx | 4 +- .../epm/screens/home/search_packages.tsx | 4 +- .../components/actions_menu.tsx | 2 +- .../agent_details_page/components/helper.ts | 2 +- .../components/metadata_flyout.tsx | 2 +- .../fleet/agent_details_page/index.tsx | 6 +- .../sections/fleet/agent_list_page/index.tsx | 16 +- .../config_selection.tsx | 10 +- .../agent_reassign_config_flyout/index.tsx | 4 +- .../sections/fleet/components/list_layout.tsx | 2 +- .../components/new_enrollment_key_flyout.tsx | 4 +- .../enrollment_token_list_page/index.tsx | 4 +- .../components/datastream_section.tsx | 2 +- .../components/integration_section.tsx | 7 +- .../overview/components/overview_panel.tsx | 14 +- .../overview/components/overview_stats.tsx | 4 +- .../sections/overview/index.tsx | 2 +- .../server/routes/agent/acks_handlers.ts | 4 +- .../server/routes/agent/actions_handlers.ts | 2 +- .../server/routes/agent/handlers.ts | 4 +- .../server/routes/data_streams/handlers.ts | 8 +- .../server/saved_objects/index.ts | 2 +- .../migrations/agent_config_v790.ts | 7 +- .../migrations/datasources_v790.ts | 7 +- .../server/services/agent_config.ts | 8 +- .../server/services/agents/acks.ts | 8 +- .../server/services/agents/actions.ts | 6 +- .../server/services/agents/checkin.ts | 8 +- .../server/services/agents/crud.ts | 5 +- .../server/services/agents/events.ts | 2 +- .../server/services/agents/status.ts | 2 +- .../server/services/agents/update.ts | 2 +- .../server/services/api_keys/index.ts | 4 +- .../server/services/datasource.ts | 14 +- .../services/epm/elasticsearch/ilm/install.ts | 2 +- .../elasticsearch/ingest_pipeline/install.ts | 10 +- .../epm/elasticsearch/template/install.ts | 4 +- .../epm/elasticsearch/template/template.ts | 8 +- .../server/services/epm/fields/field.ts | 6 +- .../epm/kibana/index_pattern/install.test.ts | 8 +- .../epm/kibana/index_pattern/install.ts | 14 +- .../server/services/epm/packages/assets.ts | 2 +- .../server/services/epm/packages/get.ts | 12 +- .../server/services/epm/packages/install.ts | 6 +- .../server/services/epm/packages/remove.ts | 2 +- .../server/services/epm/registry/extract.ts | 2 +- .../server/services/epm/registry/streams.ts | 2 +- .../install_script/install_templates/linux.ts | 2 +- .../install_script/install_templates/macos.ts | 2 +- .../ingest_manager/server/services/output.ts | 2 +- .../ingest_manager/server/services/setup.ts | 2 +- .../helpers/pipelines_list.helpers.ts | 5 +- .../public/application/app.tsx | 2 +- .../pipeline_form/pipeline_form.tsx | 6 +- .../pipeline_form/pipeline_form_fields.tsx | 4 +- .../pipeline_form/pipeline_form_provider.tsx | 4 +- .../pipeline_test_flyout.tsx | 2 +- .../tabs/pipeline_test_tabs.tsx | 2 +- .../pipeline_test_flyout/tabs/tab_output.tsx | 2 +- .../components/pipeline_form/schema.tsx | 4 +- .../pipelines_clone/pipelines_clone.tsx | 2 +- .../sections/pipelines_list/delete_modal.tsx | 2 +- .../pipelines_list/details_flyout.tsx | 2 +- .../sections/pipelines_list/main.tsx | 4 +- .../sections/pipelines_list/table.tsx | 6 +- .../public/application/services/api.ts | 2 +- .../plugins/ingest_pipelines/public/plugin.ts | 2 +- .../server/routes/api/delete.ts | 4 +- .../server/services/license.ts | 2 +- .../lens/public/app_plugin/app.test.tsx | 8 +- x-pack/plugins/lens/public/app_plugin/app.tsx | 52 +- .../expression.test.tsx | 20 +- .../datatable_visualization/expression.tsx | 18 +- .../datatable_visualization/visualization.tsx | 22 +- .../debounced_component.test.tsx | 2 +- .../config_panel/chart_switch.test.tsx | 20 +- .../config_panel/chart_switch.tsx | 14 +- .../config_panel/config_panel.tsx | 8 +- .../config_panel/dimension_popover.tsx | 2 +- .../config_panel/layer_actions.ts | 2 +- .../editor_frame/config_panel/layer_panel.tsx | 12 +- .../editor_frame/data_panel_wrapper.tsx | 4 +- .../editor_frame/editor_frame.test.tsx | 43 +- .../editor_frame/editor_frame.tsx | 10 +- .../editor_frame/expression_helpers.ts | 2 +- .../editor_frame/save.test.ts | 8 +- .../editor_frame/suggestion_helpers.ts | 4 +- .../editor_frame/suggestion_panel.test.tsx | 31 +- .../editor_frame/suggestion_panel.tsx | 6 +- .../editor_frame/workspace_panel.test.tsx | 6 +- .../editor_frame/workspace_panel.tsx | 10 +- .../embeddable/embeddable.test.tsx | 2 +- .../embeddable/embeddable.tsx | 4 +- .../embeddable/expression_wrapper.tsx | 2 +- .../editor_frame_service/format_column.ts | 2 +- .../editor_frame_service/merge_tables.test.ts | 20 +- .../public/editor_frame_service/mocks.tsx | 22 +- .../public/editor_frame_service/service.tsx | 6 +- .../change_indexpattern.tsx | 4 +- .../datapanel.test.tsx | 75 +- .../indexpattern_datasource/datapanel.tsx | 36 +- .../dimension_panel/bucket_nesting_editor.tsx | 4 +- .../dimension_panel/dimension_panel.test.tsx | 11 +- .../dimension_panel/dimension_panel.tsx | 4 +- .../dimension_panel/field_select.tsx | 8 +- .../dimension_panel/format_selector.tsx | 4 +- .../dimension_panel/popover_editor.tsx | 12 +- .../field_item.test.tsx | 2 +- .../indexpattern_datasource/field_item.tsx | 14 +- .../indexpattern_datasource/indexpattern.tsx | 10 +- .../indexpattern_suggestions.test.tsx | 10 +- .../indexpattern_suggestions.ts | 38 +- .../layerpanel.test.tsx | 15 +- .../indexpattern_datasource/loader.test.ts | 14 +- .../public/indexpattern_datasource/loader.ts | 22 +- .../operations/definitions/cardinality.tsx | 2 +- .../definitions/date_histogram.test.tsx | 4 +- .../operations/definitions/date_histogram.tsx | 10 +- .../operations/definitions/metrics.tsx | 10 +- .../operations/definitions/terms.test.tsx | 2 +- .../operations/definitions/terms.tsx | 2 +- .../operations/operations.ts | 6 +- .../indexpattern_datasource/rename_columns.ts | 4 +- .../indexpattern_datasource/state_helpers.ts | 8 +- .../indexpattern_datasource/to_expression.ts | 4 +- .../lens/public/lens_ui_telemetry/factory.ts | 4 +- .../metric_visualization/auto_scale.tsx | 4 +- .../metric_expression.test.tsx | 4 +- .../metric_suggestions.test.ts | 2 +- .../metric_visualization.tsx | 2 +- .../native_renderer/native_renderer.tsx | 2 +- .../pie_visualization/pie_visualization.tsx | 18 +- .../render_function.test.tsx | 9 +- .../pie_visualization/render_function.tsx | 20 +- .../pie_visualization/render_helpers.ts | 6 +- .../pie_visualization/settings_widget.tsx | 8 +- .../public/pie_visualization/suggestions.ts | 12 +- .../public/pie_visualization/to_expression.ts | 4 +- .../public/xy_visualization/state_helpers.ts | 4 +- .../xy_visualization/to_expression.test.ts | 2 +- .../public/xy_visualization/to_expression.ts | 10 +- .../xy_visualization/xy_config_panel.tsx | 8 +- .../xy_visualization/xy_expression.test.tsx | 19 +- .../public/xy_visualization/xy_expression.tsx | 38 +- .../xy_visualization/xy_suggestions.test.ts | 6 +- .../public/xy_visualization/xy_suggestions.ts | 24 +- .../xy_visualization/xy_visualization.test.ts | 10 +- .../xy_visualization/xy_visualization.tsx | 36 +- x-pack/plugins/lens/server/migrations.ts | 16 +- .../server/routes/existing_fields.test.ts | 6 +- .../lens/server/routes/existing_fields.ts | 16 +- .../plugins/lens/server/routes/field_stats.ts | 8 +- .../plugins/lens/server/usage/collectors.ts | 14 +- x-pack/plugins/lens/server/usage/task.ts | 13 +- .../__mocks__/focus-trap-react.js | 2 +- .../public/application/app.container.js | 2 +- .../public/application/app.js | 2 +- .../license_status.container.js | 2 +- .../request_trial_extension.container.js | 2 +- .../revert_to_basic.container.js | 2 +- .../revert_to_basic/revert_to_basic.js | 2 +- .../start_trial/start_trial.container.js | 2 +- .../start_trial/start_trial.tsx | 2 +- .../upload_license.container.js | 2 +- .../sections/upload_license/upload_license.js | 8 +- .../application/store/actions/start_basic.js | 2 +- .../store/reducers/license_management.js | 42 +- .../licensing/common/license_update.test.ts | 10 +- .../licensing/public/expired_banner.tsx | 2 +- .../plugins/licensing/public/plugin.test.ts | 6 +- x-pack/plugins/licensing/public/plugin.ts | 4 +- .../server/on_pre_response_handler.test.ts | 2 +- .../plugins/licensing/server/plugin.test.ts | 2 +- x-pack/plugins/licensing/server/plugin.ts | 2 +- .../server/services/feature_usage_service.ts | 2 +- x-pack/plugins/lists/server/create_config.ts | 14 +- x-pack/plugins/lists/server/plugin.ts | 4 +- .../delete_exception_list_items_by_list.ts | 7 +- .../server/services/exception_lists/utils.ts | 4 +- .../services/items/buffer_lines.test.ts | 12 +- .../server/services/items/buffer_lines.ts | 2 +- .../items/delete_list_item_by_value.ts | 2 +- .../items/write_lines_to_bulk_list_items.ts | 4 +- .../items/write_list_items_to_stream.test.ts | 16 +- .../items/write_list_items_to_stream.ts | 2 +- .../utils/transform_elastic_to_list_item.ts | 2 +- .../pipeline_editor/pipeline_editor.js | 24 +- .../confirm_delete_modal.test.js | 10 +- .../components/pipeline_list/pipeline_list.js | 12 +- .../pipeline_list/pipeline_list.test.js | 4 +- .../pipeline_list/pipelines_table.js | 6 +- .../public/application/pipeline_edit_view.tsx | 2 +- .../public/models/pipeline/pipeline.js | 2 +- x-pack/plugins/logstash/public/plugin.ts | 4 +- .../services/cluster/cluster_service.js | 4 +- .../services/monitoring/monitoring_service.js | 6 +- .../services/pipeline/pipeline_service.js | 6 +- .../services/pipelines/pipelines_service.js | 22 +- .../services/upgrade/upgrade_service.js | 4 +- .../lib/check_license/check_license.test.ts | 2 +- .../server/lib/check_license/check_license.ts | 2 +- .../server/routes/pipelines/delete.ts | 10 +- .../logstash/server/routes/pipelines/list.ts | 2 +- .../migrations/add_field_meta_options.js | 4 +- .../ems_raster_tile_to_ems_vector_tile.js | 2 +- .../maps/common/migrations/join_agg_key.ts | 2 +- .../migrate_symbol_style_descriptor.js | 2 +- .../migrations/move_apply_global_query.js | 4 +- .../maps/common/migrations/references.js | 6 +- .../migrations/top_hits_time_to_sort.js | 2 +- .../public/actions/data_request_actions.ts | 4 +- .../maps/public/actions/map_actions.js | 28 +- .../maps/public/actions/tooltip_actions.ts | 8 +- .../services/gis_map_saved_object_loader.js | 2 +- .../public/angular/services/saved_gis_map.js | 4 +- .../public/classes/fields/ems_file_field.ts | 2 +- .../classes/fields/kibana_region_field.ts | 2 +- .../maps/public/classes/joins/inner_join.js | 2 +- .../blended_vector_layer.ts | 2 +- .../maps/public/classes/layers/layer.tsx | 14 +- .../classes/layers/layer_wizard_registry.ts | 2 +- .../create_layer_descriptor.test.ts | 2 +- .../observability_layer_template.tsx | 2 +- .../layers/vector_layer/vector_layer.js | 48 +- .../vector_tile_layer/vector_tile_layer.js | 14 +- .../ems_file_source/create_source_editor.tsx | 2 +- .../ems_file_source/ems_file_source.tsx | 12 +- .../ems_file_source/update_source_editor.tsx | 4 +- .../sources/ems_tms_source/ems_tms_source.js | 2 +- .../ems_tms_source/tile_service_select.js | 4 +- .../sources/es_agg_source/es_agg_source.js | 10 +- .../es_geo_grid_source/convert_to_geojson.js | 8 +- .../create_source_editor.js | 10 +- .../es_geo_grid_source/es_geo_grid_source.js | 4 +- .../es_geo_grid_source/render_as_select.tsx | 2 +- .../es_geo_grid_source/resolution_editor.js | 2 +- .../update_source_editor.js | 10 +- .../es_pew_pew_source/create_source_editor.js | 10 +- .../es_pew_pew_source/update_source_editor.js | 4 +- .../es_search_source/create_source_editor.js | 12 +- .../es_search_source/es_search_source.js | 24 +- .../es_search_source/update_source_editor.js | 10 +- .../classes/sources/es_source/es_source.js | 2 +- .../sources/es_term_source/es_term_source.js | 4 +- .../kibana_regionmap_source.js | 4 +- .../classes/sources/tms_source/tms_source.js | 2 +- .../sources/vector_source/vector_source.js | 2 +- .../wms_source/wms_create_source_editor.js | 14 +- .../sources/xyz_tms_source/xyz_tms_editor.tsx | 2 +- .../maps/public/classes/styles/color_utils.js | 16 +- .../components/heatmap_style_editor.js | 2 +- .../components/color/color_map_select.js | 6 +- .../vector/components/color/color_stops.js | 4 +- .../components/color/color_stops_ordinal.js | 2 +- .../components/color/color_stops_utils.js | 2 +- .../components/color/dynamic_color_form.js | 4 +- .../components/color/static_color_form.js | 2 +- .../styles/vector/components/field_select.js | 8 +- .../components/label/static_label_form.js | 2 +- .../components/legend/vector_style_legend.js | 2 +- .../orientation/static_orientation_form.js | 2 +- .../components/size/static_size_form.js | 2 +- .../styles/vector/components/stop_input.js | 12 +- .../vector/components/style_map_select.js | 6 +- .../vector/components/style_prop_editor.js | 2 +- .../components/symbol/dynamic_icon_form.js | 2 +- .../vector/components/symbol/icon_select.js | 8 +- .../vector/components/symbol/icon_stops.js | 6 +- .../components/symbol/static_icon_form.js | 2 +- .../vector_style_symbolize_as_editor.js | 2 +- .../vector/components/vector_style_editor.js | 12 +- .../properties/dynamic_color_property.test.js | 10 +- .../properties/dynamic_icon_property.test.tsx | 2 +- .../properties/dynamic_style_property.js | 6 +- .../classes/styles/vector/symbol_utils.js | 10 +- .../classes/styles/vector/vector_style.js | 30 +- .../util/get_feature_collection_bounds.ts | 2 +- .../public/components/geometry_filter_form.js | 10 +- .../components/global_filter_checkbox.js | 2 +- .../maps/public/components/map_listing.js | 8 +- .../maps/public/components/metric_editor.js | 10 +- .../maps/public/components/metric_select.js | 2 +- .../maps/public/components/metrics_editor.js | 2 +- .../multi_index_geo_field_select.tsx | 2 +- .../public/components/single_field_select.js | 4 +- .../add_tooltip_field_popover.tsx | 10 +- .../tooltip_selector.test.tsx | 2 +- .../tooltip_selector/tooltip_selector.tsx | 2 +- .../maps/public/components/validated_range.js | 2 +- .../connected_components/gis_map/view.js | 6 +- .../filter_editor/filter_editor.js | 6 +- .../layer_panel/flyout_footer/index.js | 2 +- .../connected_components/layer_panel/index.js | 2 +- .../layer_panel/join_editor/resources/join.js | 12 +- .../join_editor/resources/join_expression.js | 10 +- .../resources/metrics_expression.js | 2 +- .../join_editor/resources/where_expression.js | 2 +- .../layer_panel/join_editor/view.js | 2 +- .../layer_settings/layer_settings.js | 4 +- .../layer_panel/style_settings/index.js | 2 +- .../connected_components/layer_panel/view.js | 2 +- .../layer_panel/view.test.js | 4 +- .../features_tooltip/feature_properties.js | 4 +- .../feature_properties.test.js | 6 +- .../map/features_tooltip/features_tooltip.js | 2 +- .../map/features_tooltip/tooltip_header.js | 8 +- .../features_tooltip/tooltip_header.test.js | 14 +- .../map/mb/draw_control/draw_control.js | 2 +- .../map/mb/get_initial_view.ts | 2 +- .../connected_components/map/mb/index.js | 4 +- .../map/mb/mb.utils.test.js | 14 +- .../map/mb/tooltip_control/tooltip_control.js | 8 +- .../tooltip_control/tooltip_control.test.js | 2 +- .../map/mb/tooltip_control/tooltip_popover.js | 6 +- .../tooltip_control/tooltip_popover.test.js | 6 +- .../connected_components/map/mb/utils.js | 36 +- .../connected_components/map/mb/view.js | 8 +- .../set_view_control/set_view_control.js | 6 +- .../toolbar_overlay/tools_control/index.js | 2 +- .../tools_control/tools_control.js | 8 +- .../attribution_control/view.js | 4 +- .../attribution_control/view.test.js | 2 +- .../layer_control/layer_toc/index.js | 2 +- .../layer_toc/toc_entry/index.js | 6 +- .../toc_entry_actions_popover.test.tsx | 6 +- .../toc_entry_actions_popover.tsx | 2 +- .../layer_toc/toc_entry/view.test.js | 10 +- .../layer_control/layer_toc/view.js | 4 +- .../widget_overlay/layer_control/view.js | 4 +- .../maps/public/elasticsearch_geo_utils.js | 4 +- .../public/elasticsearch_geo_utils.test.js | 4 +- .../maps/public/embeddable/map_embeddable.tsx | 4 +- .../embeddable/map_embeddable_factory.ts | 4 +- .../plugins/maps/public/index_pattern_util.js | 6 +- .../public/inspector/views/map_details.js | 2 +- x-pack/plugins/maps/public/kibana_services.js | 53 +- x-pack/plugins/maps/public/reducers/map.js | 18 +- .../reducers/non_serializable_instances.js | 4 +- x-pack/plugins/maps/public/reducers/ui.ts | 2 +- .../maps/public/selectors/map_selectors.ts | 32 +- .../server/lib/get_index_pattern_settings.js | 2 +- .../server/maps_telemetry/maps_telemetry.ts | 20 +- x-pack/plugins/maps/server/routes.js | 26 +- .../maps/server/saved_objects/migrations.js | 12 +- .../plugins/ml/common/license/ml_license.ts | 4 +- .../plugins/ml/common/types/capabilities.ts | 4 +- x-pack/plugins/ml/common/types/common.ts | 2 +- x-pack/plugins/ml/common/util/job_utils.ts | 36 +- .../plugins/ml/common/util/parse_interval.ts | 4 +- x-pack/plugins/ml/common/util/string_utils.ts | 4 +- .../ml/common/util/validation_utils.ts | 2 +- x-pack/plugins/ml/common/util/validators.ts | 6 +- x-pack/plugins/ml/public/application/app.tsx | 2 +- .../capabilities/check_capabilities.ts | 2 +- .../annotations/annotation_flyout/index.tsx | 4 +- .../annotations_table/annotations_table.js | 16 +- .../anomalies_table/anomalies_table.js | 10 +- .../anomalies_table_columns.js | 24 +- .../anomalies_table/anomaly_details.js | 4 +- .../anomalies_table/influencers_cell.js | 2 +- .../components/anomalies_table/links_menu.js | 16 +- .../chart_tooltip/chart_tooltip.tsx | 2 +- .../color_range_legend/color_range_legend.tsx | 13 +- .../select_interval/select_interval.test.tsx | 2 +- .../select_interval/select_interval.tsx | 2 +- .../select_severity/select_severity.test.tsx | 2 +- .../select_severity/select_severity.tsx | 2 +- .../components/data_grid/common.ts | 6 +- .../components/data_grid/data_grid.tsx | 4 +- .../components/data_grid/use_data_grid.ts | 12 +- .../data_recognizer/data_recognizer.js | 6 +- .../influencers_list/influencers_list.js | 4 +- .../components/items_grid/items_grid.js | 2 +- .../items_grid/items_grid_pagination.js | 6 +- .../custom_selection_table.js | 18 +- .../job_selector/id_badges/id_badges.js | 2 +- .../job_selector/job_select_service_utils.ts | 23 +- .../components/job_selector/job_selector.tsx | 6 +- .../job_selector/job_selector_flyout.tsx | 4 +- .../job_selector_table/job_selector_table.js | 18 +- .../job_selector/use_job_selection.ts | 4 +- .../navigation_menu/top_nav/top_nav.tsx | 2 +- .../rule_editor/condition_expression.js | 6 +- .../rule_editor/rule_editor_flyout.js | 50 +- .../rule_editor/rule_editor_flyout.test.js | 2 +- .../rule_editor/scope_expression.js | 10 +- .../rule_editor/scope_section.test.js | 2 +- .../select_rule_action/edit_condition_link.js | 2 +- .../select_rule_action/rule_action_panel.js | 4 +- .../components/rule_editor/utils.js | 14 +- .../components/stats_bar/stats_bar.tsx | 2 +- .../validate_job/validate_job_view.js | 10 +- .../data_frame_analytics/common/analytics.ts | 6 +- .../data_frame_analytics/common/fields.ts | 6 +- .../common/get_index_data.ts | 4 +- .../common/get_index_fields.ts | 4 +- .../common/use_results_view_config.ts | 2 +- .../column_data.tsx | 2 +- .../use_exploration_results.ts | 2 +- .../components/outlier_exploration/common.ts | 2 +- .../outlier_exploration/use_outlier_data.ts | 2 +- .../analytics_list/action_delete.test.tsx | 2 +- .../analytics_list/analytics_list.tsx | 26 +- .../analytics_list/expanded_row.tsx | 2 +- .../expanded_row_details_pane.tsx | 8 +- .../create_analytics_advanced_editor.tsx | 4 +- .../create_analytics_button.tsx | 2 +- .../create_analytics_flyout_wrapper.tsx | 2 +- .../create_analytics_form.tsx | 20 +- .../create_analytics_form/job_description.tsx | 2 +- .../create_analytics_form/job_type.tsx | 4 +- .../use_create_analytics_form/reducer.ts | 10 +- .../hooks/use_create_analytics_form/state.ts | 2 +- .../use_create_analytics_form.ts | 2 +- .../analytics_service/get_analytics.ts | 2 +- .../components/about_panel/about_panel.tsx | 2 +- .../components/edit_flyout/edit_flyout.js | 4 +- .../components/edit_flyout/options/options.js | 2 +- .../components/edit_flyout/overrides.js | 18 +- .../components/edit_flyout/overrides.test.js | 2 +- .../components/fields_stats/fields_stats.js | 4 +- .../file_contents/file_contents.tsx | 5 +- .../file_datavisualizer_view.js | 12 +- .../filebeat_config_flyout.tsx | 4 +- .../components/import_view/import_view.js | 24 +- .../file_based/components/utils/utils.ts | 2 +- .../content_types/number_content.tsx | 2 +- .../metric_distribution_chart.tsx | 6 +- ...metric_distribution_chart_data_builder.tsx | 6 +- .../field_types_select/field_types_select.tsx | 4 +- .../components/search_panel/search_panel.tsx | 4 +- .../index_based/data_loader/data_loader.ts | 2 +- .../datavisualizer/index_based/page.tsx | 44 +- .../explorer/actions/job_selection.ts | 8 +- .../explorer/actions/load_explorer_data.ts | 4 +- .../explorer_query_bar/explorer_query_bar.tsx | 2 +- .../public/application/explorer/explorer.js | 14 +- .../explorer_chart_label.js | 2 +- .../explorer_chart_config_builder.js | 2 +- .../explorer_chart_distribution.js | 58 +- .../explorer_chart_distribution.test.js | 22 +- .../explorer_chart_info_tooltip.js | 2 +- .../explorer_chart_single_metric.js | 55 +- .../explorer_chart_single_metric.test.js | 22 +- .../explorer_charts_container.js | 12 +- .../explorer_charts_container_service.js | 52 +- .../explorer_charts_container_service.test.js | 14 +- .../explorer/explorer_swimlane.tsx | 47 +- .../application/explorer/explorer_utils.js | 80 +- .../explorer/has_matching_points.ts | 4 +- .../explorer_reducer/get_index_pattern.ts | 2 +- .../set_influencer_filter_settings.ts | 2 +- .../explorer/select_limit/select_limit.tsx | 2 +- .../application/formatters/format_value.ts | 12 +- .../formatters/number_as_ordinal.test.ts | 2 +- .../components/custom_url_editor/editor.tsx | 12 +- .../components/custom_url_editor/list.tsx | 10 +- .../components/custom_url_editor/utils.js | 16 +- .../create_watch_flyout.js | 10 +- .../create_watch_service.js | 4 +- .../create_watch_flyout/create_watch_view.js | 10 +- .../create_watch_flyout/select_severity.tsx | 2 +- .../delete_job_modal/delete_job_modal.js | 4 +- .../edit_job_flyout/edit_job_flyout.js | 20 +- .../components/edit_job_flyout/edit_utils.js | 22 +- .../edit_job_flyout/tabs/custom_urls.tsx | 20 +- .../edit_job_flyout/tabs/datafeed.js | 8 +- .../edit_job_flyout/tabs/detectors.js | 4 +- .../edit_job_flyout/tabs/job_details.js | 18 +- .../components/job_actions/management.js | 32 +- .../job_details/datafeed_preview_tab.js | 8 +- .../job_details/extract_job_details.js | 14 +- .../forecasts_table/forecasts_table.js | 20 +- .../components/job_details/format_values.js | 4 +- .../job_details/job_details_pane.js | 4 +- .../job_filter_bar/job_filter_bar.js | 6 +- .../components/jobs_list/job_description.js | 2 +- .../components/jobs_list/jobs_list.js | 18 +- .../jobs_list_view/jobs_list_view.js | 38 +- .../jobs_stats_bar/jobs_stats_bar.js | 2 +- .../multi_job_actions/actions_menu.js | 4 +- .../group_selector/group_list/group_list.js | 6 +- .../group_selector/group_selector.js | 28 +- .../new_group_input/new_group_input.js | 4 +- .../start_datafeed_modal.js | 12 +- .../time_range_selector.js | 8 +- .../jobs/jobs_list/components/utils.js | 52 +- .../application/jobs/jobs_list/jobs.tsx | 2 +- .../common/components/job_groups_input.tsx | 8 +- .../job_creator/advanced_job_creator.ts | 2 +- .../new_job/common/job_creator/job_creator.ts | 4 +- .../job_creator/multi_metric_job_creator.ts | 2 +- .../job_creator/population_job_creator.ts | 2 +- .../common/job_creator/util/general.ts | 20 +- .../util/model_memory_estimator.ts | 8 +- .../new_job/common/job_runner/job_runner.ts | 4 +- .../common/job_validator/job_validator.ts | 8 +- .../jobs/new_job/common/job_validator/util.ts | 8 +- .../common/job_validator/validators.ts | 6 +- .../common/results_loader/results_loader.ts | 2 +- .../components/charts/common/anomalies.tsx | 2 +- .../model_memory_limit_input.tsx | 2 +- .../components/frequency/frequency_input.tsx | 2 +- .../query_delay/query_delay_input.tsx | 2 +- .../scroll_size/scroll_size_input.tsx | 2 +- .../calendars/calendars_selection.tsx | 10 +- .../model_plot/model_plot_switch.tsx | 2 +- .../components/groups/groups_input.tsx | 6 +- .../job_description/job_description_input.tsx | 2 +- .../components/job_id/job_id_input.tsx | 2 +- .../advanced_detector_modal.tsx | 12 +- .../components/agg_select/agg_select.tsx | 8 +- .../bucket_span/bucket_span_input.tsx | 2 +- .../bucket_span_estimator.tsx | 2 +- .../estimate_bucket_span.ts | 6 +- .../examples_valid_callout.tsx | 2 +- .../categorization_view/top_categories.tsx | 2 +- .../components/influencers/influencers.tsx | 2 +- .../influencers/influencers_select.tsx | 4 +- .../multi_metric_view/metric_selection.tsx | 4 +- .../population_view/metric_selection.tsx | 4 +- .../metric_selection_summary.tsx | 2 +- .../sparse_data/sparse_data_switch.tsx | 2 +- .../components/split_cards/split_cards.tsx | 4 +- .../components/split_field/by_field.tsx | 2 +- .../split_field/split_field_select.tsx | 2 +- .../jobs/new_job/pages/new_job/wizard.tsx | 4 +- .../new_job/recognize/components/edit_job.tsx | 6 +- .../new_job/recognize/components/job_item.tsx | 2 +- .../components/job_settings_form.tsx | 2 +- .../jobs/new_job/recognize/page.tsx | 6 +- .../jobs/new_job/recognize/resolvers.ts | 4 +- .../ml/public/application/management/index.ts | 2 +- .../anomaly_detection_panel.tsx | 6 +- .../anomaly_detection_panel/utils.ts | 2 +- .../ml/public/application/routing/router.tsx | 2 +- .../routing/routes/timeseriesexplorer.tsx | 4 +- .../public/application/routing/use_refresh.ts | 2 +- .../application/routing/use_resolver.ts | 2 +- .../services/anomaly_detector_service.ts | 4 +- .../application/services/explorer_service.ts | 4 +- .../services/field_format_service.ts | 14 +- .../application/services/forecast_service.js | 24 +- .../application/services/http_service.ts | 12 +- .../application/services/job_service.js | 101 +- .../application/services/mapping_service.js | 8 +- .../services/ml_server_info.test.ts | 6 +- .../new_job_capabilities._service.test.ts | 14 +- .../services/new_job_capabilities_service.ts | 24 +- .../results_service/result_service_rx.ts | 12 +- .../results_service/results_service.js | 78 +- .../edit/events_table/events_table.js | 6 +- .../edit/import_modal/import_modal.js | 16 +- .../calendars/edit/import_modal/utils.js | 4 +- .../settings/calendars/edit/new_calendar.js | 46 +- .../calendars/edit/new_calendar.test.js | 4 +- .../edit/new_event_modal/new_event_modal.js | 14 +- .../new_event_modal/new_event_modal.test.js | 10 +- .../settings/calendars/edit/utils.js | 20 +- .../settings/calendars/list/calendars_list.js | 4 +- .../calendars/list/calendars_list.test.js | 4 +- .../settings/calendars/list/header.test.js | 2 +- .../settings/calendars/list/table/table.js | 10 +- .../add_item_popover/add_item_popover.js | 4 +- .../delete_filter_list_modal.test.js | 2 +- .../edit_description_popover.js | 2 +- .../filter_list_usage_popover.js | 2 +- .../filter_lists/edit/edit_filter_list.js | 40 +- .../edit/edit_filter_list.test.js | 2 +- .../settings/filter_lists/edit/header.js | 2 +- .../settings/filter_lists/edit/utils.js | 26 +- .../filter_lists/list/filter_lists.js | 14 +- .../filter_lists/list/filter_lists.test.js | 2 +- .../settings/filter_lists/list/table.js | 10 +- .../context_chart_mask/context_chart_mask.js | 28 +- .../entity_control/entity_control.tsx | 2 +- .../forecasting_modal/forecasting_modal.js | 36 +- .../forecasting_modal/forecasts_list.js | 8 +- .../timeseries_chart/timeseries_chart.js | 201 +-- .../timeseries_chart/timeseries_chart.test.js | 2 +- .../timeseries_chart_annotations.ts | 27 +- .../timeseries_search_service.ts | 6 +- .../timeseriesexplorer/timeseriesexplorer.js | 60 +- .../timeseriesexplorer_utils.js | 8 +- .../application/util/calc_auto_interval.js | 4 +- .../ml/public/application/util/chart_utils.js | 37 +- .../application/util/chart_utils.test.js | 9 +- .../application/util/custom_url_utils.ts | 4 +- .../application/util/dependency_cache.ts | 2 +- .../util/field_types_utils.test.ts | 2 +- .../application/util/field_types_utils.ts | 2 +- .../ml/public/application/util/index_utils.ts | 10 +- .../public/application/util/string_utils.js | 6 +- .../application/util/string_utils.test.ts | 2 +- .../public/application/util/time_buckets.js | 28 +- .../ml/public/application/util/url_state.ts | 6 +- .../anomaly_swimlane_embeddable.tsx | 2 +- .../anomaly_swimlane_initializer.tsx | 12 +- .../explorer_swimlane_container.tsx | 6 +- .../swimlane_input_resolver.ts | 14 +- .../ml/server/client/elasticsearch_ml.test.ts | 4 +- .../capabilities/__mocks__/ml_capabilities.ts | 4 +- .../lib/capabilities/capabilities_switcher.ts | 4 +- .../capabilities/check_capabilities.test.ts | 14 +- .../lib/capabilities/check_capabilities.ts | 2 +- .../annotation_service/annotation.test.ts | 10 +- .../bucket_span_estimator.js | 48 +- .../bucket_span_estimator.test.ts | 18 +- .../polled_data_checker.js | 4 +- .../single_series_checker.js | 16 +- .../calculate_model_memory_limit.ts | 6 +- .../models/calendar/calendar_manager.ts | 14 +- .../models/data_recognizer/data_recognizer.ts | 134 +- .../models/data_visualizer/data_visualizer.ts | 18 +- .../models/fields_service/fields_service.ts | 6 +- .../file_data_visualizer/import_data.ts | 4 +- .../ml/server/models/filter/filter_manager.ts | 8 +- .../job_audit_messages/job_audit_messages.js | 8 +- .../ml/server/models/job_service/groups.ts | 10 +- .../ml/server/models/job_service/jobs.ts | 44 +- .../new_job/categorization/examples.ts | 10 +- .../new_job/categorization/top_categories.ts | 4 +- .../categorization/validation_results.ts | 12 +- .../models/job_service/new_job/line_chart.ts | 2 +- .../job_service/new_job/population_chart.ts | 2 +- .../job_service/new_job_caps/field_service.ts | 34 +- .../new_job_caps/new_job_caps.test.ts | 8 +- .../job_service/new_job_caps/new_job_caps.ts | 8 +- .../models/job_service/new_job_caps/rollup.ts | 2 +- .../job_validation/job_validation.test.ts | 76 +- .../models/job_validation/job_validation.ts | 6 +- .../job_validation/validate_bucket_span.js | 20 +- .../validate_bucket_span.test.ts | 28 +- .../validate_cardinality.test.ts | 72 +- .../job_validation/validate_cardinality.ts | 24 +- .../validate_influencers.test.ts | 30 +- .../job_validation/validate_influencers.ts | 4 +- .../validate_model_memory_limit.test.ts | 72 +- .../validate_time_range.test.ts | 46 +- .../build_anomaly_table_items.js | 23 +- .../models/results_service/results_service.ts | 12 +- .../routes/apidoc_scripts/schema_extractor.ts | 4 +- .../routes/apidoc_scripts/schema_worker.ts | 4 +- .../routes/apidoc_scripts/version_filter.ts | 2 +- x-pack/plugins/ml/server/routes/system.ts | 2 +- .../__tests__/format_timestamp_to_duration.js | 17 +- .../monitoring/common/cancel_promise.ts | 4 +- .../monitoring/public/angular/app_modules.ts | 38 +- .../public/angular/helpers/routes.ts | 2 +- .../public/angular/providers/private.js | 14 +- .../public/angular/providers/url.js | 28 +- .../public/components/alerts/alerts.js | 14 +- .../configuration/configuration.test.tsx | 15 +- .../alerts/configuration/step1.test.tsx | 57 +- .../components/alerts/configuration/step1.tsx | 8 +- .../components/alerts/configuration/step2.tsx | 2 +- .../components/alerts/manage_email_action.tsx | 18 +- .../public/components/alerts/status.test.tsx | 2 +- .../components/apm/instances/instances.js | 12 +- .../components/beats/listing/listing.js | 12 +- .../components/chart/__tests__/get_color.js | 2 +- .../chart/__tests__/get_last_value.js | 2 +- .../components/chart/__tests__/get_title.js | 2 +- .../chart/__tests__/get_values_for_legend.js | 2 +- .../public/components/chart/chart_target.js | 8 +- .../public/components/chart/get_title.js | 2 +- .../public/components/chart/get_units.js | 2 +- .../components/chart/horizontal_legend.js | 2 +- .../chart/monitoring_timeseries_container.js | 4 +- .../chart/timeseries_visualization.js | 2 +- .../components/cluster/listing/listing.js | 6 +- .../cluster/overview/elasticsearch_panel.js | 2 +- .../cluster/overview/license_text.js | 2 +- .../components/elasticsearch/ccr/ccr.js | 10 +- .../elasticsearch/indices/indices.js | 18 +- .../components/elasticsearch/nodes/cells.js | 2 +- .../components/elasticsearch/nodes/nodes.js | 6 +- .../shard_activity/parse_props.js | 6 +- .../shard_activity/recovery_index.js | 2 +- .../shard_activity/shard_activity.js | 10 +- .../shard_activity/source_destination.js | 2 +- .../shard_allocation/components/assigned.js | 4 +- .../components/cluster_view.js | 6 +- .../shard_allocation/components/shard.js | 6 +- .../shard_allocation/components/table_body.js | 2 +- .../shard_allocation/components/table_head.js | 2 +- .../shard_allocation/components/unassigned.js | 2 +- .../shard_allocation/lib/decorate_shards.js | 6 +- .../shard_allocation/lib/vents.js | 8 +- .../shard_allocation/shard_allocation.js | 2 +- .../transformers/indices_by_nodes.js | 4 +- .../transformers/nodes_by_indices.js | 6 +- .../components/kibana/instances/instances.js | 10 +- .../monitoring/public/components/logs/logs.js | 10 +- .../components/logstash/listing/listing.js | 14 +- .../logstash/listing/listing.test.js | 2 +- .../pipeline_listing/pipeline_listing.js | 6 +- .../models/graph/__tests__/index.js | 198 +-- .../pipeline_viewer/models/graph/if_vertex.js | 12 +- .../pipeline_viewer/models/graph/index.js | 22 +- .../pipeline_viewer/models/graph/vertex.js | 6 +- .../models/list/flatten_pipeline_section.js | 2 +- .../pipeline/__tests__/make_statement.js | 4 +- .../models/pipeline/if_statement.js | 4 +- .../models/pipeline/pipeline.js | 17 +- .../views/__test__/plugin_statement.test.js | 2 +- .../views/__test__/statement_list.test.js | 2 +- .../pipeline_viewer/views/detail_drawer.js | 6 +- .../pipeline_viewer/views/statement_list.js | 10 +- .../metricbeat_migration/flyout/flyout.js | 8 +- .../no_data/__tests__/checker_errors.test.js | 2 +- .../components/no_data/checker_errors.js | 2 +- .../no_data/reasons/reason_found.js | 2 +- .../public/components/renderers/setup_mode.js | 2 +- .../sparkline/__test__/index.test.js | 4 +- .../sparkline/sparkline_flot_chart.js | 4 +- .../public/components/table/eui_table.js | 4 +- .../public/components/table/eui_table_ssp.js | 2 +- .../public/components/table/storage.js | 12 +- .../elasticsearch/ml_job_listing/index.js | 8 +- .../__tests__/monitoring_main_controller.js | 2 +- .../public/directives/main/index.js | 10 +- .../plugins/monitoring/public/jest.helpers.ts | 2 +- .../public/lib/calculate_shard_stats.js | 2 +- .../__tests__/enabler.test.js | 2 +- .../__tests__/start_checks.test.js | 4 +- .../elasticsearch_settings/start_checks.js | 4 +- .../public/lib/ensure_minimum_time.js | 2 +- .../public/lib/ensure_minimum_time.test.js | 14 +- .../monitoring/public/lib/get_page_data.js | 4 +- .../monitoring/public/lib/route_init.js | 2 +- .../monitoring/public/lib/setup_mode.test.js | 16 +- x-pack/plugins/monitoring/public/plugin.ts | 2 +- .../public/services/__tests__/executor.js | 12 +- .../monitoring/public/services/breadcrumbs.js | 2 +- .../monitoring/public/services/clusters.js | 6 +- .../monitoring/public/services/executor.js | 2 +- x-pack/plugins/monitoring/public/url_state.ts | 2 +- .../public/views/__tests__/base_controller.js | 12 +- .../views/__tests__/base_table_controller.js | 2 +- .../monitoring/public/views/alerts/index.js | 8 +- .../public/views/apm/instance/index.js | 4 +- .../public/views/apm/instances/index.js | 4 +- .../public/views/apm/overview/index.js | 4 +- .../public/views/base_controller.js | 4 +- .../public/views/base_table_controller.js | 2 +- .../public/views/beats/beat/get_page_data.js | 4 +- .../public/views/beats/beat/index.js | 2 +- .../views/beats/listing/get_page_data.js | 4 +- .../public/views/beats/listing/index.js | 2 +- .../views/beats/overview/get_page_data.js | 4 +- .../public/views/beats/overview/index.js | 2 +- .../public/views/cluster/listing/index.js | 6 +- .../public/views/cluster/overview/index.js | 4 +- .../views/elasticsearch/ccr/get_page_data.js | 4 +- .../public/views/elasticsearch/ccr/index.js | 4 +- .../elasticsearch/ccr/shard/get_page_data.js | 4 +- .../views/elasticsearch/ccr/shard/index.js | 6 +- .../elasticsearch/index/advanced/index.js | 8 +- .../public/views/elasticsearch/index/index.js | 8 +- .../views/elasticsearch/indices/index.js | 4 +- .../elasticsearch/ml_jobs/get_page_data.js | 4 +- .../views/elasticsearch/ml_jobs/index.js | 2 +- .../elasticsearch/node/advanced/index.js | 8 +- .../views/elasticsearch/node/get_page_data.js | 4 +- .../public/views/elasticsearch/node/index.js | 8 +- .../public/views/elasticsearch/nodes/index.js | 8 +- .../elasticsearch/overview/controller.js | 4 +- .../public/views/kibana/instance/index.js | 6 +- .../views/kibana/instances/get_page_data.js | 4 +- .../public/views/kibana/instances/index.js | 2 +- .../public/views/kibana/overview/index.js | 8 +- .../monitoring/public/views/license/index.js | 2 +- .../views/logstash/node/advanced/index.js | 6 +- .../public/views/logstash/node/index.js | 6 +- .../views/logstash/node/pipelines/index.js | 6 +- .../views/logstash/nodes/get_page_data.js | 4 +- .../public/views/logstash/nodes/index.js | 2 +- .../public/views/logstash/overview/index.js | 8 +- .../public/views/logstash/pipeline/index.js | 14 +- .../public/views/logstash/pipelines/index.js | 10 +- .../no_data/__tests__/model_updater.test.js | 2 +- .../public/views/no_data/controller.js | 2 +- .../public/views/no_data/model_updater.js | 2 +- .../server/__tests__/deprecations.js | 18 +- .../server/alerts/license_expiration.test.ts | 16 +- .../server/cloud/__tests__/cloud_service.js | 4 +- x-pack/plugins/monitoring/server/cloud/aws.js | 4 +- .../plugins/monitoring/server/cloud/azure.js | 4 +- x-pack/plugins/monitoring/server/cloud/gcp.js | 6 +- .../__tests__/alerts_cluster_search.js | 12 +- .../__tests__/alerts_clusters_aggregation.js | 8 +- .../__tests__/fixtures/create_stubs.js | 5 +- .../__tests__/verify_monitoring_license.js | 30 +- .../cluster_alerts/alerts_cluster_search.js | 6 +- .../alerts_clusters_aggregation.js | 2 +- x-pack/plugins/monitoring/server/config.ts | 10 +- .../__tests__/bulk_uploader.js | 54 +- .../server/kibana_monitoring/bulk_uploader.js | 6 +- .../server/lib/__tests__/calculate_auto.js | 2 +- .../lib/__tests__/calculate_overall_status.js | 6 +- .../server/lib/__tests__/create_query.js | 4 +- .../server/lib/__tests__/helpers.js | 2 +- .../server/lib/alerts/fetch_cluster_state.ts | 2 +- .../server/lib/alerts/fetch_licenses.ts | 2 +- .../server/lib/alerts/fetch_status.ts | 2 +- .../lib/alerts/get_ccs_index_pattern.ts | 4 +- .../monitoring/server/lib/apm/_apm_stats.js | 4 +- .../server/lib/apm/get_apms_for_clusters.js | 2 +- .../lib/beats/__tests__/create_beats_query.js | 2 +- .../server/lib/beats/_beats_stats.js | 4 +- .../lib/beats/get_beats_for_clusters.js | 2 +- .../server/lib/beats/get_latest_stats.js | 4 +- .../monitoring/server/lib/calculate_auto.js | 2 +- .../monitoring/server/lib/ccs_utils.js | 2 +- .../__test__/get_clusters_summary.test.js | 2 +- .../__tests__/flag_supported_clusters.js | 25 +- .../cluster/__tests__/get_clusters_state.js | 8 +- .../lib/cluster/flag_supported_clusters.js | 10 +- .../server/lib/cluster/get_cluster_license.js | 2 +- .../server/lib/cluster/get_cluster_stats.js | 2 +- .../lib/cluster/get_clusters_from_request.js | 10 +- .../server/lib/cluster/get_clusters_state.js | 8 +- .../server/lib/cluster/get_clusters_stats.js | 6 +- .../lib/cluster/get_clusters_summary.js | 2 +- .../server/lib/details/get_metrics.js | 6 +- .../server/lib/details/get_series.js | 6 +- .../lib/elasticsearch/convert_metric_names.js | 2 +- .../lib/elasticsearch/get_last_recovery.js | 4 +- .../server/lib/elasticsearch/get_ml_jobs.js | 4 +- .../indices/get_index_summary.js | 2 +- .../lib/elasticsearch/indices/get_indices.js | 4 +- .../elasticsearch/nodes/__tests__/lookups.js | 4 +- .../elasticsearch/nodes/get_node_summary.js | 6 +- .../nodes/get_nodes/get_live_nodes.js | 2 +- .../nodes/get_nodes/get_metric_aggs.js | 2 +- .../nodes/get_nodes/get_node_ids.js | 2 +- .../nodes/get_nodes/get_nodes.js | 2 +- .../nodes/get_nodes/get_paginated_nodes.js | 6 +- .../nodes/get_nodes/handle_response.js | 2 +- .../nodes/get_nodes/map_nodes_metrics.js | 8 +- .../nodes/get_nodes/sort_nodes.js | 2 +- .../shards/__tests__/get_shard_stats.js | 4 +- .../calculate_shard_stat_indices_totals.js | 2 +- .../get_indices_unassigned_shard_stats.js | 4 +- ...get_indices_unassigned_shard_stats.test.js | 2 +- .../shards/get_nodes_shard_count.test.js | 2 +- .../shards/get_shard_allocation.test.js | 4 +- .../elasticsearch/shards/get_shard_stats.js | 2 +- .../shards/normalize_shard_objects.js | 12 +- .../__tests__/cluster.js | 8 +- .../elasticsearch_settings/__tests__/nodes.js | 2 +- .../lib/elasticsearch_settings/find_reason.js | 8 +- .../server/lib/errors/auth_errors.js | 2 +- .../server/lib/filter_partial_buckets.js | 2 +- .../lib/kibana/__tests__/get_kibana_info.js | 4 +- .../server/lib/kibana/get_kibanas.js | 4 +- .../lib/kibana/get_kibanas_for_clusters.js | 8 +- .../server/lib/logs/get_log_types.js | 4 +- .../monitoring/server/lib/logs/get_logs.js | 2 +- .../lib/logstash/__tests__/get_node_info.js | 8 +- .../server/lib/logstash/get_cluster_status.js | 2 +- .../lib/logstash/get_logstash_for_clusters.js | 12 +- .../server/lib/logstash/get_nodes.js | 4 +- .../lib/logstash/get_paginated_pipelines.js | 16 +- .../server/lib/logstash/get_pipeline.js | 4 +- .../server/lib/logstash/get_pipeline_ids.js | 4 +- .../lib/logstash/get_pipeline_versions.js | 2 +- .../lib/logstash/get_pipeline_vertex.js | 6 +- .../server/lib/logstash/sort_pipelines.js | 2 +- .../lib/metrics/classes/quota_metric.js | 2 +- .../__test__/latency_calculation.test.js | 2 +- .../lib/metrics/elasticsearch/classes.js | 12 +- .../server/lib/metrics/logstash/classes.js | 12 +- .../server/lib/pagination/filter.js | 2 +- .../__test__/get_collection_status.test.js | 5 +- .../setup/collection/get_collection_status.js | 2 +- .../monitoring/server/license_service.ts | 2 +- .../routes/api/v1/alerts/legacy_alerts.js | 2 +- .../api/v1/apm/_get_apm_cluster_status.js | 2 +- .../api/v1/check_access/check_access.js | 2 +- .../server/routes/api/v1/cluster/cluster.js | 2 +- .../server/routes/api/v1/cluster/clusters.js | 2 +- .../server/routes/api/v1/elasticsearch/ccr.js | 6 +- .../api/v1/elasticsearch/index_detail.js | 2 +- .../api/v1/elasticsearch/node_detail.js | 2 +- .../v1/kibana/_get_kibana_cluster_status.js | 2 +- .../server/routes/api/v1/logstash/node.js | 2 +- .../server/routes/api/v1/logstash/pipeline.js | 2 +- .../pipelines/cluster_pipeline_ids.js | 2 +- .../logstash/pipelines/cluster_pipelines.js | 2 +- .../v1/logstash/pipelines/node_pipelines.js | 2 +- .../api/v1/setup/cluster_setup_status.js | 2 +- ...sable_elasticsearch_internal_collection.js | 2 +- .../routes/api/v1/setup/node_setup_status.js | 2 +- .../plugins/monitoring/server/routes/index.js | 2 +- .../telemetry_collection/get_all_stats.ts | 4 +- .../telemetry_collection/get_beats_stats.ts | 6 +- .../get_cluster_uuids.test.ts | 4 +- .../telemetry_collection/get_cluster_uuids.ts | 2 +- .../telemetry_collection/get_es_stats.test.ts | 4 +- .../telemetry_collection/get_es_stats.ts | 2 +- .../get_high_level_stats.ts | 2 +- .../telemetry_collection/get_licenses.test.ts | 4 +- .../public/components/action_menu.tsx | 12 +- x-pack/plugins/observability/server/plugin.ts | 2 +- .../server/utils/create_or_update_index.ts | 2 +- .../server/lib/get_next_midnight.test.ts | 5 +- .../lib/tasks/visualizations/task_runner.ts | 2 +- .../oss_telemetry/server/test_utils/index.ts | 4 +- .../public/application/components/main.tsx | 2 +- .../components/output_pane/context_tab.tsx | 8 +- .../components/output_pane/parameters_tab.tsx | 2 +- .../public/application/lib/format.test.ts | 2 +- x-pack/plugins/painless_lab/public/plugin.tsx | 2 +- .../painless_lab/server/services/license.ts | 2 +- .../helpers/http_requests.js | 6 +- .../helpers/remote_clusters_add.helpers.js | 4 +- .../helpers/remote_clusters_edit.helpers.js | 2 +- .../helpers/remote_clusters_list.helpers.js | 4 +- .../remote_clusters_add.test.js | 10 +- .../remote_clusters_list.test.js | 6 +- .../common/lib/cluster_serialization.ts | 2 +- .../remote_cluster_form.js | 32 +- .../remote_cluster_form.test.js | 2 +- .../validators/validate_name.test.js | 4 +- .../validators/validate_seeds.js | 2 +- .../remote_cluster_add.container.js | 6 +- .../remote_cluster_add/remote_cluster_add.js | 2 +- .../remote_cluster_edit.container.js | 10 +- .../remote_cluster_edit.js | 2 +- ...emove_cluster_button_provider.container.js | 4 +- .../remove_cluster_button_provider.js | 4 +- .../detail_panel/detail_panel.container.js | 4 +- .../detail_panel/detail_panel.js | 4 +- .../remote_cluster_list.container.js | 6 +- .../remote_cluster_table.container.js | 4 +- .../remote_cluster_table.js | 16 +- .../public/application/services/routing.js | 6 +- .../application/services/validate_address.js | 2 +- .../services/validate_address.test.js | 12 +- .../application/store/actions/add_cluster.js | 6 +- .../application/store/actions/detail_panel.js | 4 +- .../application/store/actions/edit_cluster.js | 10 +- .../store/actions/load_clusters.js | 2 +- .../store/actions/refresh_clusters.js | 2 +- .../store/actions/remove_clusters.js | 8 +- .../store/middleware/detail_panel.js | 2 +- .../application/store/reducers/clusters.js | 8 +- .../application/store/selectors/index.js | 26 +- .../plugins/remote_clusters/server/plugin.ts | 2 +- .../reporting/common/cancellation_token.ts | 2 +- x-pack/plugins/reporting/common/poller.ts | 2 +- .../buttons/report_error_button.tsx | 2 +- .../public/components/report_listing.tsx | 6 +- .../components/reporting_panel_content.tsx | 2 +- .../public/lib/stream_handler.test.ts | 18 +- .../reporting/public/lib/stream_handler.ts | 2 +- .../panel_actions/get_csv_panel_action.tsx | 2 +- x-pack/plugins/reporting/public/plugin.tsx | 8 +- .../register_csv_reporting.tsx | 2 +- .../register_pdf_png_reporting.tsx | 2 +- .../reporting/server/config/create_config.ts | 9 +- .../default_chromium_sandbox_disabled.test.ts | 2 +- x-pack/plugins/rollup/fixtures/job.js | 2 +- .../components/field_list/field_list.js | 2 +- .../job_action_menu.container.js | 6 +- .../job_action_menu/job_action_menu.js | 8 +- .../job_create/job_create.container.js | 6 +- .../sections/job_create/job_create.js | 14 +- .../steps/components/field_chooser.js | 8 +- .../job_create/steps/step_date_histogram.js | 10 +- .../job_create/steps/step_histogram.js | 8 +- .../job_create/steps/step_logistics.js | 12 +- .../sections/job_create/steps/step_metrics.js | 20 +- .../sections/job_create/steps/step_review.js | 2 +- .../sections/job_create/steps/step_terms.js | 6 +- .../sections/job_create/steps_config/index.js | 12 +- .../detail_panel/detail_panel.container.js | 4 +- .../detail_panel/detail_panel.test.js | 18 +- .../sections/job_list/job_list.container.js | 8 +- .../sections/job_list/job_list.test.js | 10 +- .../job_list/job_table/job_table.container.js | 12 +- .../sections/job_list/job_table/job_table.js | 34 +- .../job_list/job_table/job_table.test.js | 24 +- .../public/crud_app/services/filter_items.js | 4 +- .../crud_app/services/flatten_panel_tree.js | 2 +- .../public/crud_app/services/format_fields.js | 2 +- .../rollup/public/crud_app/services/jobs.js | 6 +- .../crud_app/services/noticeable_delay.js | 2 +- .../public/crud_app/services/query_params.js | 2 +- .../crud_app/services/retype_metrics.js | 6 +- .../public/crud_app/services/routing.js | 6 +- .../public/crud_app/services/sort_table.js | 2 +- .../crud_app/services/track_ui_metric.ts | 2 +- .../store/actions/change_job_status.js | 4 +- .../crud_app/store/actions/clone_job.js | 4 +- .../crud_app/store/actions/create_job.js | 6 +- .../crud_app/store/actions/delete_jobs.js | 2 +- .../crud_app/store/actions/detail_panel.js | 4 +- .../crud_app/store/actions/load_jobs.js | 2 +- .../crud_app/store/actions/refresh_jobs.js | 2 +- .../crud_app/store/actions/table_state.js | 8 +- .../crud_app/store/middleware/clone_job.js | 2 +- .../crud_app/store/middleware/detail_panel.js | 2 +- .../public/crud_app/store/reducers/jobs.js | 4 +- .../public/crud_app/store/selectors/index.js | 38 +- .../rollup_index_pattern_creation_config.js | 6 +- .../rollup_index_pattern_list_config.js | 8 +- .../helpers/job_clone.helpers.js | 2 +- .../helpers/job_create.helpers.js | 12 +- .../helpers/job_list.helpers.js | 2 +- .../job_create_clone.test.js | 10 +- .../job_create_date_histogram.test.js | 8 +- .../job_create_histogram.test.js | 2 +- .../job_create_logistics.test.js | 36 +- .../job_create_metrics.test.js | 40 +- .../job_create_review.test.js | 10 +- .../job_create_terms.test.js | 2 +- .../test/client_integration/job_list.test.js | 2 +- .../client_integration/job_list_clone.test.js | 2 +- .../rollup/server/collectors/register.ts | 6 +- .../lib/__tests__/jobs_compatibility.js | 32 +- .../rollup/server/lib/jobs_compatibility.ts | 2 +- .../rollup/server/lib/map_capabilities.ts | 2 +- .../lib/merge_capabilities_with_fields.ts | 8 +- .../rollup_search_capabilities.test.js | 2 +- x-pack/plugins/rollup/server/plugin.ts | 2 +- .../rollup/server/rollup_data_enricher.ts | 2 +- .../register_fields_for_wildcard_route.ts | 2 +- .../register_validate_index_pattern_route.ts | 2 +- .../plugins/rollup/server/services/license.ts | 2 +- .../__jest__/unsafe_utils.test.ts | 12 +- .../components/profile_tree/init_data.ts | 4 +- .../components/profile_tree/profile_tree.tsx | 2 +- .../shard_details/shard_details.tsx | 2 +- .../components/profile_tree/unsafe_utils.ts | 10 +- .../components/profile_tree/utils.ts | 2 +- .../application/containers/main/main.tsx | 2 +- .../containers/profile_query_editor.tsx | 4 +- .../public/application/editor/editor.test.tsx | 2 +- .../utils/check_for_json_errors.test.ts | 6 +- .../application/utils/ns_to_pretty.test.ts | 18 +- .../plugins/searchprofiler/public/plugin.ts | 2 +- .../plugins/searchprofiler/server/plugin.ts | 2 +- .../common/licensing/license_service.test.ts | 2 +- .../common/licensing/license_service.ts | 4 +- .../common/model/authenticated_user.test.ts | 2 +- .../common/privilege_calculator_utils.ts | 2 +- .../access_agreement_page.tsx | 4 +- .../authentication_state_page.tsx | 2 +- .../disabled_login_form.tsx | 2 +- .../components/login_form/login_form.test.tsx | 12 +- .../components/login_form/login_form.tsx | 4 +- .../overwritten_session_page.tsx | 2 +- .../api_keys_grid/api_keys_grid_page.test.tsx | 14 +- .../api_keys_grid/api_keys_grid_page.tsx | 20 +- .../management/management_service.test.ts | 2 +- .../public/management/management_service.ts | 2 +- .../role_combo_box/role_combo_box.tsx | 8 +- .../delete_provider/delete_provider.test.tsx | 8 +- .../delete_provider/delete_provider.tsx | 6 +- .../edit_role_mapping_page.test.tsx | 10 +- .../edit_role_mapping_page.tsx | 8 +- .../mapping_info_panel/mapping_info_panel.tsx | 6 +- .../role_selector/role_selector.tsx | 10 +- .../role_selector/role_template_editor.tsx | 6 +- .../role_template_type_select.tsx | 2 +- .../rule_editor_panel/field_rule_editor.tsx | 4 +- .../rule_group_editor.test.tsx | 14 +- .../rule_editor_panel/rule_group_editor.tsx | 4 +- .../rule_editor_panel/rule_group_title.tsx | 2 +- .../rule_editor_panel/visual_rule_editor.tsx | 4 +- .../role_mappings/model/all_rule.test.ts | 2 +- .../role_mappings/model/all_rule.ts | 4 +- .../role_mappings/model/any_rule.test.ts | 2 +- .../role_mappings/model/any_rule.ts | 6 +- .../model/except_all_rule.test.ts | 2 +- .../role_mappings/model/except_all_rule.ts | 4 +- .../model/except_any_rule.test.ts | 2 +- .../role_mappings/model/except_any_rule.ts | 6 +- .../role_mappings/model/field_rule.test.ts | 2 +- .../role_mappings/model/rule_builder.test.ts | 2 +- .../role_mappings/model/rule_builder.ts | 2 +- .../role_mappings/role_mappings_api_client.ts | 4 +- .../role_mappings_grid_page.tsx | 14 +- .../roles/edit_role/edit_role_page.tsx | 18 +- .../privileges/es/cluster_privileges.tsx | 4 +- .../es/elasticsearch_privileges.tsx | 4 +- .../privileges/es/index_privilege_form.tsx | 4 +- .../privileges/es/index_privileges.tsx | 4 +- .../feature_table/__fixtures__/index.ts | 2 +- .../feature_table/change_all_privileges.tsx | 2 +- .../feature_table/feature_table.test.tsx | 8 +- .../kibana/feature_table/feature_table.tsx | 8 +- .../feature_table_expanded_row.tsx | 8 +- .../feature_table/sub_feature_form.test.tsx | 6 +- .../kibana/feature_table/sub_feature_form.tsx | 10 +- .../feature_table_cell.test.tsx | 7 +- .../privilege_form_calculator.test.ts | 12 +- .../privilege_form_calculator.ts | 34 +- .../privilege_summary/__fixtures__/index.ts | 4 +- .../privilege_summary_calculator.ts | 12 +- .../privilege_summary_expanded_row.tsx | 4 +- .../privilege_summary_table.test.tsx | 2 +- .../privilege_summary_table.tsx | 10 +- .../privilege_summary/space_column_header.tsx | 8 +- .../privilege_selector.tsx | 2 +- .../simple_privilege_section.tsx | 14 +- .../privilege_display.tsx | 2 +- .../privilege_space_form.test.tsx | 5 +- .../privilege_space_form.tsx | 8 +- .../privilege_space_table.test.tsx | 2 +- .../privilege_space_table.tsx | 16 +- .../space_aware_privilege_section.tsx | 2 +- .../space_selector.tsx | 6 +- .../spaces_popover_list.test.tsx | 7 +- .../spaces_popover_list.tsx | 2 +- .../roles/edit_role/validate_role.test.ts | 2 +- .../roles/edit_role/validate_role.ts | 4 +- .../roles/model/kibana_privilege.ts | 2 +- .../roles/model/kibana_privileges.ts | 6 +- .../roles/model/privilege_collection.ts | 2 +- .../management/roles/model/secured_feature.ts | 2 +- .../roles/model/secured_sub_feature.ts | 6 +- .../model/sub_feature_privilege_group.ts | 2 +- .../management/roles/roles_api_client.ts | 6 +- .../confirm_delete/confirm_delete.tsx | 4 +- .../roles/roles_grid/roles_grid_page.test.tsx | 10 +- .../roles/roles_grid/roles_grid_page.tsx | 4 +- .../change_password_form.tsx | 2 +- .../confirm_delete_users.test.tsx | 2 +- .../confirm_delete_users.tsx | 4 +- .../users/edit_user/edit_user_page.tsx | 8 +- .../users/users_grid/users_grid_page.tsx | 4 +- .../nav_control/nav_control_component.tsx | 2 +- .../nav_control/nav_control_service.test.ts | 2 +- .../public/session/session_expired.test.ts | 4 +- .../session_timeout_http_interceptor.test.ts | 2 +- ...thorized_response_http_interceptor.test.ts | 6 +- .../server/authentication/authenticator.ts | 4 +- .../server/authentication/providers/http.ts | 2 +- .../authentication/providers/kerberos.test.ts | 6 +- .../authentication/providers/kerberos.ts | 2 +- .../authentication/providers/oidc.test.ts | 2 +- .../authentication/providers/pki.test.ts | 4 +- .../authentication/providers/saml.test.ts | 2 +- .../server/authentication/providers/saml.ts | 5 +- .../authentication/providers/token.test.ts | 4 +- .../server/authorization/actions/ui.ts | 2 +- .../authorization/api_authorization.test.ts | 4 +- .../server/authorization/api_authorization.ts | 4 +- .../authorization/app_authorization.test.ts | 4 +- .../server/authorization/app_authorization.ts | 2 +- .../authorization/check_privileges.test.ts | 2 +- .../server/authorization/check_privileges.ts | 4 +- .../check_saved_objects_privileges.test.ts | 2 +- .../check_saved_objects_privileges.ts | 2 +- .../disable_ui_capabilities.test.ts | 6 +- .../authorization/disable_ui_capabilities.ts | 10 +- .../privilege_serializer.test.ts | 18 +- .../authorization/privilege_serializer.ts | 2 +- .../feature_privilege_builder/api.ts | 2 +- .../feature_privilege_builder/app.ts | 2 +- .../feature_privilege_builder/catalogue.ts | 2 +- .../feature_privilege_builder/index.ts | 2 +- .../feature_privilege_builder/management.ts | 2 +- .../feature_privilege_builder/saved_object.ts | 8 +- .../feature_privilege_builder/ui.ts | 2 +- .../feature_privilege_iterator.test.ts | 2 +- .../authorization/privileges/privileges.ts | 8 +- .../register_privileges_with_cluster.test.ts | 2 +- .../validate_feature_privileges.ts | 8 +- x-pack/plugins/security/server/config.ts | 8 +- x-pack/plugins/security/server/index.ts | 2 +- x-pack/plugins/security/server/plugin.ts | 4 +- .../server/routes/api_keys/invalidate.ts | 2 +- .../routes/authentication/basic.test.ts | 4 +- .../authorization/privileges/get_builtin.ts | 4 +- .../roles/model/elasticsearch_role.ts | 58 +- .../authorization/roles/model/put_payload.ts | 16 +- .../server/routes/indices/get_fields.ts | 2 +- .../routes/role_mapping/feature_check.ts | 8 +- .../server/routes/role_mapping/get.ts | 2 +- .../server/routes/views/index.test.ts | 6 +- .../security/server/saved_objects/index.ts | 18 +- ...ecure_saved_objects_client_wrapper.test.ts | 10 +- .../secure_saved_objects_client_wrapper.ts | 12 +- .../common/endpoint/generate_data.test.ts | 4 +- .../siem/common/endpoint/generate_data.ts | 8 +- x-pack/plugins/siem/common/exact_check.ts | 4 +- x-pack/plugins/siem/common/format_errors.ts | 6 +- x-pack/plugins/siem/common/test_utils.ts | 2 +- .../siem/cypress/integration/cases.spec.ts | 16 +- .../integration/cases_connectors.spec.ts | 8 +- .../cypress/integration/detections.spec.ts | 14 +- .../integration/detections_timeline.spec.ts | 6 +- .../cypress/integration/events_viewer.spec.ts | 20 +- .../integration/fields_browser.spec.ts | 22 +- .../siem/cypress/integration/inspect.spec.ts | 4 +- .../siem/cypress/integration/overview.spec.ts | 12 +- .../cypress/integration/pagination.spec.ts | 8 +- .../signal_detection_rules.spec.ts | 16 +- .../signal_detection_rules_custom.spec.ts | 100 +- .../signal_detection_rules_export.spec.ts | 4 +- .../signal_detection_rules_ml.spec.ts | 78 +- .../signal_detection_rules_prebuilt.spec.ts | 22 +- .../timeline_data_providers.spec.ts | 4 +- .../timeline_search_or_filter.spec.ts | 2 +- .../cypress/integration/url_state.spec.ts | 13 +- x-pack/plugins/siem/cypress/plugins/index.js | 2 +- .../plugins/siem/cypress/support/commands.js | 4 +- x-pack/plugins/siem/cypress/support/index.js | 4 +- .../siem/cypress/tasks/configure_cases.ts | 4 +- .../siem/cypress/tasks/create_new_case.ts | 6 +- .../siem/cypress/tasks/create_new_rule.ts | 36 +- .../plugins/siem/cypress/tasks/date_picker.ts | 28 +- .../plugins/siem/cypress/tasks/detections.ts | 30 +- .../siem/cypress/tasks/fields_browser.ts | 4 +- .../siem/cypress/tasks/hosts/all_hosts.ts | 14 +- .../cypress/tasks/hosts/authentications.ts | 4 +- .../siem/cypress/tasks/hosts/events.ts | 9 +- .../cypress/tasks/hosts/uncommon_processes.ts | 4 +- x-pack/plugins/siem/cypress/tasks/login.ts | 2 +- x-pack/plugins/siem/cypress/tasks/overview.ts | 4 +- .../plugins/siem/cypress/tasks/siem_header.ts | 9 +- .../plugins/siem/cypress/tasks/siem_main.ts | 2 +- .../cypress/tasks/signal_detection_rules.ts | 20 +- x-pack/plugins/siem/cypress/tasks/timeline.ts | 15 +- .../detection_engine_header_page/index.tsx | 2 +- .../components/rules/add_item_form/index.tsx | 2 +- .../rules/description_step/helpers.test.tsx | 20 +- .../rules/description_step/helpers.tsx | 10 +- .../rules/description_step/index.test.tsx | 5 +- .../rules/description_step/index.tsx | 2 +- .../description_step/ml_job_description.tsx | 2 +- .../alerts/components/rules/mitre/index.tsx | 10 +- .../components/rules/ml_job_select/index.tsx | 4 +- .../components/rules/query_bar/index.tsx | 2 +- .../rules/rule_actions_field/index.tsx | 4 +- .../rule_actions_overflow/index.test.tsx | 45 +- .../rules/rule_actions_overflow/index.tsx | 2 +- .../components/rules/rule_switch/index.tsx | 2 +- .../rules/schedule_item_form/index.tsx | 4 +- .../rules/step_about_rule/index.test.tsx | 5 +- .../rules/step_about_rule/schema.tsx | 4 +- .../step_about_rule_details/index.test.tsx | 14 +- .../rules/step_about_rule_details/index.tsx | 4 +- .../rules/step_rule_actions/index.tsx | 2 +- .../rules/step_rule_actions/schema.tsx | 2 +- .../rules/step_rule_actions/utils.ts | 2 +- .../rules/throttle_select_field/index.tsx | 4 +- .../alerts/components/signals/actions.tsx | 6 +- .../alerts/components/signals/helpers.ts | 8 +- .../signals_histogram_panel/index.tsx | 4 +- .../containers/detection_engine/rules/api.ts | 12 +- .../rules/fetch_index_patterns.tsx | 4 +- .../rules/use_pre_packaged_rules.tsx | 2 +- .../detection_engine/rules/use_rule.test.tsx | 2 +- .../rules/use_rule_status.tsx | 4 +- .../detection_engine/rules/use_rules.test.tsx | 6 +- .../signals/use_query.test.tsx | 4 +- .../detection_engine/rules/all/actions.tsx | 10 +- .../rules/all/batch_actions.tsx | 18 +- .../rules/all/columns.test.tsx | 4 +- .../detection_engine/rules/all/columns.tsx | 4 +- .../detection_engine/rules/all/index.tsx | 6 +- .../detection_engine/rules/all/reducer.ts | 8 +- .../rules_table_filters.tsx | 4 +- .../detection_engine/rules/create/helpers.ts | 10 +- .../detection_engine/rules/create/index.tsx | 8 +- .../rules/details/failure_history.tsx | 2 +- .../detection_engine/rules/details/index.tsx | 2 +- .../detection_engine/rules/edit/index.tsx | 4 +- .../pages/detection_engine/rules/helpers.tsx | 4 +- x-pack/plugins/siem/public/app/home/index.tsx | 2 +- .../components/add_comment/index.test.tsx | 15 +- .../components/all_cases/columns.test.tsx | 15 +- .../cases/components/all_cases/index.test.tsx | 84 +- .../cases/components/all_cases/index.tsx | 4 +- .../all_cases/table_filters.test.tsx | 38 +- .../components/all_cases/table_filters.tsx | 16 +- .../cases/components/callout/index.test.tsx | 36 +- .../public/cases/components/callout/index.tsx | 2 +- .../components/case_header_page/index.tsx | 2 +- .../components/case_view/actions.test.tsx | 15 +- .../cases/components/case_view/index.test.tsx | 106 +- .../cases/components/case_view/index.tsx | 10 +- .../configure_cases/button.test.tsx | 42 +- .../configure_cases/closure_options.test.tsx | 23 +- .../closure_options_radio.test.tsx | 9 +- .../configure_cases/connectors.test.tsx | 23 +- .../components/configure_cases/connectors.tsx | 2 +- .../connectors_dropdown.test.tsx | 17 +- .../configure_cases/field_mapping.test.tsx | 10 +- .../configure_cases/field_mapping.tsx | 2 +- .../field_mapping_row.test.tsx | 20 +- .../components/configure_cases/index.test.tsx | 5 +- .../components/configure_cases/index.tsx | 10 +- .../configure_cases/mapping.test.tsx | 113 +- .../cases/components/configure_cases/utils.ts | 4 +- .../cases/components/create/index.test.tsx | 15 +- .../public/cases/components/create/index.tsx | 6 +- .../components/edit_connector/index.test.tsx | 36 +- .../cases/components/edit_connector/index.tsx | 2 +- .../cases/components/filter_popover/index.tsx | 2 +- .../cases/components/tag_list/index.test.tsx | 82 +- .../cases/components/tag_list/index.tsx | 6 +- .../user_action_tree/helpers.test.tsx | 68 +- .../components/user_action_tree/helpers.tsx | 4 +- .../user_action_tree/index.test.tsx | 33 +- .../components/user_action_tree/index.tsx | 4 +- .../user_action_markdown.test.tsx | 15 +- .../user_action_title.test.tsx | 5 +- .../siem/public/cases/containers/api.ts | 2 +- .../cases/containers/use_bulk_update_case.tsx | 2 +- .../cases/containers/use_delete_cases.tsx | 2 +- .../containers/use_get_action_license.tsx | 2 +- .../containers/use_get_case_user_actions.tsx | 6 +- .../public/cases/containers/use_get_cases.tsx | 8 +- .../cases/containers/use_get_reporters.tsx | 6 +- .../containers/use_post_push_to_service.tsx | 5 +- .../cases/containers/use_update_comment.tsx | 4 +- .../siem/public/cases/containers/utils.ts | 2 +- .../alerts_viewer/histogram_configs.ts | 2 +- .../components/autocomplete_field/index.tsx | 14 +- .../autocomplete_field/suggestion_item.tsx | 20 +- .../components/charts/areachart.test.tsx | 64 +- .../common/components/charts/areachart.tsx | 2 +- .../components/charts/barchart.test.tsx | 71 +- .../common/components/charts/barchart.tsx | 2 +- .../charts/chart_place_holder.test.tsx | 18 +- .../common/components/charts/common.test.tsx | 4 +- .../common/components/charts/common.tsx | 4 +- .../charts/draggable_legend.test.tsx | 2 +- .../components/charts/draggable_legend.tsx | 2 +- .../charts/draggable_legend_item.test.tsx | 32 +- .../drag_and_drop/draggable_wrapper.tsx | 2 +- .../draggable_wrapper_hover_content.test.tsx | 123 +- .../drag_and_drop/droppable_wrapper.tsx | 4 +- .../components/draggables/index.test.tsx | 56 +- .../common/components/empty_value/index.tsx | 2 +- .../components/endpoint/link_to_app.test.tsx | 8 +- .../common/components/endpoint/page_view.tsx | 2 +- .../error_toast_dispatcher/index.tsx | 2 +- .../components/event_details/columns.tsx | 6 +- .../event_details/event_details.test.tsx | 8 +- .../event_details/event_details.tsx | 2 +- .../event_fields_browser.test.tsx | 44 +- .../event_details/event_fields_browser.tsx | 2 +- .../components/event_details/helpers.tsx | 2 +- .../event_details/stateful_event_details.tsx | 2 +- .../events_viewer/events_viewer.test.tsx | 36 +- .../events_viewer/events_viewer.tsx | 13 +- .../components/events_viewer/index.test.tsx | 7 +- .../common/components/events_viewer/index.tsx | 4 +- .../external_link_icon/index.test.tsx | 27 +- .../components/formatted_date/index.tsx | 8 +- .../formatted_date/maybe_date.test.ts | 18 +- .../header_page/editable_title.test.tsx | 50 +- .../components/header_page/index.test.tsx | 58 +- .../common/components/header_page/index.tsx | 14 +- .../components/header_page/title.test.tsx | 21 +- .../components/header_section/index.test.tsx | 39 +- .../import_data_modal/index.test.tsx | 2 +- .../components/import_data_modal/index.tsx | 2 +- .../common/components/inspect/index.test.tsx | 83 +- .../common/components/inspect/index.tsx | 2 +- .../common/components/inspect/modal.test.tsx | 74 +- .../common/components/inspect/modal.tsx | 4 +- .../components/link_icon/index.test.tsx | 28 +- .../common/components/link_icon/index.tsx | 22 +- .../public/common/components/links/index.tsx | 4 +- .../localized_date_tooltip/index.tsx | 5 +- .../common/components/markdown/index.test.tsx | 86 +- .../markdown/markdown_hint.test.tsx | 7 +- .../components/matrix_histogram/index.tsx | 7 +- .../ml/anomaly/use_anomalies_table_data.ts | 2 +- .../ml/influencers/create_influencers.tsx | 4 +- .../get_host_name_from_influencers.ts | 2 +- .../get_network_from_influencers.ts | 2 +- .../ml/score/anomaly_score.test.tsx | 5 +- .../ml/score/anomaly_scores.test.tsx | 5 +- .../ml/score/score_interval_to_datetime.ts | 16 +- .../get_anomalies_host_table_columns.test.tsx | 11 +- .../get_anomalies_host_table_columns.tsx | 8 +- ...t_anomalies_network_table_columns.test.tsx | 8 +- .../get_anomalies_network_table_columns.tsx | 8 +- .../common/components/ml_popover/api.tsx | 2 +- .../common/components/ml_popover/helpers.tsx | 8 +- .../hooks/use_siem_jobs_helpers.tsx | 16 +- .../filters/groups_filter_popover.test.tsx | 17 +- .../filters/groups_filter_popover.tsx | 6 +- .../filters/jobs_table_filters.test.tsx | 30 +- .../ml_popover/jobs_table/job_switch.tsx | 2 +- .../ml_popover/jobs_table/jobs_table.test.tsx | 16 +- .../ml_popover/jobs_table/jobs_table.tsx | 2 +- .../components/ml_popover/ml_popover.test.tsx | 5 +- .../components/ml_popover/ml_popover.tsx | 7 +- .../common/components/navigation/index.tsx | 8 +- .../navigation/tab_navigation/index.tsx | 4 +- .../common/components/news_feed/helpers.ts | 2 +- .../public/common/components/page/index.tsx | 8 +- .../components/paginated_table/index.mock.tsx | 2 +- .../components/paginated_table/index.test.tsx | 85 +- .../common/components/search_bar/index.tsx | 4 +- .../common/components/search_bar/selectors.ts | 5 +- .../components/stat_items/index.test.tsx | 4 +- .../common/components/stat_items/index.tsx | 14 +- .../super_date_picker/index.test.tsx | 55 +- .../components/super_date_picker/index.tsx | 4 +- .../components/super_date_picker/selectors.ts | 20 +- .../common/components/tables/helpers.test.tsx | 36 +- .../common/components/tables/helpers.tsx | 4 +- .../common/components/toasters/index.test.tsx | 14 +- .../common/components/toasters/index.tsx | 2 +- .../common/components/top_n/index.test.tsx | 85 +- .../common/components/top_n/top_n.test.tsx | 19 +- .../components/url_state/index.test.tsx | 10 +- .../common/components/url_state/index.tsx | 2 +- .../url_state/index_mocked.test.tsx | 10 +- .../url_state/initialize_redux_by_url.tsx | 2 +- .../components/url_state/test_dependencies.ts | 2 +- .../common/components/utility_bar/styles.tsx | 6 +- .../utility_bar/utility_bar_action.test.tsx | 7 +- .../common/components/wrapper_page/index.tsx | 2 +- .../histogram_configs.ts | 2 +- .../anomalies_query_tab_body/utils.ts | 6 +- .../events/last_event_time/index.ts | 4 +- .../containers/matrix_histogram/index.ts | 4 +- .../public/common/containers/source/index.tsx | 8 +- ..._navigate_by_router_event_handler.test.tsx | 4 +- .../use_navigate_by_router_event_handler.ts | 2 +- .../use_navigate_to_app_event_handler.ts | 2 +- .../common/hooks/use_add_to_timeline.tsx | 2 +- .../components/connector_flyout/index.tsx | 2 +- .../common/lib/connectors/jira/flyout.tsx | 6 +- .../lib/connectors/servicenow/flyout.tsx | 4 +- .../public/common/lib/connectors/utils.ts | 2 +- .../siem/public/common/lib/helpers/index.tsx | 4 +- .../public/common/lib/helpers/scheduler.ts | 5 +- .../siem/public/common/lib/keury/index.ts | 7 +- .../mock/endpoint/app_context_render.tsx | 8 +- .../siem/public/common/mock/match_media.ts | 2 +- .../public/common/mock/timeline_results.ts | 2 +- .../siem/public/common/store/app/reducer.ts | 2 +- .../siem/public/common/store/app/selectors.ts | 2 +- .../common/store/drag_and_drop/selectors.ts | 2 +- .../plugins/siem/public/common/store/index.ts | 2 +- .../public/common/store/inputs/helpers.ts | 6 +- .../public/common/store/inputs/reducer.ts | 4 +- .../public/common/store/inputs/selectors.ts | 33 +- .../siem/public/common/store/test_utils.ts | 8 +- .../common/utils/kql/use_update_kql.test.tsx | 2 +- .../siem/public/endpoint_alerts/index.ts | 2 +- .../store/alert_details.test.ts | 6 +- .../endpoint_alerts/store/alert_list.test.ts | 6 +- .../store/alert_list_pagination.test.ts | 2 +- .../endpoint_alerts/store/middleware.ts | 2 +- .../public/endpoint_alerts/store/selectors.ts | 4 +- .../public/endpoint_alerts/view/index.tsx | 6 +- .../endpoint_alerts/view/index_search_bar.tsx | 2 +- .../siem/public/endpoint_hosts/index.ts | 2 +- .../store/host_pagination.test.ts | 2 +- .../public/endpoint_hosts/store/middleware.ts | 8 +- .../public/endpoint_hosts/store/selectors.ts | 14 +- .../details/components/flyout_sub_header.tsx | 8 +- .../view/details/policy_response.tsx | 18 +- .../siem/public/endpoint_hosts/view/hooks.ts | 2 +- .../public/endpoint_hosts/view/index.test.tsx | 16 +- .../siem/public/endpoint_policy/details.ts | 2 +- .../siem/public/endpoint_policy/list.ts | 2 +- .../store/policy_details/middleware.ts | 4 +- .../store/policy_details/selectors.ts | 12 +- .../store/policy_list/middleware.ts | 8 +- .../store/policy_list/selectors.ts | 2 +- .../endpoint_policy/view/agents_summary.tsx | 2 +- .../view/policy_details.test.tsx | 2 +- .../view/policy_forms/events/checkbox.tsx | 2 +- .../view/policy_forms/events/linux.tsx | 2 +- .../view/policy_forms/events/mac.tsx | 2 +- .../view/policy_forms/events/windows.tsx | 2 +- .../view/policy_forms/protections/malware.tsx | 6 +- .../endpoint_policy/view/vertical_divider.ts | 6 +- .../authentications_table/index.test.tsx | 8 +- .../authentications_table/index.tsx | 14 +- .../components/first_last_seen_host/index.tsx | 2 +- .../hosts/components/hosts_table/columns.tsx | 8 +- .../components/hosts_table/index.test.tsx | 30 +- .../hosts/components/hosts_table/index.tsx | 4 +- .../uncommon_process_table/index.test.tsx | 84 +- .../uncommon_process_table/index.tsx | 12 +- .../containers/hosts/first_last_seen/index.ts | 4 +- .../siem/public/hosts/pages/hosts.test.tsx | 4 +- .../authentications_query_tab_body.tsx | 2 +- .../navigation/events_query_tab_body.tsx | 2 +- .../siem/public/hosts/store/reducer.ts | 4 +- .../siem/public/hosts/store/selectors.ts | 10 +- .../network/components/arrows/index.test.tsx | 7 +- .../network/components/arrows/index.tsx | 2 +- .../embeddables/embeddable_header.test.tsx | 25 +- .../embeddables/embedded_map_helpers.tsx | 4 +- .../embeddables/map_tool_tip/map_tool_tip.tsx | 2 +- .../map_tool_tip/point_tool_tip_content.tsx | 4 +- .../map_tool_tip/tooltip_footer.test.tsx | 96 +- .../flow_controls/flow_target_select.test.tsx | 15 +- .../flow_controls/flow_target_select.tsx | 2 +- .../network/components/ip/index.test.tsx | 14 +- .../components/network_dns_table/columns.tsx | 10 +- .../network_dns_table/index.test.tsx | 12 +- .../components/network_dns_table/index.tsx | 4 +- .../is_ptr_included.test.tsx | 5 +- .../components/network_http_table/columns.tsx | 4 +- .../network_http_table/index.test.tsx | 12 +- .../components/network_http_table/index.tsx | 4 +- .../network_top_countries_table/columns.tsx | 10 +- .../index.test.tsx | 30 +- .../network_top_countries_table/index.tsx | 4 +- .../network_top_n_flow_table/columns.tsx | 8 +- .../network_top_n_flow_table/index.test.tsx | 30 +- .../network_top_n_flow_table/index.tsx | 5 +- .../network/components/port/index.test.tsx | 19 +- .../source_destination/country_flag.tsx | 2 +- .../source_destination/geo_fields.tsx | 6 +- .../source_destination/index.test.tsx | 204 +-- .../components/source_destination/network.tsx | 12 +- .../source_destination_ip.test.tsx | 109 +- .../source_destination_ip.tsx | 14 +- .../network/components/tls_table/columns.tsx | 4 +- .../components/tls_table/index.test.tsx | 14 +- .../network/components/tls_table/index.tsx | 4 +- .../components/users_table/columns.tsx | 10 +- .../components/users_table/index.test.tsx | 14 +- .../network/components/users_table/index.tsx | 4 +- .../network/pages/ip_details/index.test.tsx | 2 +- .../pages/navigation/dns_query_tab_body.tsx | 2 +- .../public/network/pages/network.test.tsx | 6 +- .../siem/public/network/store/reducer.ts | 4 +- .../siem/public/network/store/selectors.ts | 13 +- .../alerts_by_category/index.test.tsx | 2 +- .../components/alerts_by_category/index.tsx | 2 +- .../components/event_counts/index.test.tsx | 6 +- .../components/events_by_dataset/index.tsx | 3 +- .../components/host_overview/index.tsx | 2 +- .../components/overview_host/index.test.tsx | 25 +- .../overview_host_stats/index.test.tsx | 10 +- .../components/overview_host_stats/index.tsx | 4 +- .../overview_network/index.test.tsx | 25 +- .../overview_network_stats/index.test.tsx | 10 +- .../overview_network_stats/index.tsx | 4 +- .../components/recent_cases/filters/index.tsx | 2 +- .../recent_timelines/filters/index.tsx | 2 +- .../recent_timelines/recent_timelines.tsx | 2 +- .../components/signals_by_category/index.tsx | 2 +- .../public/overview/pages/overview.test.tsx | 4 +- .../resolver/store/camera/panning.test.ts | 2 +- .../public/resolver/store/camera/selectors.ts | 18 +- .../public/resolver/store/data/selectors.ts | 4 +- .../siem/public/resolver/store/middleware.ts | 6 +- .../siem/public/resolver/store/selectors.ts | 2 +- .../public/resolver/view/graph_controls.tsx | 2 +- .../siem/public/resolver/view/panel.tsx | 4 +- .../resolver/view/process_event_dot.tsx | 2 +- .../resolver/view/side_effect_simulator.ts | 4 +- .../siem/public/resolver/view/submenu.tsx | 4 +- .../siem/public/resolver/view/use_camera.ts | 2 +- .../certificate_fingerprint/index.test.tsx | 23 +- .../components/duration/index.test.tsx | 7 +- .../components/edit_data_provider/helpers.tsx | 6 +- .../edit_data_provider/index.test.tsx | 92 +- .../field_renderers/field_renderers.test.tsx | 10 +- .../field_renderers/field_renderers.tsx | 2 +- .../fields_browser/categories_pane.test.tsx | 18 +- .../fields_browser/categories_pane.tsx | 2 +- .../fields_browser/category.test.tsx | 23 +- .../fields_browser/category_columns.test.tsx | 14 +- .../fields_browser/category_title.test.tsx | 27 +- .../fields_browser/field_browser.test.tsx | 6 +- .../fields_browser/field_items.test.tsx | 48 +- .../components/fields_browser/field_items.tsx | 8 +- .../fields_browser/field_name.test.tsx | 12 +- .../fields_browser/fields_pane.test.tsx | 36 +- .../components/fields_browser/fields_pane.tsx | 2 +- .../components/fields_browser/header.test.tsx | 74 +- .../components/fields_browser/helpers.tsx | 6 +- .../components/fields_browser/index.test.tsx | 48 +- .../components/flyout/button/index.test.tsx | 10 +- .../header_with_close_button/index.test.tsx | 5 +- .../components/flyout/index.test.tsx | 45 +- .../components/flyout/pane/index.test.tsx | 7 +- .../flyout/pane/timeline_resize_handle.tsx | 2 +- .../components/formatted_ip/index.tsx | 2 +- .../components/ja3_fingerprint/index.test.tsx | 25 +- .../components/netflow/fingerprints/index.tsx | 6 +- .../components/netflow/index.test.tsx | 241 +-- .../duration_event_start_end.tsx | 6 +- .../netflow/netflow_columns/user_process.tsx | 4 +- .../components/notes/add_note/index.test.tsx | 37 +- .../notes/add_note/new_note.test.tsx | 35 +- .../components/notes/add_note/new_note.tsx | 2 +- .../notes/note_card/note_card_body.test.tsx | 7 +- .../notes/note_card/note_card_header.test.tsx | 21 +- .../notes/note_card/note_created.test.tsx | 7 +- .../components/notes/note_cards/index.tsx | 2 +- .../delete_timeline_modal.test.tsx | 62 +- .../delete_timeline_modal/index.test.tsx | 21 +- .../export_timeline/export_timeline.tsx | 2 +- .../components/open_timeline/helpers.test.ts | 6 +- .../components/open_timeline/helpers.ts | 4 +- .../components/open_timeline/index.test.tsx | 133 +- .../note_previews/index.test.tsx | 29 +- .../open_timeline/note_previews/index.tsx | 2 +- .../note_previews/note_preview.test.tsx | 91 +- .../note_previews/note_preview.tsx | 4 +- .../open_timeline/open_timeline.test.tsx | 73 +- .../open_timeline_modal_body.test.tsx | 21 +- .../open_timeline_modal_body.tsx | 2 +- .../open_timeline_modal_button.test.tsx | 14 +- .../open_timeline/search_row/index.test.tsx | 24 +- .../open_timeline/search_row/index.tsx | 4 +- .../timelines_table/actions_columns.test.tsx | 17 +- .../timelines_table/actions_columns.tsx | 2 +- .../timelines_table/common_columns.test.tsx | 99 +- .../timelines_table/extended_columns.test.tsx | 23 +- .../timelines_table/index.test.tsx | 84 +- .../open_timeline/title_row/index.test.tsx | 26 +- .../timeline/body/actions/index.test.tsx | 15 +- .../body/column_headers/column_header.tsx | 2 +- .../body/column_headers/filter/index.test.tsx | 9 +- .../body/column_headers/header/index.test.tsx | 43 +- .../header_tooltip_content/index.test.tsx | 39 +- .../timeline/body/column_headers/helpers.ts | 2 +- .../body/column_headers/index.test.tsx | 16 +- .../range_picker/index.test.tsx | 2 +- .../column_headers/range_picker/index.tsx | 2 +- .../body/column_headers/text_filter/index.tsx | 2 +- .../body/data_driven_columns/index.test.tsx | 2 +- .../body/data_driven_columns/index.tsx | 4 +- .../body/events/event_column_view.tsx | 2 +- .../components/timeline/body/helpers.ts | 2 +- .../components/timeline/body/index.test.tsx | 34 +- .../body/mini_map/date_ranges.test.ts | 10 +- .../timeline/body/mini_map/date_ranges.ts | 8 +- .../renderers/auditd/generic_row_renderer.tsx | 4 +- .../body/renderers/bytes/index.test.tsx | 7 +- .../renderers/empty_column_renderer.test.tsx | 6 +- .../body/renderers/empty_column_renderer.tsx | 2 +- .../body/renderers/formatted_field.tsx | 2 +- .../body/renderers/get_column_renderer.ts | 2 +- .../body/renderers/get_row_renderer.ts | 2 +- .../timeline/body/renderers/helpers.test.tsx | 8 +- .../timeline/body/renderers/helpers.tsx | 4 +- .../netflow/netflow_row_renderer.test.tsx | 7 +- .../netflow/netflow_row_renderer.tsx | 2 +- .../renderers/plain_column_renderer.test.tsx | 36 +- .../body/renderers/plain_column_renderer.tsx | 4 +- .../body/renderers/plain_row_renderer.tsx | 2 +- .../body/renderers/suricata/suricata_refs.tsx | 2 +- .../suricata/suricata_row_renderer.tsx | 2 +- .../suricata/suricata_signature.test.tsx | 5 +- .../renderers/suricata/suricata_signature.tsx | 7 +- .../system/generic_file_details.test.tsx | 2 +- .../renderers/system/generic_row_renderer.tsx | 14 +- .../unknown_column_renderer.test.tsx | 6 +- .../body/renderers/zeek/zeek_details.test.tsx | 7 +- .../body/renderers/zeek/zeek_row_renderer.tsx | 2 +- .../renderers/zeek/zeek_signature.test.tsx | 32 +- .../body/sort/sort_indicator.test.tsx | 9 +- .../timeline/body/stateful_body.test.tsx | 2 +- .../timeline/body/stateful_body.tsx | 12 +- .../data_providers/data_providers.test.tsx | 4 +- .../timeline/data_providers/empty.test.tsx | 2 +- .../timeline/data_providers/empty.tsx | 6 +- .../timeline/data_providers/helpers.test.tsx | 20 +- .../timeline/data_providers/helpers.tsx | 6 +- .../timeline/data_providers/index.tsx | 4 +- .../mock/mock_data_providers.tsx | 2 +- .../data_providers/providers.test.tsx | 34 +- .../timeline/data_providers/providers.tsx | 2 +- .../components/timeline/footer/index.test.tsx | 30 +- .../components/timeline/footer/index.tsx | 7 +- .../timelines/components/timeline/index.tsx | 4 +- .../timeline/properties/helpers.tsx | 4 +- .../timeline/properties/index.test.tsx | 7 +- .../timeline/properties/properties_right.tsx | 2 +- .../components/timeline/query_bar/index.tsx | 4 +- .../timeline/selectable_timeline/index.tsx | 6 +- .../components/timeline/timeline.test.tsx | 17 +- .../components/timeline/timeline.tsx | 2 +- .../public/timelines/containers/all/index.tsx | 4 +- .../siem/public/timelines/pages/index.tsx | 2 +- .../public/timelines/store/timeline/epic.ts | 2 +- .../timelines/store/timeline/epic_favorite.ts | 6 +- .../timelines/store/timeline/epic_note.ts | 8 +- .../store/timeline/epic_pinned_event.ts | 6 +- .../timelines/store/timeline/helpers.ts | 48 +- .../timelines/store/timeline/reducer.test.ts | 26 +- .../timelines/store/timeline/reducer.ts | 2 +- .../timelines/store/timeline/selectors.ts | 18 +- .../scripts/convert_saved_search_to_rules.js | 8 +- .../extract_tactics_techniques_mitre.js | 20 +- .../siem/scripts/loop_cypress_tests.js | 18 +- .../plugins/siem/scripts/optimize_tsconfig.js | 2 +- .../scripts/optimize_tsconfig/optimize.js | 2 +- .../siem/scripts/unoptimize_tsconfig.js | 2 +- .../endpoint/alerts/handlers/details/index.ts | 2 +- .../endpoint/alerts/handlers/list/index.ts | 2 +- .../server/endpoint/routes/metadata/index.ts | 6 +- .../routes/metadata/query_builders.ts | 2 +- .../server/endpoint/routes/policy/handlers.ts | 2 +- .../endpoint/routes/resolver/utils/fetch.ts | 2 +- .../routes/resolver/utils/pagination.ts | 2 +- .../endpoint/routes/resolver/utils/tree.ts | 8 +- .../siem/server/graphql/ecs/resolvers.ts | 4 +- .../siem/server/graphql/hosts/resolvers.ts | 2 +- .../scalar_to_boolean_array/resolvers.ts | 4 +- .../graphql/scalar_to_date_array/resolvers.ts | 4 +- .../scalar_to_number_array/resolvers.ts | 4 +- .../authentications/elasticsearch_adapter.ts | 2 +- .../detection_engine/notifications/types.ts | 2 +- .../routes/__mocks__/request_responses.ts | 8 +- .../routes/__mocks__/server.ts | 2 +- .../routes/__mocks__/utils.ts | 4 +- .../routes/rules/create_rules_bulk_route.ts | 6 +- .../routes/rules/delete_rules_bulk_route.ts | 4 +- .../routes/rules/delete_rules_route.ts | 2 +- .../routes/rules/find_rules_route.ts | 4 +- .../routes/rules/find_rules_status_route.ts | 2 +- .../routes/rules/import_rules_route.test.ts | 2 +- .../routes/rules/import_rules_route.ts | 6 +- .../routes/rules/patch_rules_bulk_route.ts | 2 +- .../routes/rules/update_rules_bulk_route.ts | 2 +- .../detection_engine/routes/rules/utils.ts | 10 +- .../schemas/add_prepackaged_rules_schema.ts | 5 +- .../routes/schemas/schemas.ts | 52 +- .../detection_engine/rule_actions/types.ts | 2 +- .../rules/get_export_by_object_ids.ts | 10 +- .../rules/get_prepackaged_rules.test.ts | 2 +- .../rules/get_prepackaged_rules.ts | 2 +- .../rules/get_rules_to_install.ts | 2 +- .../rules/get_rules_to_update.ts | 4 +- .../lib/detection_engine/rules/types.ts | 4 +- .../rules/update_prepacked_rules.ts | 2 +- .../signals/build_exceptions_query.ts | 4 +- .../detection_engine/signals/build_signal.ts | 2 +- .../signals/bulk_create_ml_signals.ts | 6 +- .../detection_engine/signals/get_filter.ts | 2 +- .../rule_status_saved_objects_client.ts | 6 +- .../signals/rule_status_service.test.ts | 2 +- .../signals/rule_status_service.ts | 2 +- .../signals/search_after_bulk_create.test.ts | 10 +- .../signals/signal_rule_alert_type.ts | 2 +- .../signals/single_bulk_create.ts | 6 +- .../detection_engine/signals/utils.test.ts | 56 +- .../lib/detection_engine/signals/utils.ts | 5 +- .../lib/detection_engine/tags/read_tags.ts | 2 +- .../lib/events/elasticsearch_adapter.ts | 2 +- .../server/lib/hosts/elasticsearch_adapter.ts | 4 +- .../server/lib/hosts/query.detail_host.dsl.ts | 2 +- .../lib/index_fields/elasticsearch_adapter.ts | 6 +- .../siem/server/lib/machine_learning/index.ts | 2 +- .../lib/network/elasticsearch_adapter.ts | 2 +- .../siem/server/lib/note/saved_object.ts | 14 +- .../server/lib/pinned_event/saved_object.ts | 12 +- .../source_status/elasticsearch_adapter.ts | 2 +- .../convert_saved_object_to_savedtimeline.ts | 4 +- .../timeline/routes/import_timelines_route.ts | 6 +- .../routes/schemas/import_timelines_schema.ts | 4 +- .../timeline/routes/utils/create_timelines.ts | 6 +- .../timeline/routes/utils/export_timelines.ts | 20 +- .../siem/server/lib/timeline/saved_object.ts | 20 +- .../elasticsearch_adapter.ts | 4 +- x-pack/plugins/siem/server/saved_objects.ts | 4 +- .../siem/server/utils/beat_schema/index.ts | 2 +- .../utils/build_query/create_options.ts | 8 +- .../build_validation/route_validation.test.ts | 4 +- .../build_validation/route_validation.ts | 2 +- .../read_stream/create_stream_from_ndjson.ts | 4 +- .../helpers/home.helpers.ts | 10 +- .../__jest__/client_integration/home.test.ts | 23 +- .../client_integration/repository_add.test.ts | 4 +- .../common/lib/snapshot_serialization.ts | 2 +- .../common/lib/time_serialization.test.ts | 2 +- .../common/lib/time_serialization.ts | 2 +- .../public/application/app.tsx | 2 +- .../components/collapsible_indices_list.tsx | 2 +- .../components/policy_delete_provider.tsx | 2 +- .../policy_form/steps/step_logistics.tsx | 8 +- .../policy_form/steps/step_retention.tsx | 8 +- .../policy_form/steps/step_settings.tsx | 14 +- .../components/repository_delete_provider.tsx | 2 +- .../components/repository_form/step_one.tsx | 4 +- .../type_settings/azure_settings.tsx | 20 +- .../type_settings/fs_settings.tsx | 12 +- .../type_settings/gcs_settings.tsx | 16 +- .../type_settings/hdfs_settings.tsx | 18 +- .../type_settings/readonly_settings.tsx | 4 +- .../type_settings/s3_settings.tsx | 28 +- .../steps/step_logistics.tsx | 18 +- .../steps/step_review.tsx | 2 +- .../steps/step_settings.tsx | 8 +- .../retention_update_modal_provider.tsx | 2 +- .../public/application/constants/index.ts | 4 +- .../public/application/sections/home/home.tsx | 2 +- .../policy_details/policy_details.tsx | 6 +- .../sections/home/policy_list/policy_list.tsx | 2 +- .../policy_retention_schedule.tsx | 4 +- .../policy_list/policy_table/policy_table.tsx | 10 +- .../repository_details/repository_details.tsx | 2 +- .../type_details/hdfs_details.tsx | 2 +- .../repository_table/repository_table.tsx | 10 +- .../home/restore_list/restore_list.tsx | 4 +- .../restore_table/restore_table.tsx | 4 +- .../snapshot_details/snapshot_details.tsx | 4 +- .../home/snapshot_list/snapshot_list.tsx | 2 +- .../snapshot_table/snapshot_table.tsx | 8 +- .../services/http/policy_requests.ts | 2 +- .../services/http/repository_requests.ts | 2 +- .../services/validation/validate_restore.ts | 4 +- .../plugins/snapshot_restore/public/plugin.ts | 2 +- .../snapshot_restore/server/routes/api/app.ts | 2 +- .../server/routes/api/policy.test.ts | 2 +- .../server/routes/api/policy.ts | 4 +- .../server/routes/api/repositories.test.ts | 6 +- .../server/routes/api/repositories.ts | 16 +- .../server/routes/api/restore.ts | 6 +- .../server/routes/api/snapshots.ts | 4 +- .../server/services/license.ts | 2 +- x-pack/plugins/spaces/common/lib/dataurl.ts | 2 +- .../common/licensing/license_service.test.ts | 2 +- .../common/licensing/license_service.ts | 2 +- .../advanced_settings_subtitle.tsx | 2 +- .../advanced_settings_title.tsx | 2 +- .../components/copy_status_indicator.tsx | 2 +- .../components/copy_to_space_flyout.tsx | 8 +- .../copy_to_space_flyout_footer.tsx | 6 +- .../components/copy_to_space_form.tsx | 4 +- .../components/processing_copy_to_space.tsx | 6 +- .../components/selectable_spaces_control.tsx | 8 +- .../components/space_result.tsx | 2 +- .../components/space_result_details.tsx | 6 +- .../summarize_copy_result.ts | 26 +- .../confirm_delete_modal.tsx | 2 +- .../confirm_alter_active_space_modal.tsx | 2 +- .../customize_space_avatar.tsx | 2 +- .../customize_space/space_identifier.tsx | 2 +- .../enabled_features.test.tsx | 20 +- .../enabled_features/feature_table.tsx | 6 +- .../enabled_features/toggle_all_features.tsx | 2 +- .../edit_space/manage_space_page.test.tsx | 5 +- .../edit_space/manage_space_page.tsx | 4 +- .../public/management/lib/feature_utils.ts | 2 +- .../management/management_service.test.ts | 6 +- .../spaces_grid/spaces_grid_page.tsx | 4 +- .../nav_control/components/spaces_menu.tsx | 2 +- .../nav_control/nav_control_popover.tsx | 2 +- .../public/space_avatar/space_attributes.ts | 2 +- .../public/space_selector/space_selector.tsx | 4 +- .../capabilities/capabilities_switcher.ts | 10 +- .../default_space/default_space_service.ts | 2 +- .../lib/copy_to_spaces/copy_to_spaces.test.ts | 12 +- .../lib/create_empty_failure_response.ts | 2 +- .../copy_to_spaces/lib/get_eligible_types.ts | 4 +- .../lib/read_stream_to_completion.ts | 2 +- .../lib/readable_stream_from_array.ts | 2 +- .../resolve_copy_conflicts.test.ts | 12 +- .../copy_to_spaces/resolve_copy_conflicts.ts | 2 +- .../on_post_auth_interceptor.test.ts | 9 +- .../on_post_auth_interceptor.ts | 6 +- .../on_request_interceptor.ts | 2 +- .../spaces/server/lib/space_schema.test.ts | 2 +- .../plugins/spaces/server/lib/space_schema.ts | 6 +- .../lib/spaces_client/spaces_client.test.ts | 6 +- .../server/lib/spaces_client/spaces_client.ts | 8 +- .../spaces/server/lib/utils/url.test.ts | 8 +- .../__fixtures__/create_mock_so_repository.ts | 6 +- .../__fixtures__/create_mock_so_service.ts | 8 +- .../routes/api/external/copy_to_space.test.ts | 2 +- .../routes/api/external/copy_to_space.ts | 10 +- .../server/routes/api/external/get.test.ts | 4 +- .../routes/api/external/get_all.test.ts | 2 +- .../routes/api/external/share_add_spaces.ts | 4 +- .../api/external/share_remove_spaces.ts | 4 +- .../saved_objects/migrations/migrate_6x.ts | 2 +- .../spaces_saved_objects_client.test.ts | 2 +- .../spaces_saved_objects_client.ts | 4 +- .../server/spaces_service/spaces_service.ts | 2 +- .../spaces_usage_collector.ts | 4 +- x-pack/plugins/task_manager/server/config.ts | 2 +- .../server/lib/middleware.test.ts | 2 +- .../task_manager/server/lib/result_type.ts | 6 +- x-pack/plugins/task_manager/server/plugin.ts | 20 +- .../mark_available_tasks_as_claimed.ts | 2 +- .../server/queries/query_clauses.ts | 2 +- .../server/saved_objects/migrations.ts | 2 +- x-pack/plugins/task_manager/server/task.ts | 4 +- .../task_manager/server/task_manager.test.ts | 12 +- .../task_manager/server/task_manager.ts | 10 +- .../task_manager/server/task_poller.test.ts | 18 +- .../task_manager/server/task_poller.ts | 4 +- .../task_manager/server/task_pool.test.ts | 5 +- .../plugins/task_manager/server/task_pool.ts | 16 +- .../task_manager/server/task_runner.test.ts | 10 +- .../task_manager/server/task_store.test.ts | 12 +- .../plugins/task_manager/server/task_store.ts | 14 +- .../task_manager/server/test_utils/index.ts | 4 +- .../get_stats_with_xpack.ts | 4 +- .../plugins/transform/common/types/common.ts | 2 +- .../transform/public/app/common/fields.ts | 8 +- .../transform/public/app/common/request.ts | 4 +- .../transform/public/app/common/transform.ts | 6 +- .../public/app/hooks/use_delete_transform.tsx | 2 +- .../public/app/hooks/use_get_transforms.ts | 2 +- .../public/app/hooks/use_index_data.test.tsx | 4 +- .../public/app/hooks/use_index_data.ts | 6 +- .../public/app/hooks/use_pivot_data.ts | 10 +- .../app/hooks/use_search_items/common.ts | 8 +- .../public/app/hooks/use_start_transform.ts | 2 +- .../public/app/hooks/use_stop_transform.ts | 2 +- .../components/with_privileges.tsx | 2 +- .../components/aggregation_list/list_form.tsx | 4 +- .../aggregation_list/popover_form.tsx | 16 +- .../components/group_by_list/list_form.tsx | 4 +- .../components/group_by_list/popover_form.tsx | 20 +- .../get_agg_name_conflict_toast_messages.ts | 2 +- .../common/get_pivot_dropdown_options.ts | 8 +- .../step_define/hooks/use_pivot_config.ts | 8 +- .../step_define/step_define_form.test.tsx | 2 +- .../step_define/step_define_form.tsx | 6 +- .../step_define/step_define_summary.test.tsx | 2 +- .../step_details/step_details_form.tsx | 26 +- .../edit_transform_flyout_form.tsx | 6 +- .../edit_transform_flyout_form_text_input.tsx | 2 +- .../use_edit_transform_flyout.ts | 6 +- .../components/stats_bar/stats_bar.tsx | 2 +- .../transform_list/expanded_row.tsx | 2 +- .../expanded_row_details_pane.tsx | 8 +- .../transform_list/transform_list.tsx | 26 +- .../transform_list/transforms_stats_bar.tsx | 2 +- x-pack/plugins/transform/public/plugin.ts | 2 +- .../transform/server/routes/api/privileges.ts | 2 +- .../transform/server/routes/api/transforms.ts | 2 +- .../transform/server/services/license.ts | 2 +- .../application/action_type_registry.mock.ts | 2 +- .../email/email_connector.test.tsx | 9 +- .../email/email_connector.tsx | 12 +- .../email/email_params.test.tsx | 5 +- .../email/email_params.tsx | 16 +- .../es_index/es_index_connector.test.tsx | 5 +- .../es_index/es_index_connector.tsx | 8 +- .../es_index/es_index_params.test.tsx | 7 +- .../pagerduty/pagerduty_connectors.test.tsx | 9 +- .../pagerduty/pagerduty_params.test.tsx | 9 +- .../pagerduty/pagerduty_params.tsx | 4 +- .../server_log/server_log_params.test.tsx | 10 +- .../server_log/server_log_params.tsx | 4 +- .../slack/slack_connectors.test.tsx | 9 +- .../slack/slack_connectors.tsx | 2 +- .../slack/slack_params.test.tsx | 5 +- .../slack/slack_params.tsx | 2 +- .../webhook/webhook_connectors.test.tsx | 5 +- .../webhook/webhook_connectors.tsx | 18 +- .../webhook/webhook_params.test.tsx | 5 +- .../threshold/expression.tsx | 22 +- .../threshold/visualization.tsx | 4 +- .../application/components/health_check.tsx | 4 +- .../public/application/home.tsx | 2 +- .../application/lib/action_connector_api.ts | 6 +- .../application/lib/action_type_compare.ts | 2 +- .../application/lib/action_variables.ts | 2 +- .../public/application/lib/alert_api.ts | 18 +- .../public/application/lib/capabilities.ts | 2 +- .../lib/check_action_type_enabled.tsx | 2 +- .../application/lib/value_validators.test.ts | 20 +- .../action_connector_form.tsx | 2 +- .../action_connector_form/action_form.tsx | 22 +- .../action_type_menu.tsx | 2 +- .../connector_add_flyout.tsx | 6 +- .../connector_add_modal.tsx | 6 +- .../connector_edit_flyout.test.tsx | 4 +- .../connector_edit_flyout.tsx | 6 +- .../actions_connectors_list.test.tsx | 30 +- .../components/actions_connectors_list.tsx | 8 +- .../components/alert_details_route.tsx | 4 +- .../components/alert_instances.tsx | 6 +- .../components/view_in_app.test.tsx | 6 +- .../alert_details/components/view_in_app.tsx | 4 +- .../sections/alert_form/alert_add.test.tsx | 5 +- .../sections/alert_form/alert_add.tsx | 6 +- .../sections/alert_form/alert_edit.test.tsx | 5 +- .../sections/alert_form/alert_edit.tsx | 4 +- .../sections/alert_form/alert_form.tsx | 28 +- .../components/action_type_filter.tsx | 4 +- .../alerts_list/components/alerts_list.tsx | 16 +- .../alerts_list/components/type_filter.tsx | 2 +- .../components/bulk_operation_popover.tsx | 2 +- .../with_bulk_alert_api_operations.tsx | 15 +- .../common/expression_items/for_the_last.tsx | 4 +- .../common/expression_items/group_by_over.tsx | 6 +- .../public/common/expression_items/of.tsx | 2 +- .../common/expression_items/threshold.tsx | 4 +- .../public/common/expression_items/when.tsx | 2 +- .../public/common/index_controls/index.ts | 4 +- .../triggers_actions_ui/public/plugin.ts | 2 +- .../get_index_state_from_cluster_state.ts | 2 +- .../application/components/tabs.test.tsx | 4 +- .../components/tabs/checkup/checkup_tab.tsx | 2 +- .../components/tabs/checkup/controls.tsx | 2 +- .../tabs/checkup/deprecations/cell.tsx | 2 +- .../checkup/deprecations/grouped.test.tsx | 19 +- .../tabs/checkup/deprecations/grouped.tsx | 8 +- .../tabs/checkup/deprecations/health.tsx | 6 +- .../tabs/checkup/deprecations/index_table.tsx | 2 +- .../tabs/checkup/deprecations/list.tsx | 6 +- .../checkup/deprecations/reindex/button.tsx | 2 +- .../deprecations/reindex/flyout/progress.tsx | 2 +- .../reindex/flyout/warnings_step.tsx | 2 +- .../reindex/polling_service.test.ts | 6 +- .../components/tabs/checkup/filter_bar.tsx | 2 +- .../components/tabs/checkup/group_by_bar.tsx | 2 +- .../components/tabs/overview/index.tsx | 2 +- .../public/application/utils.ts | 2 +- .../lib/es_deprecation_logging_apis.test.ts | 8 +- .../server/lib/es_indices_state_check.ts | 2 +- .../server/lib/es_migration_apis.ts | 8 +- .../server/lib/es_version_precheck.ts | 6 +- .../lib/reindexing/reindex_actions.test.ts | 19 +- .../server/lib/reindexing/reindex_actions.ts | 6 +- .../server/lib/reindexing/reindex_service.ts | 22 +- .../server/lib/reindexing/worker.ts | 6 +- .../routes/reindex_indices/reindex_indices.ts | 2 +- .../__tests__/cert_status.test.tsx | 4 +- .../__tests__/fingerprint_col.test.tsx | 4 +- .../certificates/fingerprint_col.tsx | 2 +- .../common/charts/annotation_tooltip.tsx | 2 +- .../components/common/charts/donut_chart.tsx | 9 +- .../common/charts/duration_chart.tsx | 6 +- .../common/charts/duration_line_bar_list.tsx | 6 +- .../__tests__/location_status_tags.test.tsx | 60 +- .../location_map/embeddables/map_config.ts | 4 +- .../__test__/monitor_status.bar.test.tsx | 4 +- .../__test__/ssl_certificate.test.tsx | 12 +- .../monitor/ping_list/expanded_row.tsx | 2 +- .../monitor/ping_list/ping_list.tsx | 6 +- .../overview/alerts/add_filter_btn.tsx | 2 +- .../overview/alerts/alert_field_number.tsx | 2 +- .../overview/alerts/alert_monitor_status.tsx | 8 +- .../components/overview/alerts/alert_tls.tsx | 2 +- .../toggle_alert_flyout_button.tsx | 2 +- .../__tests__/down_number_select.test.tsx | 4 +- .../__tests__/time_expression_select.test.tsx | 4 +- .../filters_expression_select.tsx | 2 +- .../time_expression_select.tsx | 4 +- .../settings_message_expression_popover.tsx | 2 +- .../alerts/toggle_alert_flyout_button.tsx | 2 +- .../__tests__/filter_popover.test.tsx | 7 +- .../overview/filter_group/filter_group.tsx | 2 +- .../overview/filter_group/filter_popover.tsx | 8 +- .../overview/kuery_bar/kuery_bar.tsx | 2 +- .../kuery_bar/typeahead/click_outside.js | 4 +- .../overview/kuery_bar/typeahead/index.js | 20 +- .../kuery_bar/typeahead/suggestion.js | 8 +- .../kuery_bar/typeahead/suggestions.js | 4 +- .../overview/monitor_list/monitor_list.tsx | 2 +- .../monitor_list/monitor_list_container.tsx | 2 +- .../monitor_status_list.tsx | 2 +- .../monitor_status_row.tsx | 2 +- .../monitor_list_page_size_select.tsx | 2 +- .../monitor_list_status_column.tsx | 2 +- .../overview/overview_container.tsx | 2 +- .../components/settings/certificate_form.tsx | 2 +- .../uptime/public/hooks/use_filter_update.ts | 2 +- .../uptime/public/hooks/use_url_params.ts | 2 +- .../framework/new_platform_adapter.tsx | 2 +- .../observability_integration/build_href.ts | 2 +- .../lib/helper/series_has_down_values.ts | 2 +- .../public/lib/helper/stringify_kueries.ts | 2 +- .../url_params/get_supported_url_params.ts | 2 +- .../plugins/uptime/public/pages/settings.tsx | 4 +- .../state/api/__tests__/snapshot.test.ts | 4 +- .../uptime/public/state/api/ml_anomaly.ts | 4 +- .../public/state/effects/dynamic_settings.ts | 2 +- .../public/state/effects/fetch_effect.ts | 2 +- .../public/state/reducers/dynamic_settings.ts | 4 +- .../public/state/reducers/index_pattern.ts | 2 +- .../public/state/reducers/ml_anomaly.ts | 2 +- .../public/state/reducers/monitor_status.ts | 4 +- .../uptime/public/state/reducers/ping.ts | 2 +- .../uptime/public/state/reducers/ping_list.ts | 2 +- .../uptime/public/state/selectors/index.ts | 6 +- .../telemetry/kibana_telemetry_adapter.ts | 8 +- .../server/lib/alerts/__tests__/tls.test.ts | 15 +- .../plugins/uptime/server/lib/alerts/tls.ts | 17 +- .../uptime/server/lib/domains/license.ts | 2 +- .../__tests__/get_monitor_status.test.ts | 2 +- .../lib/requests/generate_filter_aggs.ts | 2 +- .../server/lib/requests/get_filter_bar.ts | 4 +- .../lib/requests/get_monitor_duration.ts | 4 +- .../server/lib/requests/get_monitor_status.ts | 2 +- .../server/lib/requests/get_ping_histogram.ts | 2 +- .../search/__tests__/fetch_page.test.ts | 4 +- .../requests/search/enrich_monitor_groups.ts | 2 +- .../server/lib/requests/search/fetch_page.ts | 2 +- .../search/refine_potential_matches.ts | 4 +- .../server/rest_api/monitors/monitor_list.ts | 2 +- .../server/rest_api/uptime_route_wrapper.ts | 2 +- x-pack/plugins/uptime/server/uptime_server.ts | 4 +- .../helpers/setup_environment.ts | 4 +- .../helpers/watch_create_json.helpers.ts | 7 +- .../helpers/watch_create_threshold.helpers.ts | 2 +- .../helpers/watch_edit.helpers.ts | 2 +- .../helpers/watch_status.helpers.ts | 5 +- .../watch_create_json.test.ts | 2 +- .../client_integration/watch_list.test.ts | 8 +- .../client_integration/watch_status.test.ts | 4 +- .../lib/get_moment/__tests__/get_moment.js | 2 +- .../serialization_helpers/build_actions.js | 2 +- .../application/components/form_errors.tsx | 2 +- .../application/models/watch/base_watch.js | 10 +- .../application/models/watch/json_watch.js | 4 +- .../lib/create_action_id/create_action_id.js | 2 +- .../models/watch_status/watch_status.js | 2 +- .../json_watch_edit/json_watch_edit.tsx | 4 +- .../json_watch_edit/json_watch_edit_form.tsx | 2 +- .../json_watch_edit_simulate.tsx | 12 +- .../json_watch_edit_simulate_results.tsx | 4 +- .../action_fields/email_action_fields.tsx | 10 +- .../action_fields/jira_action_fields.tsx | 6 +- .../action_fields/slack_action_fields.tsx | 8 +- .../action_fields/webhook_action_fields.tsx | 18 +- .../threshold_watch_action_accordion.tsx | 2 +- .../threshold_watch_edit.tsx | 46 +- .../watch_visualization.tsx | 2 +- .../sections/watch_edit/watch_edit_actions.ts | 8 +- .../watch_list/components/watch_list.tsx | 4 +- .../parse_es_interval.test.ts | 4 +- .../parse_es_interval/parse_es_interval.ts | 4 +- .../watcher/public/legacy/time_buckets.js | 36 +- .../__tests__/fetch_all_from_scroll.js | 8 +- .../models/action_status/action_status.js | 2 +- .../watcher/server/models/watch/base_watch.js | 4 +- .../server/models/watch/base_watch.test.js | 4 +- .../models/watch_status/watch_status.js | 6 +- x-pack/plugins/watcher/server/plugin.ts | 2 +- .../api/watches/register_delete_route.ts | 4 +- x-pack/tasks/helpers/flags.ts | 4 +- .../test/accessibility/apps/grok_debugger.ts | 2 +- x-pack/test/accessibility/apps/home.ts | 2 +- x-pack/test/accessibility/apps/login_page.ts | 2 +- .../accessibility/apps/search_profiler.ts | 2 +- x-pack/test/accessibility/apps/uptime.ts | 10 +- x-pack/test/accessibility/config.ts | 2 +- .../basic/tests/index.ts | 2 +- .../alerting_api_integration/common/config.ts | 11 +- .../fixtures/plugins/aad/server/plugin.ts | 2 +- .../server/jira_simulation.ts | 8 +- .../server/pagerduty_simulation.ts | 2 +- .../actions_simulators/server/plugin.ts | 2 +- .../server/servicenow_simulation.ts | 6 +- .../actions_simulators_legacy/index.ts | 2 +- .../slack_simulation.ts | 11 +- .../webhook_simulation.ts | 15 +- .../plugins/alerts/server/alert_types.ts | 2 +- .../tests/actions/execute.ts | 2 +- .../security_and_spaces/tests/index.ts | 4 +- .../spaces_only/tests/actions/execute.ts | 2 +- .../tests/actions/type_not_enabled.ts | 11 +- .../index_threshold/create_test_data.ts | 4 +- .../index_threshold/fields_endpoint.ts | 7 +- .../index_threshold/indices_endpoint.ts | 5 +- .../time_series_query_endpoint.ts | 5 +- .../spaces_only/tests/index.ts | 2 +- .../apis/beats/assign_tags_to_beats.js | 2 +- .../apis/beats/create_enrollment_tokens.js | 18 +- .../api_integration/apis/beats/enroll_beat.js | 14 +- .../api_integration/apis/beats/get_beat.js | 2 +- .../test/api_integration/apis/beats/index.js | 2 +- .../api_integration/apis/beats/list_beats.js | 8 +- .../apis/beats/remove_tags_from_beats.js | 2 +- .../api_integration/apis/beats/set_config.js | 2 +- .../api_integration/apis/beats/set_tag.js | 2 +- .../api_integration/apis/beats/update_beat.js | 6 +- .../apis/endpoint/alerts/index.ts | 10 +- .../apis/endpoint/alerts/index_pattern.ts | 2 +- .../api_integration/apis/endpoint/index.ts | 2 +- .../api_integration/apis/endpoint/metadata.ts | 2 +- .../api_integration/apis/endpoint/policy.ts | 2 +- .../api_integration/apis/es/has_privileges.js | 8 +- x-pack/test/api_integration/apis/es/index.js | 2 +- .../apis/es/post_privileges.js | 2 +- .../apis/features/features/features.ts | 7 +- .../apis/features/features/index.ts | 2 +- .../api_integration/apis/features/index.ts | 2 +- .../api_integration/apis/fleet/agents/acks.ts | 2 +- .../apis/fleet/agents/actions.ts | 2 +- .../apis/fleet/agents/checkin.ts | 2 +- .../apis/fleet/agents/enroll.ts | 2 +- .../apis/fleet/agents/events.ts | 2 +- .../apis/fleet/agents/services.ts | 5 +- .../apis/fleet/delete_agent.ts | 2 +- .../apis/fleet/enrollment_api_keys/crud.ts | 2 +- .../api_integration/apis/fleet/install.ts | 2 +- .../api_integration/apis/fleet/list_agent.ts | 2 +- .../test/api_integration/apis/fleet/setup.ts | 17 +- .../apis/fleet/unenroll_agent.ts | 2 +- x-pack/test/api_integration/apis/index.js | 4 +- .../apis/infra/feature_controls.ts | 2 +- .../test/api_integration/apis/infra/index.js | 2 +- .../apis/infra/log_analysis.ts | 4 +- .../api_integration/apis/infra/log_entries.ts | 2 +- .../apis/infra/log_entry_highlights.ts | 14 +- .../api_integration/apis/infra/log_item.ts | 2 +- .../api_integration/apis/infra/log_sources.ts | 2 +- .../api_integration/apis/infra/log_summary.ts | 4 +- .../apis/infra/logs_without_millis.ts | 2 +- .../api_integration/apis/infra/metadata.ts | 4 +- .../api_integration/apis/infra/metrics.ts | 6 +- .../apis/infra/metrics_alerting.ts | 2 +- .../apis/infra/metrics_explorer.ts | 10 +- .../api_integration/apis/infra/sources.ts | 4 +- .../test/api_integration/apis/infra/waffle.ts | 16 +- .../api_integration/apis/ingest/policies.ts | 10 +- .../test/api_integration/apis/kibana/index.js | 2 +- .../apis/kibana/kql_telemetry/index.js | 2 +- .../kibana/kql_telemetry/kql_telemetry.js | 2 +- .../apis/kibana/stats/index.js | 2 +- .../apis/kibana/stats/stats.js | 2 +- .../api_integration/apis/lens/telemetry.ts | 16 +- .../apis/logstash/cluster/index.ts | 2 +- .../apis/logstash/cluster/load.ts | 2 +- .../api_integration/apis/logstash/index.ts | 2 +- .../apis/logstash/pipeline/delete.ts | 2 +- .../apis/logstash/pipeline/index.ts | 2 +- .../apis/logstash/pipeline/load.ts | 2 +- .../apis/logstash/pipeline/save.ts | 2 +- .../apis/logstash/pipelines/delete.ts | 2 +- .../apis/logstash/pipelines/index.ts | 2 +- .../apis/logstash/pipelines/list.ts | 2 +- .../management/advanced_settings/index.ts | 2 +- .../auto_follow_pattern.helpers.js | 10 +- .../auto_follow_pattern.js | 4 +- .../follower_indices.helpers.js | 19 +- .../follower_indices.js | 4 +- .../cross_cluster_replication/index.js | 2 +- .../lib/elasticsearch.js | 6 +- .../remote_clusters.helpers.js | 4 +- .../api_integration/apis/management/index.js | 2 +- .../index_lifecycle_management/index.js | 2 +- .../indices.helpers.js | 35 +- .../index_lifecycle_management/indices.js | 2 +- .../lib/elasticsearch.js | 14 +- .../index_lifecycle_management/lib/utils.js | 4 +- .../nodes.helpers.js | 2 +- .../index_lifecycle_management/nodes.js | 4 +- .../policies.helpers.js | 11 +- .../index_lifecycle_management/policies.js | 6 +- .../templates.helpers.js | 13 +- .../index_lifecycle_management/templates.js | 6 +- .../apis/management/index_management/index.js | 2 +- .../index_management/indices.helpers.js | 23 +- .../management/index_management/indices.js | 20 +- .../index_management/lib/elasticsearch.js | 8 +- .../management/index_management/lib/utils.js | 2 +- .../index_management/mapping.helpers.js | 2 +- .../management/index_management/mapping.js | 2 +- .../index_management/settings.helpers.js | 7 +- .../management/index_management/settings.js | 4 +- .../index_management/stats.helpers.js | 2 +- .../apis/management/index_management/stats.js | 4 +- .../index_management/templates.helpers.js | 14 +- .../management/index_management/templates.js | 12 +- .../apis/management/ingest_pipelines/index.ts | 2 +- .../ingest_pipelines/ingest_pipelines.ts | 31 +- .../apis/management/remote_clusters/index.js | 2 +- .../remote_clusters/remote_clusters.js | 21 +- .../apis/management/rollup/index.js | 2 +- .../rollup/index_patterns_extensions.js | 4 +- .../apis/management/rollup/lib/es_index.js | 8 +- .../apis/management/rollup/lib/utils.js | 2 +- .../apis/management/rollup/rollup.js | 12 +- .../management/rollup/rollup.test_helpers.js | 27 +- .../apis/management/rollup/rollup_search.js | 2 +- .../test/api_integration/apis/maps/index.js | 2 +- .../apis/maps/index_settings.js | 2 +- .../api_integration/apis/maps/migrations.js | 2 +- .../apis/ml/anomaly_detectors/create.ts | 2 +- .../apis/ml/anomaly_detectors/index.ts | 4 +- .../apis/ml/data_frame_analytics/index.ts | 4 +- .../ml/data_visualizer/get_field_stats.ts | 2 +- .../ml/data_visualizer/get_overall_stats.ts | 2 +- .../apis/ml/data_visualizer/index.ts | 4 +- .../ml/fields_service/field_cardinality.ts | 2 +- .../apis/ml/fields_service/index.ts | 4 +- .../ml/fields_service/time_field_range.ts | 2 +- x-pack/test/api_integration/apis/ml/index.ts | 4 +- .../job_validation/bucket_span_estimator.ts | 8 +- .../calculate_model_memory_limit.ts | 2 +- .../apis/ml/job_validation/cardinality.ts | 2 +- .../apis/ml/job_validation/index.ts | 4 +- .../apis/ml/job_validation/validate.ts | 2 +- .../ml/jobs/categorization_field_examples.ts | 2 +- .../api_integration/apis/ml/jobs/index.ts | 4 +- .../apis/ml/jobs/jobs_summary.ts | 16 +- .../apis/ml/modules/get_module.ts | 2 +- .../api_integration/apis/ml/modules/index.ts | 4 +- .../apis/ml/modules/recognize_module.ts | 4 +- .../apis/ml/modules/setup_module.ts | 26 +- .../api_integration/apis/ml/results/index.ts | 2 +- .../apis/monitoring/apm/index.js | 2 +- .../apis/monitoring/apm/instance.js | 2 +- .../apis/monitoring/apm/instances.js | 2 +- .../apis/monitoring/apm/overview.js | 2 +- .../apis/monitoring/beats/detail.js | 2 +- .../apis/monitoring/beats/index.js | 2 +- .../apis/monitoring/beats/list.js | 2 +- .../apis/monitoring/beats/overview.js | 2 +- .../apis/monitoring/cluster/index.js | 2 +- .../apis/monitoring/cluster/list.js | 2 +- .../apis/monitoring/cluster/overview.js | 4 +- .../apis/monitoring/common/index.js | 2 +- .../apis/monitoring/common/mappings_exist.js | 2 +- .../apis/monitoring/elasticsearch/ccr.js | 2 +- .../monitoring/elasticsearch/ccr_shard.js | 2 +- .../apis/monitoring/elasticsearch/index.js | 2 +- .../monitoring/elasticsearch/index_detail.js | 2 +- .../apis/monitoring/elasticsearch/indices.js | 2 +- .../monitoring/elasticsearch/node_detail.js | 4 +- .../elasticsearch/node_detail_advanced.js | 2 +- .../apis/monitoring/elasticsearch/nodes.js | 22 +- .../apis/monitoring/elasticsearch/overview.js | 2 +- .../elasticsearch_settings/check_cluster.js | 2 +- .../elasticsearch_settings/check_nodes.js | 4 +- .../elasticsearch_settings/index.js | 2 +- .../set_collection_enabled.js | 7 +- .../set_collection_interval.js | 2 +- .../api_integration/apis/monitoring/index.js | 2 +- .../apis/monitoring/kibana/index.js | 2 +- .../apis/monitoring/kibana/instance.js | 2 +- .../apis/monitoring/kibana/listing.js | 2 +- .../apis/monitoring/kibana/overview.js | 2 +- .../apis/monitoring/logs/cluster.js | 2 +- .../apis/monitoring/logs/index.js | 2 +- .../apis/monitoring/logs/index_detail.js | 2 +- .../apis/monitoring/logs/multiple_clusters.js | 2 +- .../apis/monitoring/logs/node_detail.js | 2 +- .../apis/monitoring/logstash/index.js | 2 +- .../logstash/multicluster_pipelines.js | 2 +- .../apis/monitoring/logstash/node_detail.js | 2 +- .../apis/monitoring/logstash/nodes.js | 2 +- .../apis/monitoring/logstash/overview.js | 2 +- .../apis/monitoring/logstash/pipelines.js | 4 +- .../apis/monitoring/setup/collection/ccs.js | 2 +- .../monitoring/setup/collection/detect_apm.js | 2 +- .../setup/collection/detect_beats.js | 2 +- .../collection/detect_beats_management.js | 2 +- .../setup/collection/detect_logstash.js | 2 +- .../collection/detect_logstash_management.js | 2 +- .../collection/es_and_kibana_exclusive_mb.js | 2 +- .../setup/collection/es_and_kibana_mb.js | 2 +- .../apis/monitoring/setup/collection/index.js | 2 +- .../setup/collection/kibana_exclusive_mb.js | 2 +- .../monitoring/setup/collection/kibana_mb.js | 2 +- .../monitoring/setup/collection/security.js | 2 +- .../apis/monitoring/setup/index.js | 4 +- .../monitoring/standalone_cluster/cluster.js | 2 +- .../monitoring/standalone_cluster/clusters.js | 4 +- .../monitoring/standalone_cluster/index.js | 2 +- .../api_integration/apis/security/api_keys.ts | 2 +- .../apis/security/basic_login.js | 12 +- .../apis/security/builtin_es_privileges.ts | 6 +- .../apis/security/change_password.ts | 2 +- .../api_integration/apis/security/index.js | 4 +- .../apis/security/index_fields.ts | 4 +- .../apis/security/privileges.ts | 12 +- .../apis/security/privileges_basic.ts | 2 +- .../api_integration/apis/security/roles.js | 7 +- .../apis/security/security_basic.ts | 4 +- .../api_integration/apis/security/session.ts | 2 +- .../apis/short_urls/feature_controls.ts | 6 +- .../apis/siem/authentications.ts | 6 +- .../apis/siem/feature_controls.ts | 2 +- .../test/api_integration/apis/siem/hosts.ts | 10 +- .../test/api_integration/apis/siem/index.js | 2 +- .../api_integration/apis/siem/ip_overview.ts | 6 +- .../apis/siem/kpi_host_details.ts | 6 +- .../api_integration/apis/siem/kpi_hosts.ts | 6 +- .../api_integration/apis/siem/kpi_network.ts | 6 +- .../api_integration/apis/siem/network_dns.ts | 10 +- .../apis/siem/network_top_n_flow.ts | 14 +- .../apis/siem/overview_host.ts | 4 +- .../apis/siem/overview_network.ts | 8 +- .../apis/siem/saved_objects/notes.ts | 2 +- .../apis/siem/saved_objects/pinned_events.ts | 2 +- .../apis/siem/saved_objects/timeline.ts | 4 +- .../test/api_integration/apis/siem/sources.ts | 4 +- .../api_integration/apis/siem/timeline.ts | 6 +- .../apis/siem/timeline_details.ts | 6 +- x-pack/test/api_integration/apis/siem/tls.ts | 10 +- .../apis/siem/uncommon_processes.ts | 2 +- .../test/api_integration/apis/siem/users.ts | 4 +- .../apis/spaces/get_active_space.ts | 21 +- .../test/api_integration/apis/spaces/index.ts | 4 +- .../apis/spaces/saved_objects.ts | 2 +- .../apis/spaces/space_attributes.ts | 2 +- .../api_integration/apis/telemetry/index.js | 2 +- .../api_integration/apis/telemetry/opt_in.ts | 2 +- .../apis/telemetry/telemetry.js | 2 +- .../apis/telemetry/telemetry_local.js | 11 +- .../telemetry/telemetry_optin_notice_seen.ts | 5 +- .../apis/uptime/get_all_pings.ts | 2 +- .../test/api_integration/apis/uptime/index.ts | 2 +- .../api_integration/apis/uptime/rest/certs.ts | 2 +- .../apis/uptime/rest/doc_count.ts | 2 +- .../apis/uptime/rest/dynamic_settings.ts | 2 +- .../apis/uptime/rest/filters.ts | 2 +- .../uptime/rest/helper/expect_fixture_eql.ts | 2 +- .../apis/uptime/rest/helper/make_checks.ts | 17 +- .../apis/uptime/rest/helper/make_tls.ts | 5 +- .../api_integration/apis/uptime/rest/index.ts | 2 +- .../apis/uptime/rest/monitor_duration.ts | 2 +- .../apis/uptime/rest/monitor_latest_status.ts | 2 +- .../uptime/rest/monitor_states_generated.ts | 4 +- .../uptime/rest/monitor_states_real_data.ts | 10 +- .../apis/uptime/rest/ping_histogram.ts | 2 +- .../apis/uptime/rest/ping_list.ts | 2 +- .../apis/uptime/rest/snapshot.ts | 2 +- .../apis/uptime/rest/telemetry_collectors.ts | 2 +- .../api_integration/apis/xpack_main/index.js | 2 +- .../apis/xpack_main/settings/index.js | 2 +- .../apis/xpack_main/settings/settings.js | 7 +- .../api_integration/config_security_basic.js | 4 +- .../services/infraops_graphql_client.ts | 2 +- .../services/ingest_manager.ts | 5 +- .../services/siem_graphql_client.ts | 2 +- .../basic/tests/agent_configuration.ts | 6 +- .../basic/tests/annotations.ts | 5 +- .../apm_api_integration/basic/tests/index.ts | 2 +- .../trial/tests/annotations.ts | 5 +- .../apm_api_integration/trial/tests/index.ts | 2 +- .../basic/tests/cases/find_cases.ts | 25 +- .../basic/tests/cases/get_case.ts | 6 +- .../tests/cases/reporters/get_reporters.ts | 6 +- .../basic/tests/cases/status/get_status.ts | 5 +- .../basic/tests/cases/tags/get_tags.ts | 5 +- .../user_actions/get_all_user_actions.ts | 13 +- .../case_api_integration/basic/tests/index.ts | 2 +- .../case_api_integration/common/config.ts | 7 +- .../basic/tests/find_statuses.ts | 2 +- .../basic/tests/import_rules.ts | 2 +- .../basic/tests/index.ts | 2 +- .../common/config.ts | 2 +- .../tests/find_statuses.ts | 2 +- .../security_and_spaces/tests/import_rules.ts | 2 +- .../security_and_spaces/tests/index.ts | 2 +- .../detection_engine_api_integration/utils.ts | 14 +- .../config.ts | 2 +- .../server/hidden_saved_object_routes.ts | 4 +- .../api_consumer_plugin/server/index.ts | 2 +- .../tests/encrypted_saved_objects_api.ts | 7 +- .../tests/index.ts | 2 +- .../apis/alerts/index.ts | 2 +- .../apis/alerts/index_pattern.ts | 2 +- .../apis/index.ts | 2 +- .../apis/metadata.ts | 8 +- .../config.ts | 2 +- x-pack/test/epm_api_integration/apis/file.ts | 2 +- x-pack/test/epm_api_integration/apis/ilm.ts | 2 +- x-pack/test/epm_api_integration/apis/index.js | 4 +- x-pack/test/epm_api_integration/apis/list.ts | 2 +- .../test/epm_api_integration/apis/template.ts | 2 +- x-pack/test/epm_api_integration/config.ts | 2 +- .../advanced_settings_security.ts | 10 +- .../advanced_settings_spaces.ts | 6 +- .../functional/apps/api_keys/home_page.ts | 2 +- x-pack/test/functional/apps/api_keys/index.ts | 2 +- .../apps/apm/feature_controls/apm_security.ts | 8 +- .../apps/apm/feature_controls/apm_spaces.ts | 6 +- .../apps/apm/feature_controls/index.ts | 4 +- x-pack/test/functional/apps/apm/index.ts | 4 +- .../functional/apps/canvas/custom_elements.ts | 2 +- .../test/functional/apps/canvas/expression.ts | 2 +- .../feature_controls/canvas_security.ts | 8 +- .../canvas/feature_controls/canvas_spaces.ts | 8 +- .../test/functional/apps/canvas/smoke_test.js | 2 +- .../cross_cluster_replication/home_page.ts | 2 +- .../apps/cross_cluster_replication/index.ts | 2 +- .../apps/dashboard/_async_dashboard.ts | 10 +- .../drilldowns/dashboard_drilldowns.ts | 4 +- .../apps/dashboard/drilldowns/index.ts | 4 +- .../feature_controls/dashboard_security.ts | 8 +- .../feature_controls/dashboard_spaces.ts | 6 +- .../apps/dashboard/feature_controls/index.ts | 4 +- .../test/functional/apps/dashboard/index.ts | 4 +- .../functional/apps/dashboard/preserve_url.ts | 12 +- .../apps/dashboard/reporting/download_csv.ts | 6 +- .../apps/dashboard/reporting/index.ts | 4 +- .../apps/dashboard/reporting/screenshots.ts | 6 +- .../dashboard_mode/dashboard_empty_screen.js | 4 +- .../dashboard_mode/dashboard_view_mode.js | 4 +- .../functional/apps/dashboard_mode/index.js | 4 +- .../feature_controls/dev_tools_security.ts | 6 +- .../feature_controls/dev_tools_spaces.ts | 6 +- .../apps/dev_tools/feature_controls/index.ts | 4 +- .../test/functional/apps/dev_tools/index.ts | 4 +- .../apps/dev_tools/searchprofiler_editor.ts | 2 +- .../feature_controls/discover_security.ts | 8 +- .../feature_controls/discover_spaces.ts | 6 +- .../apps/discover/feature_controls/index.ts | 4 +- x-pack/test/functional/apps/discover/index.ts | 4 +- .../functional/apps/discover/preserve_url.ts | 12 +- .../functional/apps/discover/reporting.ts | 2 +- .../graph/feature_controls/graph_security.ts | 8 +- .../graph/feature_controls/graph_spaces.ts | 6 +- .../apps/graph/feature_controls/index.ts | 4 +- x-pack/test/functional/apps/graph/graph.ts | 26 +- x-pack/test/functional/apps/graph/index.ts | 4 +- .../apps/grok_debugger/grok_debugger.js | 4 +- .../functional/apps/grok_debugger/index.js | 4 +- .../index_lifecycle_management/home_page.ts | 2 +- .../apps/index_lifecycle_management/index.ts | 2 +- .../apps/index_management/home_page.ts | 2 +- .../functional/apps/index_management/index.ts | 2 +- .../index_patterns/feature_controls/index.ts | 4 +- .../index_patterns_security.ts | 8 +- .../feature_controls/index_patterns_spaces.ts | 4 +- .../apps/infra/feature_controls/index.ts | 4 +- .../infrastructure_security.ts | 8 +- .../feature_controls/infrastructure_spaces.ts | 6 +- .../infra/feature_controls/logs_security.ts | 8 +- .../infra/feature_controls/logs_spaces.ts | 6 +- .../test/functional/apps/infra/home_page.ts | 2 +- x-pack/test/functional/apps/infra/index.ts | 2 +- x-pack/test/functional/apps/infra/link_to.ts | 2 +- .../apps/infra/log_entry_categories_tab.ts | 2 +- .../apps/infra/log_entry_rate_tab.ts | 2 +- .../apps/infra/logs_source_configuration.ts | 2 +- .../infra/metrics_source_configuration.ts | 2 +- .../functional/apps/ingest_pipelines/index.ts | 2 +- .../apps/ingest_pipelines/ingest_pipelines.ts | 4 +- x-pack/test/functional/apps/lens/index.ts | 4 +- .../functional/apps/lens/lens_reporting.ts | 2 +- .../test/functional/apps/lens/smokescreen.ts | 8 +- .../apps/license_management/home_page.ts | 2 +- .../apps/license_management/index.ts | 2 +- x-pack/test/functional/apps/logstash/index.js | 4 +- .../apps/logstash/pipeline_create.js | 4 +- .../functional/apps/logstash/pipeline_list.js | 18 +- .../anomaly_detection/advanced_job.ts | 10 +- .../anomaly_detection/anomaly_explorer.ts | 8 +- .../anomaly_detection/categorization_job.ts | 10 +- .../anomaly_detection/date_nanos_job.ts | 8 +- .../anomaly_detection/index.ts | 4 +- .../anomaly_detection/multi_metric_job.ts | 8 +- .../anomaly_detection/population_job.ts | 12 +- .../anomaly_detection/saved_search_job.ts | 8 +- .../anomaly_detection/single_metric_job.ts | 10 +- .../anomaly_detection/single_metric_viewer.ts | 6 +- .../classification_creation.ts | 8 +- .../data_frame_analytics/cloning.ts | 8 +- .../data_frame_analytics/index.ts | 4 +- .../outlier_detection_creation.ts | 8 +- .../regression_creation.ts | 8 +- .../data_visualizer/file_data_visualizer.ts | 8 +- .../machine_learning/data_visualizer/index.ts | 4 +- .../data_visualizer/index_data_visualizer.ts | 8 +- .../feature_controls/index.ts | 4 +- .../feature_controls/ml_security.ts | 8 +- .../feature_controls/ml_spaces.ts | 6 +- .../functional/apps/machine_learning/index.ts | 4 +- .../functional/apps/machine_learning/pages.ts | 4 +- .../functional/apps/maps/add_layer_panel.js | 2 +- .../apps/maps/blended_vector_layer.js | 2 +- x-pack/test/functional/apps/maps/discover.js | 2 +- .../maps/documents_source/docvalue_fields.js | 2 +- .../apps/maps/documents_source/index.js | 4 +- .../apps/maps/documents_source/search_hits.js | 2 +- .../apps/maps/documents_source/top_hits.js | 2 +- .../apps/maps/embeddable/dashboard.js | 2 +- .../apps/maps/embeddable/embeddable_state.js | 2 +- .../functional/apps/maps/embeddable/index.js | 4 +- .../maps/embeddable/tooltip_filter_actions.js | 2 +- .../apps/maps/es_geo_grid_source.js | 2 +- .../functional/apps/maps/es_pew_pew_source.js | 2 +- .../maps/feature_controls/maps_security.ts | 8 +- .../apps/maps/feature_controls/maps_spaces.ts | 4 +- .../functional/apps/maps/full_screen_mode.js | 2 +- .../import_geojson/add_layer_import_panel.js | 2 +- .../import_geojson/file_indexing_panel.js | 6 +- .../apps/maps/import_geojson/index.js | 4 +- x-pack/test/functional/apps/maps/index.js | 8 +- x-pack/test/functional/apps/maps/joins.js | 8 +- .../test/functional/apps/maps/layer_errors.js | 2 +- .../test/functional/apps/maps/sample_data.js | 2 +- .../apps/maps/saved_object_management.js | 2 +- .../functional/apps/maps/vector_styling.js | 9 +- .../apps/maps/visualize_create_menu.js | 2 +- .../apps/monitoring/beats/beat_detail.js | 2 +- .../apps/monitoring/beats/cluster.js | 2 +- .../apps/monitoring/beats/listing.js | 2 +- .../apps/monitoring/beats/overview.js | 2 +- .../apps/monitoring/cluster/alerts.js | 4 +- .../apps/monitoring/cluster/list.js | 8 +- .../apps/monitoring/cluster/overview.js | 2 +- .../monitoring/elasticsearch/index_detail.js | 2 +- .../apps/monitoring/elasticsearch/indices.js | 2 +- .../monitoring/elasticsearch/node_detail.js | 2 +- .../apps/monitoring/elasticsearch/nodes.js | 6 +- .../apps/monitoring/elasticsearch/overview.js | 2 +- .../apps/monitoring/elasticsearch/shards.js | 2 +- .../monitoring/enable_monitoring/index.js | 11 +- .../apps/monitoring/feature_controls/index.ts | 4 +- .../feature_controls/monitoring_security.ts | 6 +- .../feature_controls/monitoring_spaces.ts | 6 +- .../test/functional/apps/monitoring/index.js | 4 +- .../apps/monitoring/kibana/instance.js | 2 +- .../apps/monitoring/kibana/instances.js | 2 +- .../apps/monitoring/kibana/overview.js | 2 +- .../apps/monitoring/logstash/pipelines.js | 2 +- .../functional/apps/monitoring/time_filter.js | 2 +- .../apps/remote_clusters/home_page.ts | 2 +- .../functional/apps/remote_clusters/index.ts | 2 +- .../apps/reporting_management/index.ts | 2 +- .../report_delete_pagination.ts | 2 +- .../apps/rollup_job/hybrid_index_pattern.js | 8 +- .../test/functional/apps/rollup_job/index.js | 4 +- .../functional/apps/rollup_job/rollup_jobs.js | 6 +- .../test/functional/apps/rollup_job/tsvb.js | 6 +- .../saved_objects_management_security.ts | 2 +- .../apps/security/basic_license/index.ts | 4 +- .../security/basic_license/role_mappings.ts | 2 +- .../apps/security/doc_level_security_roles.js | 10 +- .../apps/security/field_level_security.js | 16 +- x-pack/test/functional/apps/security/index.js | 4 +- .../functional/apps/security/management.js | 4 +- .../functional/apps/security/rbac_phase1.js | 8 +- .../functional/apps/security/role_mappings.ts | 6 +- .../apps/security/secure_roles_perm.js | 14 +- .../test/functional/apps/security/security.ts | 4 +- .../apps/security/trial_license/index.ts | 4 +- .../security/trial_license/login_selector.ts | 4 +- .../functional/apps/security/user_email.js | 14 +- x-pack/test/functional/apps/security/users.js | 14 +- .../apps/snapshot_restore/home_page.ts | 2 +- .../functional/apps/snapshot_restore/index.ts | 2 +- .../apps/spaces/copy_saved_objects.ts | 2 +- .../functional/apps/spaces/enter_space.ts | 2 +- .../feature_controls/spaces_security.ts | 6 +- .../apps/spaces/spaces_selection.ts | 2 +- .../apps/status_page/status_page.ts | 2 +- .../feature_controls/timelion_security.ts | 6 +- .../feature_controls/timelion_spaces.ts | 6 +- .../test/functional/apps/transform/cloning.ts | 6 +- .../apps/transform/creation_index_pattern.ts | 8 +- .../apps/transform/creation_saved_search.ts | 8 +- .../test/functional/apps/transform/index.ts | 4 +- .../upgrade_assistant/upgrade_assistant.ts | 2 +- .../functional/apps/uptime/certificates.ts | 2 +- .../apps/uptime/feature_controls/index.ts | 4 +- .../feature_controls/uptime_security.ts | 8 +- .../uptime/feature_controls/uptime_spaces.ts | 6 +- x-pack/test/functional/apps/uptime/index.ts | 2 +- .../test/functional/apps/uptime/locations.ts | 4 +- .../test/functional/apps/uptime/ml_anomaly.ts | 2 +- x-pack/test/functional/apps/uptime/monitor.ts | 2 +- .../test/functional/apps/uptime/overview.ts | 2 +- .../feature_controls/visualize_security.ts | 8 +- .../feature_controls/visualize_spaces.ts | 6 +- .../apps/visualize/hybrid_visualization.ts | 2 +- .../apps/visualize/precalculated_histogram.ts | 10 +- .../functional/apps/visualize/preserve_url.ts | 12 +- .../functional/apps/visualize/reporting.ts | 4 +- x-pack/test/functional/apps/watcher/index.js | 4 +- .../functional/apps/watcher/watcher_test.js | 4 +- x-pack/test/functional/config.coverage.js | 2 +- x-pack/test/functional/config.edge.js | 2 +- x-pack/test/functional/config.firefox.js | 2 +- x-pack/test/functional/config.ie.js | 2 +- x-pack/test/functional/config.js | 2 +- .../test/functional/config_security_basic.ts | 2 +- .../test/functional/config_security_trial.ts | 2 +- .../test/functional/page_objects/gis_page.js | 2 +- .../page_objects/index_management_page.ts | 26 +- .../page_objects/ingest_pipelines_page.ts | 2 +- .../test/functional/page_objects/lens_page.ts | 4 +- .../functional/page_objects/log_wrapper.ts | 2 +- .../functional/page_objects/reporting_page.ts | 2 +- .../functional/page_objects/rollup_page.js | 2 +- .../functional/page_objects/security_page.ts | 34 +- .../page_objects/snapshot_restore_page.ts | 4 +- .../functional/page_objects/uptime_page.ts | 2 +- .../functional/page_objects/watcher_page.js | 4 +- x-pack/test/functional/services/ace_editor.js | 2 +- .../infra_source_configuration_form.ts | 4 +- .../functional/services/logs_ui/log_stream.ts | 2 +- .../machine_learning/anomaly_explorer.ts | 2 +- .../services/machine_learning/api.ts | 15 +- .../data_frame_analytics_table.ts | 2 +- .../machine_learning/job_selection.ts | 2 +- .../services/machine_learning/job_table.ts | 28 +- .../machine_learning/security_common.ts | 2 +- .../services/monitoring/cluster_alerts.js | 2 +- .../monitoring/elasticsearch_shards.js | 4 +- .../functional/services/pipeline_editor.js | 2 +- .../test/functional/services/pipeline_list.js | 24 +- .../functional/services/transform_ui/api.ts | 5 +- .../services/transform_ui/security_common.ts | 2 +- .../services/transform_ui/transform_table.ts | 10 +- .../services/transform_ui/wizard.ts | 8 +- .../functional/services/uptime/monitor.ts | 2 +- .../apps/endpoint/alerts.ts | 4 +- .../feature_controls/endpoint_spaces.ts | 6 +- .../apps/endpoint/feature_controls/index.ts | 4 +- .../apps/endpoint/header_nav.ts | 2 +- .../apps/endpoint/host_list.ts | 4 +- .../apps/endpoint/index.ts | 4 +- .../apps/endpoint/landing_page.ts | 2 +- .../apps/endpoint/policy_list.ts | 4 +- .../apps/endpoint/resolver.ts | 6 +- x-pack/test/functional_endpoint/config.ts | 2 +- .../page_objects/endpoint_alerts_page.ts | 10 +- .../page_objects/endpoint_page.ts | 8 +- .../apps/endpoint/index.ts | 4 +- .../apps/endpoint/landing_page.ts | 2 +- .../config.ts | 2 +- .../apps/triggers_actions_ui/alerts.ts | 2 +- .../apps/triggers_actions_ui/connectors.ts | 2 +- .../apps/triggers_actions_ui/details.ts | 30 +- .../apps/triggers_actions_ui/home_page.ts | 2 +- .../apps/triggers_actions_ui/index.ts | 2 +- .../apps/uptime/alert_flyout.ts | 14 +- .../apps/uptime/index.ts | 2 +- x-pack/test/functional_with_es_ssl/config.ts | 2 +- .../page_objects/alert_details.ts | 4 +- .../page_objects/triggers_actions_ui_page.ts | 4 +- .../anonymous_access.config.ts | 2 +- .../kerberos_api_integration/apis/index.ts | 4 +- .../apis/security/index.ts | 2 +- .../apis/security/kerberos_login.ts | 21 +- .../test/kerberos_api_integration/config.ts | 2 +- x-pack/test/licensing_plugin/config.legacy.ts | 2 +- x-pack/test/licensing_plugin/config.public.ts | 2 +- x-pack/test/licensing_plugin/config.ts | 2 +- x-pack/test/licensing_plugin/legacy/index.ts | 4 +- .../test/licensing_plugin/legacy/updates.ts | 2 +- x-pack/test/licensing_plugin/public/index.ts | 4 +- .../test/licensing_plugin/public/updates.ts | 10 +- x-pack/test/licensing_plugin/scenario.ts | 2 +- x-pack/test/licensing_plugin/server/header.ts | 2 +- x-pack/test/licensing_plugin/server/index.ts | 4 +- x-pack/test/licensing_plugin/server/info.ts | 2 +- .../test/licensing_plugin/server/updates.ts | 2 +- .../apis/index.ts | 4 +- .../apis/login_selector.ts | 2 +- .../login_selector_api_integration/config.ts | 2 +- .../basic/tests/annotations.ts | 5 +- .../basic/tests/index.ts | 2 +- .../trial/tests/annotations.ts | 10 +- .../trial/tests/index.ts | 2 +- .../apis/authorization_code_flow/index.js | 4 +- .../apis/authorization_code_flow/oidc_auth.js | 17 +- .../apis/implicit_flow/index.ts | 4 +- .../apis/implicit_flow/oidc_auth.ts | 4 +- x-pack/test/oidc_api_integration/config.ts | 2 +- .../fixtures/oidc_provider/server/index.ts | 2 +- .../oidc_provider/server/init_routes.ts | 4 +- .../fixtures/oidc_tools.ts | 4 +- .../implicit_flow.config.ts | 2 +- x-pack/test/pki_api_integration/apis/index.ts | 4 +- .../apis/security/index.ts | 2 +- .../apis/security/pki_auth.ts | 6 +- x-pack/test/pki_api_integration/config.ts | 2 +- x-pack/test/plugin_api_integration/config.ts | 6 +- .../plugins/event_log/server/init_routes.ts | 16 +- .../sample_task_plugin/server/init_routes.ts | 16 +- .../sample_task_plugin/server/plugin.ts | 6 +- .../test_suites/event_log/index.ts | 2 +- .../event_log/public_api_integration.ts | 9 +- .../event_log/service_api_integration.ts | 7 +- .../licensed_feature_usage/feature_usage.ts | 2 +- .../licensed_feature_usage/index.ts | 4 +- .../test_suites/task_manager/index.js | 2 +- .../task_manager/task_manager_integration.js | 50 +- x-pack/test/plugin_api_perf/config.js | 6 +- .../server/init_routes.ts | 8 +- .../task_manager_performance/server/plugin.ts | 9 +- .../test_suites/task_manager/index.ts | 2 +- .../task_manager_perf_integration.ts | 7 +- x-pack/test/plugin_functional/config.ts | 6 +- .../applications/resolver_test/index.tsx | 2 +- .../plugins/resolver_test/public/plugin.ts | 2 +- .../test_suites/resolver/index.ts | 10 +- .../test/reporting_api_integration/config.js | 2 +- .../reporting/csv_job_params.ts | 2 +- .../reporting/csv_saved_search.ts | 4 +- .../reporting/index.ts | 4 +- .../reporting/usage.ts | 2 +- .../reporting_api_integration/services.ts | 6 +- .../test/saml_api_integration/apis/index.ts | 4 +- .../apis/security/index.ts | 2 +- .../apis/security/saml_login.ts | 19 +- x-pack/test/saml_api_integration/config.ts | 2 +- .../fixtures/saml_provider/server/index.ts | 2 +- .../common/config.ts | 2 +- .../common/lib/saved_object_test_utils.ts | 10 +- .../common/suites/bulk_create.ts | 8 +- .../common/suites/bulk_get.ts | 6 +- .../common/suites/bulk_update.ts | 8 +- .../common/suites/create.ts | 4 +- .../common/suites/delete.ts | 4 +- .../common/suites/export.ts | 4 +- .../common/suites/find.ts | 4 +- .../common/suites/get.ts | 4 +- .../common/suites/import.ts | 14 +- .../common/suites/resolve_import_errors.ts | 14 +- .../common/suites/update.ts | 4 +- .../security_and_spaces/apis/bulk_create.ts | 6 +- .../security_and_spaces/apis/bulk_get.ts | 6 +- .../security_and_spaces/apis/bulk_update.ts | 6 +- .../security_and_spaces/apis/create.ts | 6 +- .../security_and_spaces/apis/delete.ts | 6 +- .../security_and_spaces/apis/export.ts | 6 +- .../security_and_spaces/apis/find.ts | 6 +- .../security_and_spaces/apis/get.ts | 6 +- .../security_and_spaces/apis/import.ts | 6 +- .../security_and_spaces/apis/index.ts | 4 +- .../apis/resolve_import_errors.ts | 6 +- .../security_and_spaces/apis/update.ts | 6 +- .../security_only/apis/bulk_create.ts | 6 +- .../security_only/apis/bulk_get.ts | 6 +- .../security_only/apis/bulk_update.ts | 6 +- .../security_only/apis/create.ts | 6 +- .../security_only/apis/delete.ts | 6 +- .../security_only/apis/export.ts | 6 +- .../security_only/apis/find.ts | 6 +- .../security_only/apis/get.ts | 6 +- .../security_only/apis/import.ts | 6 +- .../security_only/apis/index.ts | 4 +- .../apis/resolve_import_errors.ts | 6 +- .../security_only/apis/update.ts | 6 +- .../spaces_only/apis/bulk_create.ts | 4 +- .../spaces_only/apis/bulk_get.ts | 2 +- .../spaces_only/apis/bulk_update.ts | 2 +- .../spaces_only/apis/create.ts | 2 +- .../spaces_only/apis/delete.ts | 2 +- .../spaces_only/apis/export.ts | 2 +- .../spaces_only/apis/find.ts | 2 +- .../spaces_only/apis/get.ts | 2 +- .../spaces_only/apis/import.ts | 2 +- .../spaces_only/apis/index.ts | 4 +- .../spaces_only/apis/resolve_import_errors.ts | 2 +- .../spaces_only/apis/update.ts | 2 +- x-pack/test/siem_cypress/config.ts | 2 +- x-pack/test/siem_cypress/runner.ts | 2 +- .../spaces_api_integration/common/config.ts | 2 +- .../common/suites/copy_to_space.ts | 2 +- .../common/suites/delete.ts | 9 +- .../common/suites/get.ts | 2 +- .../common/suites/get_all.ts | 2 +- .../common/suites/share_add.ts | 4 +- .../common/suites/share_remove.ts | 4 +- .../security_and_spaces/apis/copy_to_space.ts | 2 +- .../security_and_spaces/apis/create.ts | 2 +- .../security_and_spaces/apis/delete.ts | 2 +- .../security_and_spaces/apis/get.ts | 4 +- .../security_and_spaces/apis/get_all.ts | 2 +- .../security_and_spaces/apis/index.ts | 4 +- .../apis/resolve_copy_to_space_conflicts.ts | 2 +- .../security_and_spaces/apis/share_add.ts | 14 +- .../security_and_spaces/apis/share_remove.ts | 6 +- .../security_and_spaces/apis/update.ts | 2 +- .../spaces_only/apis/copy_to_space.ts | 2 +- .../spaces_only/apis/create.ts | 2 +- .../spaces_only/apis/delete.ts | 2 +- .../spaces_only/apis/get.ts | 4 +- .../spaces_only/apis/get_all.ts | 2 +- .../spaces_only/apis/index.ts | 2 +- .../apis/resolve_copy_to_space_conflicts.ts | 2 +- .../spaces_only/apis/share_add.ts | 2 +- .../spaces_only/apis/share_remove.ts | 2 +- .../spaces_only/apis/update.ts | 2 +- .../test/token_api_integration/auth/header.js | 6 +- .../test/token_api_integration/auth/index.js | 4 +- .../test/token_api_integration/auth/login.js | 6 +- .../test/token_api_integration/auth/logout.js | 6 +- .../token_api_integration/auth/session.js | 18 +- x-pack/test/token_api_integration/config.js | 2 +- x-pack/test/ui_capabilities/common/config.ts | 2 +- .../common/lib/assert_deeply_false.ts | 2 +- .../common/nav_links_builder.ts | 4 +- .../common/services/ui_capabilities.ts | 4 +- .../security_and_spaces/tests/catalogue.ts | 2 +- .../security_and_spaces/tests/foo.ts | 2 +- .../security_and_spaces/tests/index.ts | 4 +- .../security_and_spaces/tests/nav_links.ts | 2 +- .../security_only/tests/catalogue.ts | 2 +- .../security_only/tests/foo.ts | 2 +- .../security_only/tests/index.ts | 4 +- .../security_only/tests/nav_links.ts | 2 +- .../spaces_only/tests/catalogue.ts | 2 +- .../ui_capabilities/spaces_only/tests/foo.ts | 2 +- .../spaces_only/tests/index.ts | 2 +- .../spaces_only/tests/nav_links.ts | 2 +- .../upgrade_assistant_integration/config.js | 2 +- .../upgrade_assistant/index.js | 4 +- .../upgrade_assistant/reindexing.js | 8 +- .../upgrade_assistant/status.ts | 2 +- x-pack/test/visual_regression/config.ts | 2 +- .../tests/canvas/fullscreen.js | 2 +- .../visual_regression/tests/canvas/index.js | 4 +- .../visual_regression/tests/infra/index.js | 4 +- .../tests/infra/saved_views.js | 2 +- .../tests/infra/waffle_map.js | 2 +- .../visual_regression/tests/login_page.ts | 2 +- .../visual_regression/tests/maps/index.js | 4 +- .../tests/maps/vector_styling.js | 2 +- .../test_subjects_finder/background.js | 2 +- .../test_subjects_finder/popup.js | 12 +- .../start_tracking_test_subjects.js | 10 +- x-pack/test_utils/enzyme_helpers.tsx | 6 +- x-pack/test_utils/jest/config.integration.js | 2 +- x-pack/test_utils/lib/utils.ts | 2 +- x-pack/test_utils/router_helpers.tsx | 4 +- x-pack/test_utils/testbed/testbed.ts | 20 +- 7130 files changed, 31405 insertions(+), 37175 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 86ac92de9042d..aeaf6e04fdc01 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -50,7 +50,7 @@ const ELASTIC_LICENSE_HEADER = ` `; const allMochaRulesOff = {}; -Object.keys(require('eslint-plugin-mocha').rules).forEach(k => { +Object.keys(require('eslint-plugin-mocha').rules).forEach((k) => { allMochaRulesOff['mocha/' + k] = 'off'; }); diff --git a/Gruntfile.js b/Gruntfile.js index c33a576d4340f..0216ab12f7cc5 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -19,7 +19,7 @@ require('./src/setup_node_env'); -module.exports = function(grunt) { +module.exports = function (grunt) { // set the config once before calling load-grunt-config // and once during so that we have access to it via // grunt.config.get() within the config files diff --git a/examples/alerting_example/public/alert_types/always_firing.tsx b/examples/alerting_example/public/alert_types/always_firing.tsx index b7add1f6d43ce..130519308d3c3 100644 --- a/examples/alerting_example/public/alert_types/always_firing.tsx +++ b/examples/alerting_example/public/alert_types/always_firing.tsx @@ -71,7 +71,7 @@ export const AlwaysFiringExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('instances', event.target.valueAsNumber); }} /> diff --git a/examples/alerting_example/public/alert_types/astros.tsx b/examples/alerting_example/public/alert_types/astros.tsx index 3411c6722ccd6..2e263e454fa0c 100644 --- a/examples/alerting_example/public/alert_types/astros.tsx +++ b/examples/alerting_example/public/alert_types/astros.tsx @@ -51,7 +51,7 @@ interface PeopleinSpaceParamsProps { } function isValueInEnum(enumeratin: Record, value: any): boolean { - return !!Object.values(enumeratin).find(enumVal => enumVal === value); + return !!Object.values(enumeratin).find((enumVal) => enumVal === value); } export function getAlertType(): AlertTypeModel { @@ -139,7 +139,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent - errs.map(e => ( + errs.map((e) => (

{field}:`: ${errs}`

@@ -189,7 +189,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('craft', event.target.value); setCraftTrigger({ craft: event.target.value, @@ -238,7 +238,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('op', event.target.value); setOuterSpaceCapacity({ ...outerSpaceCapacityTrigger, @@ -258,7 +258,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('outerSpaceCapacity', event.target.valueAsNumber); setOuterSpaceCapacity({ ...outerSpaceCapacityTrigger, diff --git a/examples/alerting_example/server/alert_types/astros.ts b/examples/alerting_example/server/alert_types/astros.ts index d22bc6164fa52..d25edc1e01b3f 100644 --- a/examples/alerting_example/server/alert_types/astros.ts +++ b/examples/alerting_example/server/alert_types/astros.ts @@ -68,10 +68,7 @@ export const alertType: AlertType = { if (getOperator(op)(peopleInCraft.length, outerSpaceCapacity)) { peopleInCraft.forEach(({ craft, name }) => { - services - .alertInstanceFactory(name) - .replaceState({ craft }) - .scheduleActions('default'); + services.alertInstanceFactory(name).replaceState({ craft }).scheduleActions('default'); }); } diff --git a/examples/bfetch_explorer/public/components/count_until/index.tsx b/examples/bfetch_explorer/public/components/count_until/index.tsx index ce48ce9dfe61f..73cbcf4cbdb1c 100644 --- a/examples/bfetch_explorer/public/components/count_until/index.tsx +++ b/examples/bfetch_explorer/public/components/count_until/index.tsx @@ -82,7 +82,7 @@ export const CountUntil: React.FC = ({ fetchStreaming }) => { setData(Number(e.target.value))} + onChange={(e) => setData(Number(e.target.value))} /> diff --git a/examples/bfetch_explorer/public/components/double_integers/index.tsx b/examples/bfetch_explorer/public/components/double_integers/index.tsx index d8fbe33ec73be..58940c23b1a6c 100644 --- a/examples/bfetch_explorer/public/components/double_integers/index.tsx +++ b/examples/bfetch_explorer/public/components/double_integers/index.tsx @@ -49,18 +49,18 @@ export const DoubleIntegers: React.FC = ({ double }) => { setShowingResults(true); const nums = numbers .split('\n') - .map(num => num.trim()) + .map((num) => num.trim()) .filter(Boolean) .map(Number); counter.set(nums.length); - nums.forEach(num => { + nums.forEach((num) => { double({ num }).then( - result => { + (result) => { if (!isMounted()) return; counter.dec(); pushResult({ num, result }); }, - error => { + (error) => { if (!isMounted()) return; counter.dec(); pushResult({ num, error }); @@ -94,7 +94,7 @@ export const DoubleIntegers: React.FC = ({ double }) => { fullWidth placeholder="Enter numbers in milliseconds separated by new line" value={numbers} - onChange={e => setNumbers(e.target.value)} + onChange={(e) => setNumbers(e.target.value)} /> diff --git a/examples/bfetch_explorer/public/containers/app/index.tsx b/examples/bfetch_explorer/public/containers/app/index.tsx index a448c9e4f3a6a..13dee8ad9e61f 100644 --- a/examples/bfetch_explorer/public/containers/app/index.tsx +++ b/examples/bfetch_explorer/public/containers/app/index.tsx @@ -30,7 +30,7 @@ export const App: React.FC = () => { const routeElements: React.ReactElement[] = []; for (const { items } of routes) { for (const { id, component } of items) { - routeElements.push( component} />); + routeElements.push( component} />); } } diff --git a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx index cc50698e05908..029076adea666 100644 --- a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx +++ b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx @@ -39,7 +39,7 @@ export const Sidebar: React.FC = () => { id, name: title, isSelected: true, - items: items.map(route => ({ + items: items.map((route) => ({ id: route.id, name: route.title, onClick: () => history.push(`/${route.id}`), diff --git a/examples/bfetch_explorer/server/plugin.ts b/examples/bfetch_explorer/server/plugin.ts index bf3b7f50ca6c8..2bfb63edefa3d 100644 --- a/examples/bfetch_explorer/server/plugin.ts +++ b/examples/bfetch_explorer/server/plugin.ts @@ -54,7 +54,7 @@ export class BfetchExplorerPlugin implements Plugin { // Validate inputs. if (num < 0) throw new Error('Invalid number'); // Wait number of specified milliseconds. - await new Promise(r => setTimeout(r, num)); + await new Promise((r) => setTimeout(r, num)); // Double the number and send it back. return { num: 2 * num }; }, diff --git a/examples/demo_search/server/async_demo_search_strategy.ts b/examples/demo_search/server/async_demo_search_strategy.ts index d2d40891a5d93..7ed5062acba48 100644 --- a/examples/demo_search/server/async_demo_search_strategy.ts +++ b/examples/demo_search/server/async_demo_search_strategy.ts @@ -40,7 +40,7 @@ const totalMap = new Map(); export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider = () => { return { - search: async request => { + search: async (request) => { const id = request.id ?? generateId(); const loaded = (loadedMap.get(id) ?? 0) + 1; @@ -52,7 +52,7 @@ export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider { + cancel: async (id) => { loadedMap.delete(id); totalMap.delete(id); }, diff --git a/examples/demo_search/server/demo_search_strategy.ts b/examples/demo_search/server/demo_search_strategy.ts index 5b0883be1fc51..a1fd0e45dbc8e 100644 --- a/examples/demo_search/server/demo_search_strategy.ts +++ b/examples/demo_search/server/demo_search_strategy.ts @@ -22,7 +22,7 @@ import { DEMO_SEARCH_STRATEGY } from '../common'; export const demoSearchStrategyProvider: TSearchStrategyProvider = () => { return { - search: request => { + search: (request) => { return Promise.resolve({ greeting: request.mood === 'happy' diff --git a/examples/embeddable_examples/public/list_container/list_container_component.tsx b/examples/embeddable_examples/public/list_container/list_container_component.tsx index da27889a27603..ae4de1c765154 100644 --- a/examples/embeddable_examples/public/list_container/list_container_component.tsx +++ b/examples/embeddable_examples/public/list_container/list_container_component.tsx @@ -40,7 +40,7 @@ function renderList( embeddableServices: EmbeddableStart ) { let number = 0; - const list = Object.values(panels).map(panel => { + const list = Object.values(panels).map((panel) => { const child = embeddable.getChild(panel.explicitInput.id); number++; return ( diff --git a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx index b2882c97ef501..c059a884f08a2 100644 --- a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx +++ b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx @@ -55,7 +55,7 @@ function wrapSearchTerms(task: string, search?: string) { } function renderTasks(tasks: MultiTaskTodoInput['tasks'], search?: string) { - return tasks.map(task => ( + return tasks.map((task) => ( task.match(search)); + const match = tasks.find((task) => task.match(search)); if (match) return true; return false; diff --git a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx index 49dbce74788bf..f5fe01734bfa5 100644 --- a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx +++ b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx @@ -65,12 +65,12 @@ export class SearchableListContainerComponentInner extends Component { + props.embeddable.getChildIds().forEach((id) => { checked[id] = false; const output = props.embeddable.getChild(id).getOutput(); hasMatch[id] = hasHasMatchOutput(output) && output.hasMatch; }); - props.embeddable.getChildIds().forEach(id => (checked[id] = false)); + props.embeddable.getChildIds().forEach((id) => (checked[id] = false)); this.state = { checked, hasMatch, @@ -78,13 +78,13 @@ export class SearchableListContainerComponentInner extends Component { + this.props.embeddable.getChildIds().forEach((id) => { this.subscriptions[id] = this.props.embeddable .getChild(id) .getOutput$() - .subscribe(output => { + .subscribe((output) => { if (hasHasMatchOutput(output)) { - this.setState(prevState => ({ + this.setState((prevState) => ({ hasMatch: { ...prevState.hasMatch, [id]: output.hasMatch, @@ -96,7 +96,7 @@ export class SearchableListContainerComponentInner extends Component sub.unsubscribe()); + Object.values(this.subscriptions).forEach((sub) => sub.unsubscribe()); } private updateSearch = (search: string) => { @@ -104,7 +104,7 @@ export class SearchableListContainerComponentInner extends Component { - Object.values(this.props.input.panels).map(panel => { + Object.values(this.props.input.panels).map((panel) => { if (this.state.checked[panel.explicitInput.id]) { this.props.embeddable.removeEmbeddable(panel.explicitInput.id); this.subscriptions[panel.explicitInput.id].unsubscribe(); @@ -115,7 +115,7 @@ export class SearchableListContainerComponentInner extends Component { const { input, embeddable } = this.props; const checked: { [key: string]: boolean } = {}; - Object.values(input.panels).map(panel => { + Object.values(input.panels).map((panel) => { const child = embeddable.getChild(panel.explicitInput.id); const output = child.getOutput(); if (hasHasMatchOutput(output) && output.hasMatch) { @@ -126,7 +126,7 @@ export class SearchableListContainerComponentInner extends Component { - this.setState(prevState => ({ checked: { ...prevState.checked, [id]: isChecked } })); + this.setState((prevState) => ({ checked: { ...prevState.checked, [id]: isChecked } })); }; public renderControls() { @@ -156,7 +156,7 @@ export class SearchableListContainerComponentInner extends Component this.updateSearch(ev.target.value)} + onChange={(ev) => this.updateSearch(ev.target.value)} /> @@ -183,7 +183,7 @@ export class SearchableListContainerComponentInner extends Component { + const list = Object.values(input.panels).map((panel) => { const childEmbeddable = embeddable.getChild(panel.explicitInput.id); id++; return childEmbeddable ? ( @@ -195,7 +195,7 @@ export class SearchableListContainerComponentInner extends Component this.toggleCheck(e.target.checked, childEmbeddable.id)} + onChange={(e) => this.toggleCheck(e.target.checked, childEmbeddable.id)} /> diff --git a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx index bc577ca36d793..a46c3ce9ed8e9 100644 --- a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx +++ b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx @@ -34,7 +34,7 @@ function TaskInput({ onSave }: { onSave: (task: string) => void }) { data-test-subj="taskInputField" value={task} placeholder="Enter task here" - onChange={e => setTask(e.target.value)} + onChange={(e) => setTask(e.target.value)} /> onSave(task)}> Save @@ -69,7 +69,7 @@ export class TodoEmbeddableFactory */ public getExplicitInput = async () => { const { openModal } = await this.getStartServices(); - return new Promise<{ task: string }>(resolve => { + return new Promise<{ task: string }>((resolve) => { const onSave = (task: string) => resolve({ task }); const overlay = openModal( toMountPoint( diff --git a/examples/embeddable_explorer/public/app.tsx b/examples/embeddable_explorer/public/app.tsx index e18012b4b3d80..3fc7fbb3b89ef 100644 --- a/examples/embeddable_explorer/public/app.tsx +++ b/examples/embeddable_explorer/public/app.tsx @@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & { }; const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { - const navItems = pages.map(page => ({ + const navItems = pages.map((page) => ({ id: page.id, name: page.title, onClick: () => history.push(`/${page.id}`), @@ -122,7 +122,7 @@ const EmbeddableExplorerApp = ({ ]; const routes = pages.map((page, i) => ( - page.component} /> + page.component} /> )); return ( diff --git a/examples/embeddable_explorer/public/embeddable_panel_example.tsx b/examples/embeddable_explorer/public/embeddable_panel_example.tsx index 54cd7c5b5b2c0..98f30632ebf43 100644 --- a/examples/embeddable_explorer/public/embeddable_panel_example.tsx +++ b/examples/embeddable_explorer/public/embeddable_panel_example.tsx @@ -84,7 +84,7 @@ export function EmbeddablePanelExample({ embeddableServices }: Props) { const factory = embeddableServices.getEmbeddableFactory(SEARCHABLE_LIST_CONTAINER); const promise = factory?.create(searchableInput); if (promise) { - promise.then(e => { + promise.then((e) => { if (ref.current) { setEmbeddable(e); } diff --git a/examples/embeddable_explorer/public/todo_embeddable_example.tsx b/examples/embeddable_explorer/public/todo_embeddable_example.tsx index 2af6c713593c6..f43a81c3e7651 100644 --- a/examples/embeddable_explorer/public/todo_embeddable_example.tsx +++ b/examples/embeddable_explorer/public/todo_embeddable_example.tsx @@ -82,7 +82,7 @@ export class TodoEmbeddableExample extends React.Component { icon: 'broom', title: 'Trash', }) - .then(embeddable => { + .then((embeddable) => { this.embeddable = embeddable; this.setState({ loading: false }); }); @@ -135,7 +135,7 @@ export class TodoEmbeddableExample extends React.Component { this.setState({ title: ev.target.value })} + onChange={(ev) => this.setState({ title: ev.target.value })} /> @@ -143,7 +143,7 @@ export class TodoEmbeddableExample extends React.Component { this.setState({ icon: ev.target.value })} + onChange={(ev) => this.setState({ icon: ev.target.value })} /> @@ -153,7 +153,7 @@ export class TodoEmbeddableExample extends React.Component { fullWidth resize="horizontal" data-test-subj="taskTodo" - onChange={ev => this.setState({ task: ev.target.value })} + onChange={(ev) => this.setState({ task: ev.target.value })} /> diff --git a/examples/search_explorer/public/application.tsx b/examples/search_explorer/public/application.tsx index ea6d65d9e2113..a7072936f268d 100644 --- a/examples/search_explorer/public/application.tsx +++ b/examples/search_explorer/public/application.tsx @@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & { }; const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { - const navItems = pages.map(page => ({ + const navItems = pages.map((page) => ({ id: page.id, name: page.title, onClick: () => history.push(`/${page.id}`), @@ -103,7 +103,7 @@ const SearchApp = ({ basename, data, application }: SearchBarComponentParams) => ]; const routes = pages.map((page, i) => ( - buildPage(page)} /> + buildPage(page)} /> )); return ( diff --git a/examples/search_explorer/public/async_demo_strategy.tsx b/examples/search_explorer/public/async_demo_strategy.tsx index 40ddcc1f48fe7..9cea556c32d54 100644 --- a/examples/search_explorer/public/async_demo_strategy.tsx +++ b/examples/search_explorer/public/async_demo_strategy.tsx @@ -73,7 +73,7 @@ export class AsyncDemoStrategy extends React.Component { this.setState({ fibonacciNumbers: parseFloat(e.target.value) })} + onChange={(e) => this.setState({ fibonacciNumbers: parseFloat(e.target.value) })} /> diff --git a/examples/search_explorer/public/demo_strategy.tsx b/examples/search_explorer/public/demo_strategy.tsx index 7c6c21d2b7aed..3de6827818e14 100644 --- a/examples/search_explorer/public/demo_strategy.tsx +++ b/examples/search_explorer/public/demo_strategy.tsx @@ -81,7 +81,7 @@ export class DemoStrategy extends React.Component { this.setState({ name: e.target.value })} + onChange={(e) => this.setState({ name: e.target.value })} /> @@ -90,7 +90,7 @@ export class DemoStrategy extends React.Component { this.setState({ mood: e.target.value })} + onChange={(e) => this.setState({ mood: e.target.value })} /> diff --git a/examples/search_explorer/public/do_search.tsx b/examples/search_explorer/public/do_search.tsx index a6b6b9b57db4a..deadb06b16f5f 100644 --- a/examples/search_explorer/public/do_search.tsx +++ b/examples/search_explorer/public/do_search.tsx @@ -61,10 +61,10 @@ export class DoSearch extends React.Component { this.abortController = new AbortController(); this.props.search(this.abortController.signal).subscribe( - response => { + (response) => { this.setState({ response, error: undefined }); }, - error => { + (error) => { this.setState({ error, searching: false, response: undefined }); }, () => { diff --git a/examples/search_explorer/public/es_strategy.tsx b/examples/search_explorer/public/es_strategy.tsx index aaf9dada90341..bc6223c478bf5 100644 --- a/examples/search_explorer/public/es_strategy.tsx +++ b/examples/search_explorer/public/es_strategy.tsx @@ -92,7 +92,7 @@ export class EsSearchTest extends React.Component { this.setState({ index: e.target.value, changes: true })} + onChange={(e) => this.setState({ index: e.target.value, changes: true })} /> @@ -101,7 +101,7 @@ export class EsSearchTest extends React.Component { this.setState({ query: e.target.value, changes: true })} + onChange={(e) => this.setState({ query: e.target.value, changes: true })} /> diff --git a/examples/search_explorer/public/guide_section.tsx b/examples/search_explorer/public/guide_section.tsx index 1562e33b14c2f..c13c11dc5864c 100644 --- a/examples/search_explorer/public/guide_section.tsx +++ b/examples/search_explorer/public/guide_section.tsx @@ -59,7 +59,7 @@ export class GuideSection extends React.Component { } if (props.codeSections) { - props.codeSections.forEach(section => { + props.codeSections.forEach((section) => { this.tabs.push({ name: section.title, displayName: section.title, @@ -79,7 +79,7 @@ export class GuideSection extends React.Component { }; renderTabs() { - return this.tabs.map(tab => ( + return this.tabs.map((tab) => ( this.onSelectedTabChanged(tab.name)} isSelected={tab.name === this.state.selectedTab} @@ -98,7 +98,7 @@ export class GuideSection extends React.Component { if (!this.props.codeSections) { return undefined; } - const section = this.props.codeSections.find(s => s.title === this.state.selectedTab); + const section = this.props.codeSections.find((s) => s.title === this.state.selectedTab); if (!section) { throw new Error('No section named ' + this.state.selectedTab); diff --git a/examples/state_containers_examples/public/todo/todo.tsx b/examples/state_containers_examples/public/todo/todo.tsx index 597c2b19be0f6..b6f4f6550026b 100644 --- a/examples/state_containers_examples/public/todo/todo.tsx +++ b/examples/state_containers_examples/public/todo/todo.tsx @@ -61,7 +61,7 @@ const defaultGlobalState: GlobalState = { text: '' }; const globalStateContainer = createStateContainer( defaultGlobalState, { - setText: state => text => ({ ...state, text }), + setText: (state) => (text) => ({ ...state, text }), } ); @@ -81,7 +81,7 @@ const TodoApp: React.FC = ({ filter }) => { const { text } = GlobalStateHelpers.useState(); const { edit: editTodo, delete: deleteTodo, add: addTodo } = useTransitions(); const todos = useState().todos; - const filteredTodos = todos.filter(todo => { + const filteredTodos = todos.filter((todo) => { if (!filter) return true; if (filter === 'completed') return todo.completed; if (filter === 'not-completed') return !todo.completed; @@ -111,13 +111,13 @@ const TodoApp: React.FC = ({ filter }) => {
    - {filteredTodos.map(todo => ( + {filteredTodos.map((todo) => (
  • { + onChange={(e) => { editTodo({ ...todo, completed: e.target.checked, @@ -139,7 +139,7 @@ const TodoApp: React.FC = ({ filter }) => { ))}
{ + onSubmit={(e) => { const inputRef = (e.target as HTMLFormElement).elements.namedItem( 'newTodo' ) as HTMLInputElement; @@ -147,7 +147,7 @@ const TodoApp: React.FC = ({ filter }) => { addTodo({ text: inputRef.value, completed: false, - id: todos.map(todo => todo.id).reduce((a, b) => Math.max(a, b), 0) + 1, + id: todos.map((todo) => todo.id).reduce((a, b) => Math.max(a, b), 0) + 1, }); inputRef.value = ''; e.preventDefault(); @@ -157,7 +157,7 @@ const TodoApp: React.FC = ({ filter }) => {
- setText(e.target.value)} /> + setText(e.target.value)} />
); @@ -173,7 +173,7 @@ export const TodoAppPage: React.FC<{ appTitle: string; appBasePath: string; isInitialRoute: () => boolean; -}> = props => { +}> = (props) => { const initialAppUrl = React.useRef(window.location.href); const [useHashedUrl, setUseHashedUrl] = React.useState(false); @@ -181,7 +181,7 @@ export const TodoAppPage: React.FC<{ * Replicates what src/legacy/ui/public/chrome/api/nav.ts did * Persists the url in sessionStorage and tries to restore it on "componentDidMount" */ - useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, urlToRestore => { + useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, (urlToRestore) => { // shouldRestoreUrl: // App decides if it should restore url or not // In this specific case, restore only if navigated to initial route diff --git a/examples/state_containers_examples/public/with_data_services/components/app.tsx b/examples/state_containers_examples/public/with_data_services/components/app.tsx index c820929d8a61d..baf627fd62a32 100644 --- a/examples/state_containers_examples/public/with_data_services/components/app.tsx +++ b/examples/state_containers_examples/public/with_data_services/components/app.tsx @@ -135,7 +135,7 @@ const App = ({ appStateContainer.set({ ...appState, name: e.target.value })} + onChange={(e) => appStateContainer.set({ ...appState, name: e.target.value })} aria-label="My name" /> @@ -217,7 +217,7 @@ function useAppStateSyncing( stateContainer: { ...appStateContainer, // stateSync utils requires explicit handling of default state ("null") - set: state => state && appStateContainer.set(state), + set: (state) => state && appStateContainer.set(state), }, }); diff --git a/examples/ui_actions_explorer/public/actions/actions.tsx b/examples/ui_actions_explorer/public/actions/actions.tsx index 64a820ab6d194..4ef8d5bf4d9c6 100644 --- a/examples/ui_actions_explorer/public/actions/actions.tsx +++ b/examples/ui_actions_explorer/public/actions/actions.tsx @@ -47,14 +47,14 @@ export interface PhoneContext { export const makePhoneCallAction = createAction({ type: ACTION_CALL_PHONE_NUMBER, getDisplayName: () => 'Call phone number', - execute: async context => alert(`Pretend calling ${context.phone}...`), + execute: async (context) => alert(`Pretend calling ${context.phone}...`), }); export const lookUpWeatherAction = createAction({ type: ACTION_TRAVEL_GUIDE, getIconType: () => 'popout', getDisplayName: () => 'View travel guide', - execute: async context => { + execute: async (context) => { window.open(`https://www.worldtravelguide.net/?s=${context.country}`, '_blank'); }, }); @@ -67,7 +67,7 @@ export const viewInMapsAction = createAction({ type: ACTION_VIEW_IN_MAPS, getIconType: () => 'popout', getDisplayName: () => 'View in maps', - execute: async context => { + execute: async (context) => { window.open(`https://www.google.com/maps/place/${context.country}`, '_blank'); }, }); @@ -90,7 +90,7 @@ function EditUserModal({ const [name, setName] = useState(user.name); return ( - setName(e.target.value)} /> + setName(e.target.value)} /> { update({ ...user, name }); diff --git a/examples/ui_actions_explorer/public/app.tsx b/examples/ui_actions_explorer/public/app.tsx index f08b8bb29bdd3..1b0667962a3c2 100644 --- a/examples/ui_actions_explorer/public/app.tsx +++ b/examples/ui_actions_explorer/public/app.tsx @@ -72,7 +72,7 @@ const ActionsExplorer = ({ uiActionsApi, openModal }: Props) => { from. Using the UI Action and Trigger API makes your plugin extensible by other plugins. Any actions attached to the `HELLO_WORLD_TRIGGER_ID` will show up here!

- setName(e.target.value)} /> + setName(e.target.value)} /> { diff --git a/examples/ui_actions_explorer/public/trigger_context_example.tsx b/examples/ui_actions_explorer/public/trigger_context_example.tsx index 4b88652103966..05a9895d3fac4 100644 --- a/examples/ui_actions_explorer/public/trigger_context_example.tsx +++ b/examples/ui_actions_explorer/public/trigger_context_example.tsx @@ -105,7 +105,7 @@ export function TriggerContextExample({ uiActionsApi }: Props) { ]; const updateUser = (newUser: User, oldName: string) => { - const index = rows.findIndex(u => u.name === oldName); + const index = rows.findIndex((u) => u.name === oldName); const newRows = [...rows]; newRows.splice(index, 1, createRowData(newUser, uiActionsApi, updateUser)); setRows(newRows); diff --git a/examples/url_generators_examples/public/app.tsx b/examples/url_generators_examples/public/app.tsx index c39cd876ea9b1..82f36fa13ea71 100644 --- a/examples/url_generators_examples/public/app.tsx +++ b/examples/url_generators_examples/public/app.tsx @@ -67,7 +67,7 @@ export const Routes: React.FC<{}> = () => { export const LinksExample: React.FC<{ appBasePath: string; -}> = props => { +}> = (props) => { const history = React.useMemo( () => createBrowserHistory({ diff --git a/examples/url_generators_examples/public/url_generator.ts b/examples/url_generators_examples/public/url_generator.ts index f21b1c9295e66..c74ade8bf743d 100644 --- a/examples/url_generators_examples/public/url_generator.ts +++ b/examples/url_generators_examples/public/url_generator.ts @@ -38,7 +38,7 @@ export const createHelloPageLinkGenerator = ( getStartServices: () => Promise<{ appBasePath: string }> ): UrlGeneratorsDefinition => ({ id: HELLO_URL_GENERATOR, - createUrl: async state => { + createUrl: async (state) => { const startServices = await getStartServices(); const appBasePath = startServices.appBasePath; const parsedUrl = url.parse(window.location.href); @@ -72,7 +72,7 @@ export type LegacyHelloLinkGeneratorState = UrlGeneratorState< export const helloPageLinkGeneratorV1: UrlGeneratorsDefinition = { id: HELLO_URL_GENERATOR_V1, isDeprecated: true, - migrate: async state => { + migrate: async (state) => { return { id: HELLO_URL_GENERATOR, state: { firstName: state.name, lastName: '' } }; }, }; diff --git a/examples/url_generators_explorer/public/app.tsx b/examples/url_generators_explorer/public/app.tsx index 77e804ae08c5f..50dd2e075c528 100644 --- a/examples/url_generators_explorer/public/app.tsx +++ b/examples/url_generators_explorer/public/app.tsx @@ -81,7 +81,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { const updateLinks = async () => { const updatedLinks = await Promise.all( - persistedLinks.map(async savedLink => { + persistedLinks.map(async (savedLink) => { const generator = getLinkGenerator(savedLink.id); const link = await generator.createUrl(savedLink.state); return { @@ -109,11 +109,11 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { { + onChange={(e) => { setFirstName(e.target.value); }} /> - setLastName(e.target.value)} /> + setLastName(e.target.value)} /> setPersistedLinks([ @@ -142,7 +142,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { {buildingLinks ? (
loading...
) : ( - migratedLinks.map(link => ( + migratedLinks.map((link) => ( dateMath.parse('now', { forceNow: '2000-01-01T00:00:00.000Z' }); expect(fn).to.throwError(); }); - it('should throw an Error if passed a moment', function() { + it('should throw an Error if passed a moment', function () { expect(() => dateMath.parse('now', { forceNow: moment() })).to.throwError(); }); - it('should throw an Error if passed an invalid date', function() { + it('should throw an Error if passed an invalid date', function () { expect(() => dateMath.parse('now', { forceNow: new Date('foobar') })).to.throwError(); }); }); }); - describe('objects and strings', function() { + describe('objects and strings', function () { let mmnt; let date; let string; let now; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); mmnt = moment(anchor); @@ -99,61 +99,61 @@ describe('dateMath', function() { string = mmnt.format(format); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - it('should return the same moment if passed a moment', function() { + it('should return the same moment if passed a moment', function () { expect(dateMath.parse(mmnt)).to.eql(mmnt); }); - it('should return a moment if passed a date', function() { + it('should return a moment if passed a date', function () { expect(dateMath.parse(date).format(format)).to.eql(mmnt.format(format)); }); - it('should return a moment if passed an ISO8601 string', function() { + it('should return a moment if passed an ISO8601 string', function () { expect(dateMath.parse(string).format(format)).to.eql(mmnt.format(format)); }); - it('should return the current time when parsing now', function() { + it('should return the current time when parsing now', function () { expect(dateMath.parse('now').format(format)).to.eql(now.format(format)); }); - it('should use the forceNow parameter when parsing now', function() { + it('should use the forceNow parameter when parsing now', function () { expect(dateMath.parse('now', { forceNow: anchoredDate }).valueOf()).to.eql(unix); }); }); - describe('subtraction', function() { + describe('subtraction', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - [5, 12, 247].forEach(len => { - spans.forEach(span => { + [5, 12, 247].forEach((len) => { + spans.forEach((span) => { const nowEx = `now-${len}${span}`; const thenEx = `${anchor}||-${len}${span}`; - it('should return ' + len + span + ' ago', function() { + it('should return ' + len + span + ' ago', function () { const parsed = dateMath.parse(nowEx).format(format); expect(parsed).to.eql(now.subtract(len, span).format(format)); }); - it('should return ' + len + span + ' before ' + anchor, function() { + it('should return ' + len + span + ' before ' + anchor, function () { const parsed = dateMath.parse(thenEx).format(format); expect(parsed).to.eql(anchored.subtract(len, span).format(format)); }); - it('should return ' + len + span + ' before forceNow', function() { + it('should return ' + len + span + ' before forceNow', function () { const parsed = dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf(); expect(parsed).to.eql(anchored.subtract(len, span).valueOf()); }); @@ -161,36 +161,36 @@ describe('dateMath', function() { }); }); - describe('addition', function() { + describe('addition', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - [5, 12, 247].forEach(len => { - spans.forEach(span => { + [5, 12, 247].forEach((len) => { + spans.forEach((span) => { const nowEx = `now+${len}${span}`; const thenEx = `${anchor}||+${len}${span}`; - it('should return ' + len + span + ' from now', function() { + it('should return ' + len + span + ' from now', function () { expect(dateMath.parse(nowEx).format(format)).to.eql(now.add(len, span).format(format)); }); - it('should return ' + len + span + ' after ' + anchor, function() { + it('should return ' + len + span + ' after ' + anchor, function () { expect(dateMath.parse(thenEx).format(format)).to.eql( anchored.add(len, span).format(format) ); }); - it('should return ' + len + span + ' after forceNow', function() { + it('should return ' + len + span + ' after forceNow', function () { expect(dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf()).to.eql( anchored.add(len, span).valueOf() ); @@ -199,40 +199,40 @@ describe('dateMath', function() { }); }); - describe('rounding', function() { + describe('rounding', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - spans.forEach(span => { - it(`should round now to the beginning of the ${span}`, function() { + spans.forEach((span) => { + it(`should round now to the beginning of the ${span}`, function () { expect(dateMath.parse('now/' + span).format(format)).to.eql( now.startOf(span).format(format) ); }); - it(`should round now to the beginning of forceNow's ${span}`, function() { + it(`should round now to the beginning of forceNow's ${span}`, function () { expect(dateMath.parse('now/' + span, { forceNow: anchoredDate }).valueOf()).to.eql( anchored.startOf(span).valueOf() ); }); - it(`should round now to the end of the ${span}`, function() { + it(`should round now to the end of the ${span}`, function () { expect(dateMath.parse('now/' + span, { roundUp: true }).format(format)).to.eql( now.endOf(span).format(format) ); }); - it(`should round now to the end of forceNow's ${span}`, function() { + it(`should round now to the end of forceNow's ${span}`, function () { expect( dateMath.parse('now/' + span, { roundUp: true, forceNow: anchoredDate }).valueOf() ).to.eql(anchored.endOf(span).valueOf()); @@ -240,61 +240,46 @@ describe('dateMath', function() { }); }); - describe('math and rounding', function() { + describe('math and rounding', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - it('should round to the nearest second with 0 value', function() { + it('should round to the nearest second with 0 value', function () { const val = dateMath.parse('now-0s/s').format(format); expect(val).to.eql(now.startOf('s').format(format)); }); - it('should subtract 17s, rounded to the nearest second', function() { + it('should subtract 17s, rounded to the nearest second', function () { const val = dateMath.parse('now-17s/s').format(format); - expect(val).to.eql( - now - .startOf('s') - .subtract(17, 's') - .format(format) - ); + expect(val).to.eql(now.startOf('s').subtract(17, 's').format(format)); }); - it('should add 555ms, rounded to the nearest millisecond', function() { + it('should add 555ms, rounded to the nearest millisecond', function () { const val = dateMath.parse('now+555ms/ms').format(format); - expect(val).to.eql( - now - .add(555, 'ms') - .startOf('ms') - .format(format) - ); + expect(val).to.eql(now.add(555, 'ms').startOf('ms').format(format)); }); - it('should subtract 555ms, rounded to the nearest second', function() { + it('should subtract 555ms, rounded to the nearest second', function () { const val = dateMath.parse('now-555ms/s').format(format); - expect(val).to.eql( - now - .subtract(555, 'ms') - .startOf('s') - .format(format) - ); + expect(val).to.eql(now.subtract(555, 'ms').startOf('s').format(format)); }); - it('should round weeks to Sunday by default', function() { + it('should round weeks to Sunday by default', function () { const val = dateMath.parse('now-1w/w'); expect(val.isoWeekday()).to.eql(7); }); - it('should round weeks based on the passed moment locale start of week setting', function() { + it('should round weeks based on the passed moment locale start of week setting', function () { const m = momentClone(); // Define a locale, that has Tuesday as beginning of the week m.defineLocale('x-test', { @@ -304,7 +289,7 @@ describe('dateMath', function() { expect(val.isoWeekday()).to.eql(2); }); - it('should round up weeks based on the passed moment locale start of week setting', function() { + it('should round up weeks based on the passed moment locale start of week setting', function () { const m = momentClone(); // Define a locale, that has Tuesday as beginning of the week m.defineLocale('x-test', { @@ -319,7 +304,7 @@ describe('dateMath', function() { expect(val.isoWeekday()).to.eql(3 - 1); }); - it('should round relative to forceNow', function() { + it('should round relative to forceNow', function () { const val = dateMath.parse('now-0s/s', { forceNow: anchoredDate }).valueOf(); expect(val).to.eql(anchored.startOf('s').valueOf()); }); @@ -329,15 +314,15 @@ describe('dateMath', function() { }); }); - describe('used momentjs instance', function() { - it('should use the default moment instance if parameter not specified', function() { + describe('used momentjs instance', function () { + it('should use the default moment instance if parameter not specified', function () { const momentSpy = sinon.spy(moment, 'isMoment'); dateMath.parse('now'); expect(momentSpy.called).to.be(true); momentSpy.restore(); }); - it('should not use default moment instance if parameter is specified', function() { + it('should not use default moment instance if parameter is specified', function () { const m = momentClone(); const momentSpy = sinon.spy(moment, 'isMoment'); const cloneSpy = sinon.spy(m, 'isMoment'); @@ -348,7 +333,7 @@ describe('dateMath', function() { cloneSpy.restore(); }); - it('should work with multiple different instances', function() { + it('should work with multiple different instances', function () { const m1 = momentClone(); const m2 = momentClone(); const m1Spy = sinon.spy(m1, 'isMoment'); @@ -365,7 +350,7 @@ describe('dateMath', function() { m2Spy.restore(); }); - it('should use global instance after passing an instance', function() { + it('should use global instance after passing an instance', function () { const m = momentClone(); const momentSpy = sinon.spy(moment, 'isMoment'); const cloneSpy = sinon.spy(m, 'isMoment'); @@ -382,12 +367,12 @@ describe('dateMath', function() { }); }); - describe('units', function() { - it('should have units descending for unitsDesc', function() { + describe('units', function () { + it('should have units descending for unitsDesc', function () { expect(dateMath.unitsDesc).to.eql(['y', 'M', 'w', 'd', 'h', 'm', 's', 'ms']); }); - it('should have units ascending for unitsAsc', function() { + it('should have units ascending for unitsAsc', function () { expect(dateMath.unitsAsc).to.eql(['ms', 's', 'm', 'h', 'd', 'w', 'M', 'y']); }); }); diff --git a/packages/elastic-datemath/src/index.js b/packages/elastic-datemath/src/index.js index afedad3ef6f72..52ce12ddf7027 100644 --- a/packages/elastic-datemath/src/index.js +++ b/packages/elastic-datemath/src/index.js @@ -34,9 +34,9 @@ const units = Object.keys(unitsMap).sort((a, b) => unitsMap[b].weight - unitsMap const unitsDesc = [...units]; const unitsAsc = [...units].reverse(); -const isDate = d => Object.prototype.toString.call(d) === '[object Date]'; +const isDate = (d) => Object.prototype.toString.call(d) === '[object Date]'; -const isValidDate = d => isDate(d) && !isNaN(d.valueOf()); +const isValidDate = (d) => isDate(d) && !isNaN(d.valueOf()); /* * This is a simplified version of elasticsearch's date parser. diff --git a/packages/kbn-analytics/scripts/build.js b/packages/kbn-analytics/scripts/build.js index bb28c1460c9c2..448d1ca9332f2 100644 --- a/packages/kbn-analytics/scripts/build.js +++ b/packages/kbn-analytics/scripts/build.js @@ -31,7 +31,7 @@ const padRight = (width, str) => run( async ({ log, flags }) => { - await withProcRunner(log, async proc => { + await withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -43,7 +43,7 @@ run( log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); await Promise.all([ - ...['web', 'node'].map(subTask => + ...['web', 'node'].map((subTask) => proc.run(padRight(10, `babel:${subTask}`), { cmd: 'babel', args: [ diff --git a/packages/kbn-analytics/src/report.ts b/packages/kbn-analytics/src/report.ts index 58891e48aa3a6..d9303d2d3af1d 100644 --- a/packages/kbn-analytics/src/report.ts +++ b/packages/kbn-analytics/src/report.ts @@ -86,7 +86,7 @@ export class ReportManager { }; } assignReports(newMetrics: Metric | Metric[]) { - wrapArray(newMetrics).forEach(newMetric => this.assignReport(this.report, newMetric)); + wrapArray(newMetrics).forEach((newMetric) => this.assignReport(this.report, newMetric)); return { report: this.report }; } static createMetricKey(metric: Metric): string { diff --git a/packages/kbn-analytics/src/reporter.ts b/packages/kbn-analytics/src/reporter.ts index cbcdf6af63052..b20ddc0e58ba7 100644 --- a/packages/kbn-analytics/src/reporter.ts +++ b/packages/kbn-analytics/src/reporter.ts @@ -115,7 +115,7 @@ export class Reporter { eventNames: string | string[], count?: number ) => { - const metrics = wrapArray(eventNames).map(eventName => { + const metrics = wrapArray(eventNames).map((eventName) => { this.log(`${type} Metric -> (${appName}:${eventName}):`); const report = createUiStatsMetric({ type, appName, eventName, count }); this.log(report); diff --git a/packages/kbn-babel-code-parser/src/code_parser.js b/packages/kbn-babel-code-parser/src/code_parser.js index 9431eb639e2e5..91927780363ac 100644 --- a/packages/kbn-babel-code-parser/src/code_parser.js +++ b/packages/kbn-babel-code-parser/src/code_parser.js @@ -79,7 +79,7 @@ export async function parseEntries(cwd, entries, strategy, results, wasParsed = const sanitizedCwd = cwd || process.cwd(); // Test each entry against canRequire function - const entriesQueue = entries.map(entry => canRequire(entry)); + const entriesQueue = entries.map((entry) => canRequire(entry)); while (entriesQueue.length) { // Get the first element in the queue as diff --git a/packages/kbn-babel-code-parser/src/strategies.js b/packages/kbn-babel-code-parser/src/strategies.js index f116abde9e0e6..2369692ad434b 100644 --- a/packages/kbn-babel-code-parser/src/strategies.js +++ b/packages/kbn-babel-code-parser/src/strategies.js @@ -59,7 +59,7 @@ export async function dependenciesParseStrategy( // Get dependencies from a single file and filter // out node native modules from the result const dependencies = (await parseSingleFile(mainEntry, dependenciesVisitorsGenerator)).filter( - dep => !builtinModules.includes(dep) + (dep) => !builtinModules.includes(dep) ); // Return the list of all the new entries found into diff --git a/packages/kbn-babel-code-parser/src/strategies.test.js b/packages/kbn-babel-code-parser/src/strategies.test.js index dc2c599e81c39..e61c784cdcd54 100644 --- a/packages/kbn-babel-code-parser/src/strategies.test.js +++ b/packages/kbn-babel-code-parser/src/strategies.test.js @@ -84,7 +84,7 @@ describe('Code Parser Strategies', () => { cb(null, `require('./relative_dep')`); }); - canRequire.mockImplementation(entry => { + canRequire.mockImplementation((entry) => { if (entry === `${mockCwd}dep1/relative_dep`) { return `${entry}/index.js`; } diff --git a/packages/kbn-babel-code-parser/src/visitors.js b/packages/kbn-babel-code-parser/src/visitors.js index 30014941d2a27..b159848d424fa 100644 --- a/packages/kbn-babel-code-parser/src/visitors.js +++ b/packages/kbn-babel-code-parser/src/visitors.js @@ -21,7 +21,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on require + require.resolve CallExpression: ({ node }) => { // AST check for require expressions - const isRequire = node => { + const isRequire = (node) => { return matches({ callee: { type: 'Identifier', @@ -31,7 +31,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { }; // AST check for require.resolve expressions - const isRequireResolve = node => { + const isRequireResolve = (node) => { return matches({ callee: { type: 'MemberExpression', @@ -66,7 +66,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on import ImportDeclaration: ({ node }) => { // AST check for supported import expressions - const isImport = node => { + const isImport = (node) => { return matches({ type: 'ImportDeclaration', source: { @@ -85,7 +85,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on export from ExportNamedDeclaration: ({ node }) => { // AST check for supported export from expressions - const isExportFrom = node => { + const isExportFrom = (node) => { return matches({ type: 'ExportNamedDeclaration', source: { @@ -104,7 +104,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on export * from ExportAllDeclaration: ({ node }) => { // AST check for supported export * from expressions - const isExportAllFrom = node => { + const isExportAllFrom = (node) => { return matches({ type: 'ExportAllDeclaration', source: { diff --git a/packages/kbn-babel-code-parser/src/visitors.test.js b/packages/kbn-babel-code-parser/src/visitors.test.js index 6a29d144a4dee..d2704fa9dfb72 100644 --- a/packages/kbn-babel-code-parser/src/visitors.test.js +++ b/packages/kbn-babel-code-parser/src/visitors.test.js @@ -21,7 +21,7 @@ import * as parser from '@babel/parser'; import traverse from '@babel/traverse'; import { dependenciesVisitorsGenerator } from './visitors'; -const visitorsApplier = code => { +const visitorsApplier = (code) => { const result = []; traverse( parser.parse(code, { diff --git a/packages/kbn-config-schema/src/errors/schema_error.test.ts b/packages/kbn-config-schema/src/errors/schema_error.test.ts index 0f632b781e9a6..d5cbb5a718a6a 100644 --- a/packages/kbn-config-schema/src/errors/schema_error.test.ts +++ b/packages/kbn-config-schema/src/errors/schema_error.test.ts @@ -26,8 +26,8 @@ import { SchemaError } from '.'; export const cleanStack = (stack: string) => stack .split('\n') - .filter(line => !line.includes('node_modules/') && !line.includes('internal/')) - .map(line => { + .filter((line) => !line.includes('node_modules/') && !line.includes('internal/')) + .map((line) => { const parts = /.*\((.*)\).?/.exec(line) || []; if (parts.length === 0) { diff --git a/packages/kbn-config-schema/src/errors/validation_error.ts b/packages/kbn-config-schema/src/errors/validation_error.ts index 2a4f887bc4349..0c86b61ba1e2a 100644 --- a/packages/kbn-config-schema/src/errors/validation_error.ts +++ b/packages/kbn-config-schema/src/errors/validation_error.ts @@ -26,12 +26,12 @@ export class ValidationError extends SchemaError { let message = error.message; if (error instanceof SchemaTypesError) { const indentLevel = level || 0; - const childErrorMessages = error.errors.map(childError => + const childErrorMessages = error.errors.map((childError) => ValidationError.extractMessage(childError, namespace, indentLevel + 1) ); message = `${message}\n${childErrorMessages - .map(childErrorMessage => `${' '.repeat(indentLevel)}- ${childErrorMessage}`) + .map((childErrorMessage) => `${' '.repeat(indentLevel)}- ${childErrorMessage}`) .join('\n')}`; } diff --git a/packages/kbn-config-schema/src/internals/index.ts b/packages/kbn-config-schema/src/internals/index.ts index f84e14d2f741d..f3756aaf90793 100644 --- a/packages/kbn-config-schema/src/internals/index.ts +++ b/packages/kbn-config-schema/src/internals/index.ts @@ -42,9 +42,7 @@ function isMap(o: any): o is Map { const anyCustomRule: Rules = { name: 'custom', params: { - validator: Joi.func() - .maxArity(1) - .required(), + validator: Joi.func().maxArity(1).required(), }, validate(params, value, state, options) { let validationResultMessage; diff --git a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts index e0ef3835ca0a3..485251055d2b8 100644 --- a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts +++ b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts @@ -47,7 +47,7 @@ describe('isConfigSchema', () => { expect(isConfigSchema(undefined)).toBe(false); expect(isConfigSchema([1, 2, 3])).toBe(false); expect(isConfigSchema({ foo: 'bar' })).toBe(false); - expect(isConfigSchema(function() {})).toBe(false); + expect(isConfigSchema(function () {})).toBe(false); }); it('returns true as long as `__isKbnConfigSchemaType` is true', () => { diff --git a/packages/kbn-config-schema/src/types/array_type.ts b/packages/kbn-config-schema/src/types/array_type.ts index 0df0d44a37951..2fe1fa24222a1 100644 --- a/packages/kbn-config-schema/src/types/array_type.ts +++ b/packages/kbn-config-schema/src/types/array_type.ts @@ -28,10 +28,7 @@ export type ArrayOptions = TypeOptions & { export class ArrayType extends Type { constructor(type: Type, options: ArrayOptions = {}) { - let schema = internals - .array() - .items(type.getSchema().optional()) - .sparse(false); + let schema = internals.array().items(type.getSchema().optional()).sparse(false); if (options.minSize !== undefined) { schema = schema.min(options.minSize); diff --git a/packages/kbn-config-schema/src/types/string_type.ts b/packages/kbn-config-schema/src/types/string_type.ts index 7f49440b8d7e2..cb780bcbbc6bd 100644 --- a/packages/kbn-config-schema/src/types/string_type.ts +++ b/packages/kbn-config-schema/src/types/string_type.ts @@ -36,14 +36,14 @@ export class StringType extends Type { let schema = options.hostname === true ? internals.string().hostname() - : internals.any().custom(value => { + : internals.any().custom((value) => { if (typeof value !== 'string') { return `expected value of type [string] but got [${typeDetect(value)}]`; } }); if (options.minLength !== undefined) { - schema = schema.custom(value => { + schema = schema.custom((value) => { if (value.length < options.minLength!) { return `value has length [${value.length}] but it must have a minimum length of [${options.minLength}].`; } @@ -51,7 +51,7 @@ export class StringType extends Type { } if (options.maxLength !== undefined) { - schema = schema.custom(value => { + schema = schema.custom((value) => { if (value.length > options.maxLength!) { return `value has length [${value.length}] but it must have a maximum length of [${options.maxLength}].`; } diff --git a/packages/kbn-config-schema/src/types/union_type.ts b/packages/kbn-config-schema/src/types/union_type.ts index f4de829204e80..80fa8443e75d0 100644 --- a/packages/kbn-config-schema/src/types/union_type.ts +++ b/packages/kbn-config-schema/src/types/union_type.ts @@ -24,7 +24,7 @@ import { Type, TypeOptions } from './type'; export class UnionType>, T> extends Type { constructor(types: RTS, options?: TypeOptions) { - const schema = internals.alternatives(types.map(type => type.getSchema())); + const schema = internals.alternatives(types.map((type) => type.getSchema())); super(schema, options); } diff --git a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts index 4e91289610432..b38a27fdc1b48 100644 --- a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts +++ b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts @@ -145,7 +145,7 @@ export class CiStatsReporter { `failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds` ); - await new Promise(resolve => setTimeout(resolve, attempt * 1000)); + await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); } } } diff --git a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts index 4244006f4a3a3..ea4159de55749 100644 --- a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts +++ b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts @@ -66,7 +66,7 @@ export interface ReqOptions { } const delay = (ms: number) => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, ms); }); diff --git a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts index 1a292aff303af..4951bef91c446 100644 --- a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts +++ b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts @@ -33,7 +33,7 @@ export function observeReadable(readable: Readable): Rx.Observable { Rx.fromEvent(readable, 'error').pipe( first(), - mergeMap(err => Rx.throwError(err)) + mergeMap((err) => Rx.throwError(err)) ) ); } diff --git a/packages/kbn-dev-utils/src/proc_runner/proc.ts b/packages/kbn-dev-utils/src/proc_runner/proc.ts index c899293191f2a..59512cbb133b3 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc.ts @@ -118,7 +118,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) { // observe first error event Rx.fromEvent(childProcess, 'error').pipe( take(1), - mergeMap(err => Rx.throwError(err)) + mergeMap((err) => Rx.throwError(err)) ) ).pipe(share()); @@ -126,7 +126,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) { observeLines(childProcess.stdout), observeLines(childProcess.stderr) ).pipe( - tap(line => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)), + tap((line) => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)), share() ); diff --git a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts index 1759ca2840c5b..c879b4595b451 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts @@ -50,7 +50,7 @@ export class ProcRunner { constructor(private log: ToolingLog) { this.signalUnsubscribe = exitHook(() => { - this.teardown().catch(error => { + this.teardown().catch((error) => { log.error(`ProcRunner teardown error: ${error.stack}`); }); }); @@ -105,9 +105,9 @@ export class ProcRunner { // wait for process to log matching line await Rx.race( proc.lines$.pipe( - filter(line => wait.test(line)), + filter((line) => wait.test(line)), first(), - catchError(err => { + catchError((err) => { if (err.name !== 'EmptyError') { throw createCliError(`[${name}] exited without matching pattern: ${wait}`); } else { @@ -159,7 +159,7 @@ export class ProcRunner { * @return {Promise} */ async waitForAllToStop() { - await Promise.all(this.procs.map(proc => proc.outcomePromise)); + await Promise.all(this.procs.map((proc) => proc.outcomePromise)); } /** @@ -181,19 +181,19 @@ export class ProcRunner { this.log.warning( '%d processes left running, stop them with procs.stop(name):', this.procs.length, - this.procs.map(proc => proc.name) + this.procs.map((proc) => proc.name) ); } await Promise.all( - this.procs.map(async proc => { + this.procs.map(async (proc) => { await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); }) ); } private getProc(name: string) { - return this.procs.find(proc => { + return this.procs.find((proc) => { return proc.name === name; }); } @@ -209,14 +209,14 @@ export class ProcRunner { // tie into proc outcome$, remove from _procs on compete proc.outcome$.subscribe({ - next: code => { + next: (code) => { const duration = moment.duration(Date.now() - startMs); this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); }, complete: () => { remove(); }, - error: error => { + error: (error) => { if (this.closing) { this.log.error(error); } diff --git a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts index e37bdcc40ca1c..89127069f4b8d 100644 --- a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts +++ b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts @@ -22,14 +22,14 @@ import { withProcRunner } from './with_proc_runner'; import { ProcRunner } from './proc_runner'; it('passes proc runner to a function', async () => { - await withProcRunner(new ToolingLog(), async proc => { + await withProcRunner(new ToolingLog(), async (proc) => { expect(proc).toBeInstanceOf(ProcRunner); }); }); it('calls procRunner.teardown() if function returns synchronously', async () => { let teardownSpy; - await withProcRunner(new ToolingLog(), async proc => { + await withProcRunner(new ToolingLog(), async (proc) => { teardownSpy = jest.spyOn(proc, 'teardown'); }); @@ -41,7 +41,7 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects let teardownSpy; await expect( - withProcRunner(new ToolingLog(), async proc => { + withProcRunner(new ToolingLog(), async (proc) => { teardownSpy = jest.spyOn(proc, 'teardown'); throw error; }) @@ -53,8 +53,8 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects it('waits for promise to resolve before tearing down proc', async () => { let teardownSpy; - await withProcRunner(new ToolingLog(), async proc => { - await new Promise(resolve => setTimeout(resolve, 500)); + await withProcRunner(new ToolingLog(), async (proc) => { + await new Promise((resolve) => setTimeout(resolve, 500)); teardownSpy = jest.spyOn(proc, 'teardown'); }); @@ -67,8 +67,8 @@ it('waits for promise to reject before tearing down proc and rejecting with the let teardownSpy; await expect( - withProcRunner(new ToolingLog(), async proc => { - await new Promise(resolve => setTimeout(resolve, 500)); + withProcRunner(new ToolingLog(), async (proc) => { + await new Promise((resolve) => setTimeout(resolve, 500)); teardownSpy = jest.spyOn(proc, 'teardown'); throw error; }) diff --git a/packages/kbn-dev-utils/src/run/fail.ts b/packages/kbn-dev-utils/src/run/fail.ts index a2501fc9513bf..f10ef1d52ef04 100644 --- a/packages/kbn-dev-utils/src/run/fail.ts +++ b/packages/kbn-dev-utils/src/run/fail.ts @@ -61,7 +61,7 @@ export function combineErrors(errors: Array) { .filter(isFailError) .reduce((acc, error) => Math.max(acc, error.exitCode), 1); - const showHelp = errors.some(error => isFailError(error) && error.showHelp); + const showHelp = errors.some((error) => isFailError(error) && error.showHelp); const message = errors.reduce((acc, error) => { if (isFailError(error)) { diff --git a/packages/kbn-dev-utils/src/run/run.ts b/packages/kbn-dev-utils/src/run/run.ts index 35477e988d837..894db0d3fdadb 100644 --- a/packages/kbn-dev-utils/src/run/run.ts +++ b/packages/kbn-dev-utils/src/run/run.ts @@ -62,7 +62,7 @@ export async function run(fn: RunFn, options: Options = {}) { writeTo: process.stdout, }); - process.on('unhandledRejection', error => { + process.on('unhandledRejection', (error) => { log.error('UNHANDLED PROMISE REJECTION'); log.error( error instanceof Error @@ -110,7 +110,7 @@ export async function run(fn: RunFn, options: Options = {}) { } try { - await withProcRunner(log, async procRunner => { + await withProcRunner(log, async (procRunner) => { await fn({ log, flags, diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts index 21f02325cac66..4a0f5ca5f8a5f 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts @@ -80,29 +80,31 @@ describe('#indent()', () => { }); }); -(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(method => { - describe(`#${method}()`, () => { - it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => { - const log = new ToolingLog(); - const writeA = jest.fn(); - const writeB = jest.fn(); - - log.setWriters([{ write: writeA }, { write: writeB }]); - - if (method === 'error') { - const error = new Error('error message'); - error.stack = '... stack trace ...'; - log.error(error); - log.error('string message'); - } else { - log[method]('foo', 'bar', 'baz'); - } - - expect(writeA.mock.calls).toMatchSnapshot(); - expect(writeA.mock.calls).toEqual(writeB.mock.calls); +(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach( + (method) => { + describe(`#${method}()`, () => { + it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => { + const log = new ToolingLog(); + const writeA = jest.fn(); + const writeB = jest.fn(); + + log.setWriters([{ write: writeA }, { write: writeB }]); + + if (method === 'error') { + const error = new Error('error message'); + error.stack = '... stack trace ...'; + log.error(error); + log.error('string message'); + } else { + log[method]('foo', 'bar', 'baz'); + } + + expect(writeA.mock.calls).toMatchSnapshot(); + expect(writeA.mock.calls).toEqual(writeB.mock.calls); + }); }); - }); -}); + } +); describe('#getWritten$()', () => { async function testWrittenMsgs(writers: Writer[]) { @@ -110,10 +112,7 @@ describe('#getWritten$()', () => { log.setWriters(writers); const done$ = new Rx.Subject(); - const promise = log - .getWritten$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = log.getWritten$().pipe(takeUntil(done$), toArray()).toPromise(); log.debug('foo'); log.info('bar'); diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts index 46026bdc369d4..7e79077032156 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts @@ -26,7 +26,7 @@ export class ToolingLogCollectingWriter extends ToolingLogTextWriter { super({ level: 'verbose', writeTo: { - write: msg => { + write: (msg) => { // trim trailing new line this.messages.push(msg.slice(0, -1)); }, diff --git a/packages/kbn-es/src/artifact.js b/packages/kbn-es/src/artifact.js index 83dcd1cf36d2e..7d4c7a3fd2c33 100644 --- a/packages/kbn-es/src/artifact.js +++ b/packages/kbn-es/src/artifact.js @@ -60,7 +60,7 @@ async function retry(log, fn) { } log.warning('...failure, retrying in 5 seconds:', error.message); - await new Promise(resolve => setTimeout(resolve, 5000)); + await new Promise((resolve) => setTimeout(resolve, 5000)); log.info('...retrying'); return await doAttempt(attempt + 1); } @@ -120,7 +120,7 @@ async function getArtifactSpecForSnapshot(urlVersion, license, log) { const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64'; const archive = manifest.archives.find( - archive => + (archive) => archive.version === desiredVersion && archive.platform === platform && archive.license === desiredLicense && diff --git a/packages/kbn-es/src/artifact.test.js b/packages/kbn-es/src/artifact.test.js index 02e4d5318f63f..bbcf664006046 100644 --- a/packages/kbn-es/src/artifact.test.js +++ b/packages/kbn-es/src/artifact.test.js @@ -52,14 +52,14 @@ const createArchive = (params = {}) => { }; }; -const mockFetch = mock => +const mockFetch = (mock) => fetch.mockReturnValue(Promise.resolve(new Response(JSON.stringify(mock)))); const previousEnvVars = {}; const ENV_VARS_TO_RESET = ['ES_SNAPSHOT_MANIFEST', 'KBN_ES_SNAPSHOT_USE_UNVERIFIED']; beforeAll(() => { - ENV_VARS_TO_RESET.forEach(key => { + ENV_VARS_TO_RESET.forEach((key) => { if (key in process.env) { previousEnvVars[key] = process.env[key]; delete process.env[key]; @@ -68,7 +68,7 @@ beforeAll(() => { }); afterAll(() => { - Object.keys(previousEnvVars).forEach(key => { + Object.keys(previousEnvVars).forEach((key) => { process.env[key] = previousEnvVars[key]; }); }); diff --git a/packages/kbn-es/src/cli.js b/packages/kbn-es/src/cli.js index ed81e01ccf8ab..61019d27bf383 100644 --- a/packages/kbn-es/src/cli.js +++ b/packages/kbn-es/src/cli.js @@ -26,7 +26,7 @@ const { log } = require('./utils'); function help() { const availableCommands = Object.keys(commands).map( - name => `${name} - ${commands[name].description}` + (name) => `${name} - ${commands[name].description}` ); console.log(dedent` diff --git a/packages/kbn-es/src/cluster.js b/packages/kbn-es/src/cluster.js index ceb4a5b6aece1..68bcc37c65600 100644 --- a/packages/kbn-es/src/cluster.js +++ b/packages/kbn-es/src/cluster.js @@ -40,8 +40,8 @@ const readFile = util.promisify(fs.readFile); // listen to data on stream until map returns anything but undefined const first = (stream, map) => - new Promise(resolve => { - const onData = data => { + new Promise((resolve) => { + const onData = (data) => { const result = map(data); if (result !== undefined) { resolve(result); @@ -180,7 +180,7 @@ exports.Cluster = class Cluster { await Promise.race([ // wait for native realm to be setup and es to be started Promise.all([ - first(this._process.stdout, data => { + first(this._process.stdout, (data) => { if (/started/.test(data)) { return true; } @@ -207,7 +207,7 @@ exports.Cluster = class Cluster { this._exec(installPath, options); // log native realm setup errors so they aren't uncaught - this._nativeRealmSetup.catch(error => { + this._nativeRealmSetup.catch((error) => { this._log.error(error); this.stop(); }); @@ -287,7 +287,7 @@ exports.Cluster = class Cluster { }); // parse log output to find http port - const httpPort = first(this._process.stdout, data => { + const httpPort = first(this._process.stdout, (data) => { const match = data.toString('utf8').match(/HttpServer.+publish_address {[0-9.]+:([0-9]+)/); if (match) { @@ -296,7 +296,7 @@ exports.Cluster = class Cluster { }); // once the http port is available setup the native realm - this._nativeRealmSetup = httpPort.then(async port => { + this._nativeRealmSetup = httpPort.then(async (port) => { const caCert = await this._caCertPromise; const nativeRealm = new NativeRealm({ port, @@ -309,19 +309,19 @@ exports.Cluster = class Cluster { }); // parse and forward es stdout to the log - this._process.stdout.on('data', data => { + this._process.stdout.on('data', (data) => { const lines = parseEsLog(data.toString()); - lines.forEach(line => { + lines.forEach((line) => { this._log.info(line.formattedMessage); }); }); // forward es stderr to the log - this._process.stderr.on('data', data => this._log.error(chalk.red(data.toString()))); + this._process.stderr.on('data', (data) => this._log.error(chalk.red(data.toString()))); // observe the exit code of the process and reflect in _outcome promies - const exitCode = new Promise(resolve => this._process.once('exit', resolve)); - this._outcome = exitCode.then(code => { + const exitCode = new Promise((resolve) => this._process.once('exit', resolve)); + this._outcome = exitCode.then((code) => { if (this._stopCalled) { return; } diff --git a/packages/kbn-es/src/errors.js b/packages/kbn-es/src/errors.js index 099b5214bcbdb..7b39251f1327c 100644 --- a/packages/kbn-es/src/errors.js +++ b/packages/kbn-es/src/errors.js @@ -17,12 +17,12 @@ * under the License. */ -exports.createCliError = function(message) { +exports.createCliError = function (message) { const error = new Error(message); error.isCliError = true; return error; }; -exports.isCliError = function(error) { +exports.isCliError = function (error) { return error && error.isCliError; }; diff --git a/packages/kbn-es/src/install/source.js b/packages/kbn-es/src/install/source.js index e78e9f1ff4b25..bfeff736f8cdc 100644 --- a/packages/kbn-es/src/install/source.js +++ b/packages/kbn-es/src/install/source.js @@ -99,15 +99,11 @@ async function sourceInfo(cwd, license, log = defaultLog) { etag.update(sha); // for changed files, use last modified times in hash calculation - status.files.forEach(file => { + status.files.forEach((file) => { etag.update(fs.statSync(path.join(cwd, file.path)).mtime.toString()); }); - const cwdHash = crypto - .createHash('md5') - .update(cwd) - .digest('hex') - .substr(0, 8); + const cwdHash = crypto.createHash('md5').update(cwd).digest('hex').substr(0, 8); const basename = `${branch}-${task}-${cwdHash}`; const filename = `${basename}.${ext}`; diff --git a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js index d374abe5db068..b860664443d1a 100644 --- a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js +++ b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js @@ -71,7 +71,7 @@ const delayServerClose = () => { server.on('request', delayServerClose); server.on('listening', delayServerClose); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', function () { const { port, address: hostname } = server.address(); serverUrl = new URL( formatUrl({ diff --git a/packages/kbn-es/src/integration_tests/cluster.test.js b/packages/kbn-es/src/integration_tests/cluster.test.js index dfbc04477bd40..0ae0ac0aac27a 100644 --- a/packages/kbn-es/src/integration_tests/cluster.test.js +++ b/packages/kbn-es/src/integration_tests/cluster.test.js @@ -37,7 +37,7 @@ jest.mock('../utils/extract_config_files', () => ({ const log = new ToolingLog(); function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } async function ensureNoResolve(promise) { @@ -77,7 +77,7 @@ function mockEsBin({ exitCode, start }) { beforeEach(() => { jest.resetAllMocks(); - extractConfigFiles.mockImplementation(config => config); + extractConfigFiles.mockImplementation((config) => config); }); describe('#installSource()', () => { @@ -85,7 +85,7 @@ describe('#installSource()', () => { let resolveInstallSource; installSource.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallSource = () => { resolve({ installPath: 'foo' }); }; @@ -124,7 +124,7 @@ describe('#installSnapshot()', () => { let resolveInstallSnapshot; installSnapshot.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallSnapshot = () => { resolve({ installPath: 'foo' }); }; @@ -163,7 +163,7 @@ describe('#installArchive(path)', () => { let resolveInstallArchive; installArchive.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallArchive = () => { resolve({ installPath: 'foo' }); }; diff --git a/packages/kbn-es/src/settings.ts b/packages/kbn-es/src/settings.ts index 58eedff207b4d..bf7160b9fee7b 100644 --- a/packages/kbn-es/src/settings.ts +++ b/packages/kbn-es/src/settings.ts @@ -25,7 +25,7 @@ const SECURE_SETTINGS_LIST = [ ]; function isSecureSetting(settingName: string) { - return SECURE_SETTINGS_LIST.some(secureSettingNameRegex => + return SECURE_SETTINGS_LIST.some((secureSettingNameRegex) => secureSettingNameRegex.test(settingName) ); } diff --git a/packages/kbn-es/src/utils/build_snapshot.js b/packages/kbn-es/src/utils/build_snapshot.js index 3173df700e303..ce0dc88ac1d7c 100644 --- a/packages/kbn-es/src/utils/build_snapshot.js +++ b/packages/kbn-es/src/utils/build_snapshot.js @@ -25,7 +25,7 @@ const { createCliError } = require('../errors'); const { findMostRecentlyChanged } = require('../utils'); const { GRADLE_BIN } = require('../paths'); -const onceEvent = (emitter, event) => new Promise(resolve => emitter.once(event, resolve)); +const onceEvent = (emitter, event) => new Promise((resolve) => emitter.once(event, resolve)); /** * Creates archive from source @@ -59,13 +59,13 @@ exports.buildSnapshot = async ({ license, sourcePath, log, platform = os.platfor const stdout = readline.createInterface({ input: build.stdout }); const stderr = readline.createInterface({ input: build.stderr }); - stdout.on('line', line => log.debug(line)); - stderr.on('line', line => log.error(line)); + stdout.on('line', (line) => log.debug(line)); + stderr.on('line', (line) => log.error(line)); const [exitCode] = await Promise.all([ Promise.race([ onceEvent(build, 'exit'), - onceEvent(build, 'error').then(error => { + onceEvent(build, 'error').then((error) => { throw createCliError(`Error spawning gradle: ${error.message}`); }), ]), diff --git a/packages/kbn-es/src/utils/decompress.js b/packages/kbn-es/src/utils/decompress.js index b4299594c5062..1fdb647b1dc0d 100644 --- a/packages/kbn-es/src/utils/decompress.js +++ b/packages/kbn-es/src/utils/decompress.js @@ -50,15 +50,12 @@ function decompressZip(input, output) { resolve(); }); - zipfile.on('error', err => { + zipfile.on('error', (err) => { reject(err); }); - zipfile.on('entry', entry => { - const zipPath = entry.fileName - .split(/\/|\\/) - .slice(1) - .join(path.sep); + zipfile.on('entry', (entry) => { + const zipPath = entry.fileName.split(/\/|\\/).slice(1).join(path.sep); const fileName = path.resolve(output, zipPath); if (/\/$/.test(entry.fileName)) { @@ -83,7 +80,7 @@ function decompressZip(input, output) { }); } -exports.decompress = async function(input, output) { +exports.decompress = async function (input, output) { const ext = path.extname(input); switch (path.extname(input)) { diff --git a/packages/kbn-es/src/utils/extract_config_files.js b/packages/kbn-es/src/utils/extract_config_files.js index a8a44a149e9b3..d535528cef239 100644 --- a/packages/kbn-es/src/utils/extract_config_files.js +++ b/packages/kbn-es/src/utils/extract_config_files.js @@ -32,7 +32,7 @@ exports.extractConfigFiles = function extractConfigFiles(config, dest, options = const originalConfig = typeof config === 'string' ? [config] : config; const localConfig = []; - originalConfig.forEach(prop => { + originalConfig.forEach((prop) => { const [key, value] = prop.split('='); if (isFile(value)) { diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.js b/packages/kbn-es/src/utils/find_most_recently_changed.js index 0fcd87978c357..3ba8865e88d92 100644 --- a/packages/kbn-es/src/utils/find_most_recently_changed.js +++ b/packages/kbn-es/src/utils/find_most_recently_changed.js @@ -32,7 +32,7 @@ exports.findMostRecentlyChanged = function findMostRecentlyChanged(pattern) { throw new TypeError(`Pattern must be absolute, got ${pattern}`); } - const ctime = path => fs.statSync(path).ctime.getTime(); + const ctime = (path) => fs.statSync(path).ctime.getTime(); return glob .sync(pattern) diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.test.js b/packages/kbn-es/src/utils/find_most_recently_changed.test.js index ed90576990c72..ee032686bc621 100644 --- a/packages/kbn-es/src/utils/find_most_recently_changed.test.js +++ b/packages/kbn-es/src/utils/find_most_recently_changed.test.js @@ -18,7 +18,7 @@ */ jest.mock('fs', () => ({ - statSync: jest.fn().mockImplementation(path => { + statSync: jest.fn().mockImplementation((path) => { if (path.includes('oldest')) { return { ctime: new Date(2018, 2, 1), diff --git a/packages/kbn-es/src/utils/native_realm.js b/packages/kbn-es/src/utils/native_realm.js index f3f5f7bbdf431..573944a8cc6d0 100644 --- a/packages/kbn-es/src/utils/native_realm.js +++ b/packages/kbn-es/src/utils/native_realm.js @@ -77,7 +77,7 @@ exports.NativeRealm = class NativeRealm { const reservedUsers = await this.getReservedUsers(); await Promise.all( - reservedUsers.map(async user => { + reservedUsers.map(async (user) => { await this.setPassword(user, options[`password.${user}`]); }) ); @@ -87,7 +87,7 @@ exports.NativeRealm = class NativeRealm { return await this._autoRetry(async () => { const resp = await this._client.security.getUser(); const usernames = Object.keys(resp.body).filter( - user => resp.body[user].metadata._reserved === true + (user) => resp.body[user].metadata._reserved === true ); if (!usernames?.length) { @@ -125,7 +125,7 @@ exports.NativeRealm = class NativeRealm { const sec = 1.5 * attempt; this._log.warning(`assuming ES isn't initialized completely, trying again in ${sec} seconds`); - await new Promise(resolve => setTimeout(resolve, sec * 1000)); + await new Promise((resolve) => setTimeout(resolve, sec * 1000)); return await this._autoRetry(fn, attempt + 1); } } diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js index e26660f76a550..8472aaf0fc029 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js @@ -31,6 +31,6 @@ // const PATH_IMPORT_RE = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/; -exports.getIsPathRequest = function(source) { +exports.getIsPathRequest = function (source) { return PATH_IMPORT_RE.test(source); }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js index 93c0f907d628d..3856281d15320 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js @@ -26,7 +26,7 @@ const DEFAULT_PLUGIN_PATH = '../..'; /* * Resolves the path to Kibana, either from default setting or config */ -exports.getKibanaPath = function(config, projectRoot) { +exports.getKibanaPath = function (config, projectRoot) { const inConfig = config != null && config.kibanaPath; // We only allow `.` in the config as we need it for Kibana itself diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js index 3fb5b5dab7776..445a3cad385fc 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js @@ -49,10 +49,10 @@ function getPathType(path) { return type; } -exports.isDirectory = function(path) { +exports.isDirectory = function (path) { return getPathType(path) === DIR; }; -exports.isFile = function(path) { +exports.isFile = function (path) { return getPathType(path) === FILE; }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js index 319b959883a8a..84481783b22fc 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js @@ -21,8 +21,8 @@ const { dirname, resolve } = require('path'); const glob = require('glob-all'); -exports.getPlugins = function(config, kibanaPath, projectRoot) { - const resolveToRoot = path => resolve(projectRoot, path); +exports.getPlugins = function (config, kibanaPath, projectRoot) { + const resolveToRoot = (path) => resolve(projectRoot, path); const pluginDirs = [ ...(config.pluginDirs || []).map(resolveToRoot), @@ -39,11 +39,11 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) { ]; const globPatterns = [ - ...pluginDirs.map(dir => resolve(dir, '*/package.json')), - ...pluginPaths.map(path => resolve(path, 'package.json')), + ...pluginDirs.map((dir) => resolve(dir, '*/package.json')), + ...pluginPaths.map((path) => resolve(path, 'package.json')), ]; - const pluginsFromMap = Object.keys(config.pluginMap || {}).map(name => { + const pluginsFromMap = Object.keys(config.pluginMap || {}).map((name) => { const directory = resolveToRoot(config.pluginMap[name]); return { name, @@ -53,7 +53,7 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) { }); return pluginsFromMap.concat( - glob.sync(globPatterns).map(pkgJsonPath => { + glob.sync(globPatterns).map((pkgJsonPath) => { const path = dirname(pkgJsonPath); const pkg = require(pkgJsonPath); // eslint-disable-line import/no-dynamic-require return { diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js index 5c70d63bf147b..fed40298d513f 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js @@ -55,7 +55,7 @@ function getRootPackageDir(dirRoot, dir, rootPackageName) { } } -exports.getProjectRoot = function(file, config) { +exports.getProjectRoot = function (file, config) { const { root, dir } = parse(resolve(file)); const { rootPackageName } = config; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js index da0b799b338ed..6cb2f3d2901d3 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js @@ -22,7 +22,7 @@ const { resolve } = require('path'); const { debug } = require('./debug'); const { getPlugins } = require('./get_plugins'); -exports.getWebpackConfig = function(kibanaPath, projectRoot, config) { +exports.getWebpackConfig = function (kibanaPath, projectRoot, config) { const fromKibana = (...path) => resolve(kibanaPath, ...path); const alias = { @@ -39,7 +39,7 @@ exports.getWebpackConfig = function(kibanaPath, projectRoot, config) { test_utils: fromKibana('src/test_utils/public'), }; - getPlugins(config, kibanaPath, projectRoot).forEach(plugin => { + getPlugins(config, kibanaPath, projectRoot).forEach((plugin) => { alias[`plugins/${plugin.name}`] = plugin.publicDirectory; }); diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js index 2af7d1c2f5349..9eb3234fca7b4 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js @@ -32,8 +32,8 @@ function readShimNames(shimDirectory) { } return readdirSync(shimDirectory) - .filter(name => !name.startsWith('.') && !name.startsWith('_')) - .map(name => (name.endsWith('.js') ? name.slice(0, -3) : name)); + .filter((name) => !name.startsWith('.') && !name.startsWith('_')) + .map((name) => (name.endsWith('.js') ? name.slice(0, -3) : name)); } function findRelativeWebpackShims(directory) { @@ -53,7 +53,7 @@ function findRelativeWebpackShims(directory) { return allShims; } -exports.isProbablyWebpackShim = function(source, file) { +exports.isProbablyWebpackShim = function (source, file) { const shims = findRelativeWebpackShims(dirname(file)); - return shims.some(shim => source === shim || source.startsWith(shim + '/')); + return shims.some((shim) => source === shim || source.startsWith(shim + '/')); }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js index a7bb391f9b1c6..00b07f469bd9c 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js @@ -25,7 +25,7 @@ * @param {Array<[alias,path]>} aliasEntries * @return {string|undefined} */ -exports.resolveWebpackAlias = function(source, aliasEntries) { +exports.resolveWebpackAlias = function (source, aliasEntries) { for (const [alias, path] of aliasEntries) { if (source === alias) { return path; diff --git a/packages/kbn-eslint-plugin-eslint/lib.js b/packages/kbn-eslint-plugin-eslint/lib.js index 56684746c479f..a7431be00e054 100644 --- a/packages/kbn-eslint-plugin-eslint/lib.js +++ b/packages/kbn-eslint-plugin-eslint/lib.js @@ -31,7 +31,7 @@ exports.normalizeWhitespace = function normalizeWhitespace(string) { return string.replace(/\s+/g, ' '); }; -exports.init = function(context, program, initStep) { +exports.init = function (context, program, initStep) { try { return initStep(); } catch (error) { diff --git a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js index 0567307d18968..6b5564f1f8004 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js +++ b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js @@ -39,7 +39,7 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { return { Program(program) { const licenses = init(context, program, () => { @@ -70,8 +70,8 @@ module.exports = { sourceCode .getAllComments() - .filter(node => licenses.includes(normalizeWhitespace(node.value))) - .forEach(node => { + .filter((node) => licenses.includes(normalizeWhitespace(node.value))) + .forEach((node) => { context.report({ node, message: 'This license header is not allowed in this file.', diff --git a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js index 8119d338ee536..6027a939f1a65 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js +++ b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js @@ -22,7 +22,7 @@ const KIBANA_ROOT = path.resolve(__dirname, '../../..'); function checkModuleNameNode(context, mappings, node) { const mapping = mappings.find( - mapping => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`) + (mapping) => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`) ); if (!mapping) { @@ -105,7 +105,7 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { const mappings = context.options[0]; return { diff --git a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js index f3c9fcef1985e..915ac3ed7922e 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js +++ b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js @@ -40,10 +40,10 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { return { Program(program) { - const license = init(context, program, function() { + const license = init(context, program, function () { const options = context.options[0] || {}; const license = options.license; @@ -69,7 +69,7 @@ module.exports = { const sourceCode = context.getSourceCode(); const comment = sourceCode .getAllComments() - .find(node => normalizeWhitespace(node.value) === license.nodeValue); + .find((node) => normalizeWhitespace(node.value) === license.nodeValue); // no licence comment if (!comment) { diff --git a/packages/kbn-i18n/scripts/build.js b/packages/kbn-i18n/scripts/build.js index 0764451c74575..62e1a35f00399 100644 --- a/packages/kbn-i18n/scripts/build.js +++ b/packages/kbn-i18n/scripts/build.js @@ -31,7 +31,7 @@ const padRight = (width, str) => run( async ({ log, flags }) => { - await withProcRunner(log, async proc => { + await withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -43,7 +43,7 @@ run( log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); await Promise.all([ - ...['web', 'node'].map(subTask => + ...['web', 'node'].map((subTask) => proc.run(padRight(10, `babel:${subTask}`), { cmd: 'babel', args: [ diff --git a/packages/kbn-i18n/src/angular/filter.test.ts b/packages/kbn-i18n/src/angular/filter.test.ts index 78bc279689357..5336926a64139 100644 --- a/packages/kbn-i18n/src/angular/filter.test.ts +++ b/packages/kbn-i18n/src/angular/filter.test.ts @@ -28,17 +28,14 @@ import * as i18n from '../core/i18n'; import { i18nFilter as angularI18nFilter } from './filter'; import { I18nProvider, I18nServiceType } from './provider'; -angular - .module('app', []) - .provider('i18n', I18nProvider) - .filter('i18n', angularI18nFilter); +angular.module('app', []).provider('i18n', I18nProvider).filter('i18n', angularI18nFilter); describe('i18nFilter', () => { let filter: I18nServiceType; beforeEach(angular.mock.module('app')); beforeEach( - angular.mock.inject(i18nFilter => { + angular.mock.inject((i18nFilter) => { filter = i18nFilter; }) ); diff --git a/packages/kbn-i18n/src/loader.ts b/packages/kbn-i18n/src/loader.ts index 21f540f588f46..8231ed36928d8 100644 --- a/packages/kbn-i18n/src/loader.ts +++ b/packages/kbn-i18n/src/loader.ts @@ -127,7 +127,7 @@ export function getRegisteredLocales() { */ export async function getTranslationsByLocale(locale: string): Promise { const files = translationsRegistry[locale] || []; - const notLoadedFiles = files.filter(file => !loadedFiles[file]); + const notLoadedFiles = files.filter((file) => !loadedFiles[file]); if (notLoadedFiles.length) { await loadAndCacheFiles(notLoadedFiles); diff --git a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx index db879fbae6ff1..3271ae7c98d2f 100644 --- a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx +++ b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx @@ -37,7 +37,7 @@ function translateFormattedMessageUsingPseudoLocale(message: string) { if (formattedMessageDelimiter !== null) { return message .split(formattedMessageDelimiter[0]) - .map(part => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part))) + .map((part) => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part))) .join(formattedMessageDelimiter[0]); } diff --git a/packages/kbn-interpreter/src/common/lib/arg.js b/packages/kbn-interpreter/src/common/lib/arg.js index 0aa2b52e35acb..2ab74e5035866 100644 --- a/packages/kbn-interpreter/src/common/lib/arg.js +++ b/packages/kbn-interpreter/src/common/lib/arg.js @@ -30,7 +30,7 @@ export function Arg(config) { this.multi = config.multi == null ? false : config.multi; this.resolve = config.resolve == null ? true : config.resolve; this.options = config.options || []; - this.accepts = type => { + this.accepts = (type) => { if (!this.types.length) return true; return includes(config.types, type); }; diff --git a/packages/kbn-interpreter/src/common/lib/ast.js b/packages/kbn-interpreter/src/common/lib/ast.js index 61cfe94ac955c..98123f475cd92 100644 --- a/packages/kbn-interpreter/src/common/lib/ast.js +++ b/packages/kbn-interpreter/src/common/lib/ast.js @@ -55,7 +55,7 @@ function getExpressionArgs(block, level = 0) { const argKeys = Object.keys(args); const MAX_LINE_LENGTH = 80; // length before wrapping arguments - return argKeys.map(argKey => + return argKeys.map((argKey) => args[argKey].reduce((acc, arg) => { const argString = getArgumentString(arg, argKey, level); const lineLength = acc.split('\n').pop().length; @@ -86,7 +86,7 @@ function getExpression(chain, level = 0) { const separator = level > 0 ? ' | ' : '\n| '; return chain - .map(chainObj => { + .map((chainObj) => { const type = getType(chainObj); if (type === 'function') { diff --git a/packages/kbn-interpreter/src/common/lib/fn.js b/packages/kbn-interpreter/src/common/lib/fn.js index c6b2fcbe67799..5561c08f9c7d0 100644 --- a/packages/kbn-interpreter/src/common/lib/fn.js +++ b/packages/kbn-interpreter/src/common/lib/fn.js @@ -39,7 +39,7 @@ export function Fn(config) { this.context = config.context || {}; - this.accepts = type => { + this.accepts = (type) => { if (!this.context.types) return true; // If you don't tell us about context, we'll assume you don't care what you get return includes(this.context.types, type); // Otherwise, check it }; diff --git a/packages/kbn-interpreter/src/common/lib/get_by_alias.js b/packages/kbn-interpreter/src/common/lib/get_by_alias.js index d7bb1bbf9e79d..04c435216b946 100644 --- a/packages/kbn-interpreter/src/common/lib/get_by_alias.js +++ b/packages/kbn-interpreter/src/common/lib/get_by_alias.js @@ -26,7 +26,7 @@ export function getByAlias(specs, name) { const lowerCaseName = name.toLowerCase(); return Object.values(specs).find(({ name, aliases }) => { if (name.toLowerCase() === lowerCaseName) return true; - return (aliases || []).some(alias => { + return (aliases || []).some((alias) => { return alias.toLowerCase() === lowerCaseName; }); }); diff --git a/packages/kbn-interpreter/src/common/lib/registry.js b/packages/kbn-interpreter/src/common/lib/registry.js index 3b22704b9e9c8..25b122f400711 100644 --- a/packages/kbn-interpreter/src/common/lib/registry.js +++ b/packages/kbn-interpreter/src/common/lib/registry.js @@ -48,7 +48,7 @@ export class Registry { } toArray() { - return Object.keys(this._indexed).map(key => this.get(key)); + return Object.keys(this._indexed).map((key) => this.get(key)); } get(name) { diff --git a/packages/kbn-interpreter/src/common/registries.js b/packages/kbn-interpreter/src/common/registries.js index 2c68f5647ca73..9d73433bb2d26 100644 --- a/packages/kbn-interpreter/src/common/registries.js +++ b/packages/kbn-interpreter/src/common/registries.js @@ -24,7 +24,7 @@ * @param {*} newRegistries - The new set of registries */ export function addRegistries(registries, newRegistries) { - Object.keys(newRegistries).forEach(registryName => { + Object.keys(newRegistries).forEach((registryName) => { if (registries[registryName]) { throw new Error(`There is already a registry named "${registryName}".`); } @@ -41,7 +41,7 @@ export function addRegistries(registries, newRegistries) { * @param {*} specs - The specs to be regsitered (e.g. { types: [], browserFunctions: [] }) */ export function register(registries, specs) { - Object.keys(specs).forEach(registryName => { + Object.keys(specs).forEach((registryName) => { if (!registries[registryName]) { throw new Error(`There is no registry named "${registryName}".`); } @@ -49,7 +49,7 @@ export function register(registries, specs) { if (!registries[registryName].register) { throw new Error(`Registry "${registryName}" must have a register function.`); } - specs[registryName].forEach(f => registries[registryName].register(f)); + specs[registryName].forEach((f) => registries[registryName].register(f)); }); return registries; diff --git a/packages/kbn-interpreter/tasks/build/cli.js b/packages/kbn-interpreter/tasks/build/cli.js index 86df21ee566ac..970e0f8847882 100644 --- a/packages/kbn-interpreter/tasks/build/cli.js +++ b/packages/kbn-interpreter/tasks/build/cli.js @@ -56,7 +56,7 @@ if (flags.help) { process.exit(); } -withProcRunner(log, async proc => { +withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -87,7 +87,7 @@ withProcRunner(log, async proc => { ]); log.success('Complete'); -}).catch(error => { +}).catch((error) => { log.error(error); process.exit(1); }); diff --git a/packages/kbn-optimizer/src/cli.ts b/packages/kbn-optimizer/src/cli.ts index a2fbe969e34d8..0916f12a7110d 100644 --- a/packages/kbn-optimizer/src/cli.ts +++ b/packages/kbn-optimizer/src/cli.ts @@ -77,8 +77,8 @@ run( const extraPluginScanDirs = ([] as string[]) .concat((flags['scan-dir'] as string | string[]) || []) - .map(p => Path.resolve(p)); - if (!extraPluginScanDirs.every(s => typeof s === 'string')) { + .map((p) => Path.resolve(p)); + if (!extraPluginScanDirs.every((s) => typeof s === 'string')) { throw createFlagError('expected --scan-dir to be a string'); } diff --git a/packages/kbn-optimizer/src/common/array_helpers.test.ts b/packages/kbn-optimizer/src/common/array_helpers.test.ts index 9d45217486ee8..ab5f4b694333e 100644 --- a/packages/kbn-optimizer/src/common/array_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/array_helpers.test.ts @@ -53,11 +53,7 @@ describe('ascending/descending', () => { ].sort(() => 0.5 - Math.random()); it('sorts items using getters', () => { - expect( - Array.from(values) - .sort(ascending(a, b, c)) - .map(print) - ).toMatchInlineSnapshot(` + expect(Array.from(values).sort(ascending(a, b, c)).map(print)).toMatchInlineSnapshot(` Array [ "1/2/3", "3/2/1", @@ -81,11 +77,7 @@ describe('ascending/descending', () => { ] `); - expect( - Array.from(values) - .sort(descending(a, b, c)) - .map(print) - ).toMatchInlineSnapshot(` + expect(Array.from(values).sort(descending(a, b, c)).map(print)).toMatchInlineSnapshot(` Array [ "9/9/9", "8/foo/8", diff --git a/packages/kbn-optimizer/src/common/bundle.ts b/packages/kbn-optimizer/src/common/bundle.ts index 7581b90d60af2..9e2ad186ba40c 100644 --- a/packages/kbn-optimizer/src/common/bundle.ts +++ b/packages/kbn-optimizer/src/common/bundle.ts @@ -80,7 +80,7 @@ export class Bundle { return { spec: this.toSpec(), mtimes: entriesToObject( - files.map(p => [p, mtimes.get(p)] as const).sort(ascending(e => e[0])) + files.map((p) => [p, mtimes.get(p)] as const).sort(ascending((e) => e[0])) ), }; } diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts index ba19bdc9c3be7..aba4451622dcd 100644 --- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts +++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts @@ -130,7 +130,7 @@ export const checks: DisallowedSyntaxCheck[] = [ { name: '[es2018] object spread properties', nodeType: 'ObjectExpression', - test: (n: estree.ObjectExpression) => n.properties.some(p => p.type === 'SpreadElement'), + test: (n: estree.ObjectExpression) => n.properties.some((p) => p.type === 'SpreadElement'), }, // https://github.com/estree/estree/blob/master/es2018.md#template-literals { @@ -142,7 +142,7 @@ export const checks: DisallowedSyntaxCheck[] = [ { name: '[es2018] rest properties', nodeType: 'ObjectPattern', - test: (n: estree.ObjectPattern) => n.properties.some(p => p.type === 'RestElement'), + test: (n: estree.ObjectPattern) => n.properties.some((p) => p.type === 'RestElement'), }, /** diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts index 7377462eb267b..8fb7559f3e22f 100644 --- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts +++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts @@ -26,8 +26,8 @@ import { parseFilePath } from '../parse_path'; export class DisallowedSyntaxPlugin { apply(compiler: webpack.Compiler) { - compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, factory => { - factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, parser => { + compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, (factory) => { + factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, (parser) => { parser.hooks.program.tap(DisallowedSyntaxPlugin.name, (program: acorn.Node) => { const module = parser.state?.current; if (!module || !module.resource) { @@ -43,7 +43,7 @@ export class DisallowedSyntaxPlugin { const failedChecks = new Set(); - AcornWalk.full(program, node => { + AcornWalk.full(program, (node) => { const checks = checksByNodeType.get(node.type as any); if (!checks) { return; @@ -63,7 +63,7 @@ export class DisallowedSyntaxPlugin { // throw an error to trigger a parse failure, causing this module to be reported as invalid throw new Error( `disallowed syntax found in file ${resource}:\n - ${Array.from(failedChecks) - .map(c => c.name) + .map((c) => c.name) .join('\n - ')}` ); }); diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts index f6f6841532799..7458fa13eccb3 100644 --- a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts @@ -233,6 +233,6 @@ it('stops an infinite stream when unsubscribed', async () => { // ensure summarizer still only called 10 times after a timeout expect(summarize).toHaveBeenCalledTimes(10); - await new Promise(resolve => setTimeout(resolve, 1000)); + await new Promise((resolve) => setTimeout(resolve, 1000)); expect(summarize).toHaveBeenCalledTimes(10); }); diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.ts index d07af32f88897..d93cba5653abd 100644 --- a/packages/kbn-optimizer/src/common/event_stream_helpers.ts +++ b/packages/kbn-optimizer/src/common/event_stream_helpers.ts @@ -40,7 +40,7 @@ export const summarizeEventStream = ( initialState: State, summarize: Summarizer ) => { - return new Rx.Observable>(subscriber => { + return new Rx.Observable>((subscriber) => { const eventBuffer: Event[] = []; let processingEventBuffer = false; @@ -93,7 +93,7 @@ export const summarizeEventStream = ( subscriber.add( event$.subscribe( injectEvent, - error => { + (error) => { subscriber.error(error); }, () => { diff --git a/packages/kbn-optimizer/src/common/parse_path.test.ts b/packages/kbn-optimizer/src/common/parse_path.test.ts index 61be44348cfae..48749a08fb285 100644 --- a/packages/kbn-optimizer/src/common/parse_path.test.ts +++ b/packages/kbn-optimizer/src/common/parse_path.test.ts @@ -32,13 +32,13 @@ const FILES = [ ]; describe('parseFilePath()', () => { - it.each([...FILES, ...AMBIGUOUS])('parses %s', path => { + it.each([...FILES, ...AMBIGUOUS])('parses %s', (path) => { expect(parseFilePath(path)).toMatchSnapshot(); }); }); describe('parseDirPath()', () => { - it.each([...DIRS, ...AMBIGUOUS])('parses %s', path => { + it.each([...DIRS, ...AMBIGUOUS])('parses %s', (path) => { expect(parseDirPath(path)).toMatchSnapshot(); }); }); diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts index 72be71e6bf7ec..dda66c999b8f1 100644 --- a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts @@ -29,9 +29,9 @@ describe('pipeClosure()', () => { let counter = 0; const foo$ = Rx.of(1, 2, 3).pipe( - pipeClosure(source$ => { + pipeClosure((source$) => { const multiplier = ++counter; - return source$.pipe(map(i => i * multiplier)); + return source$.pipe(map((i) => i * multiplier)); }), toArray() ); @@ -71,7 +71,7 @@ describe('maybe()', () => { describe('maybeMap()', () => { it('calls map fn and filters out undefined values returned', async () => { const foo$ = Rx.of(1, 2, 3, 4, 5).pipe( - maybeMap(i => (i % 2 ? i : undefined)), + maybeMap((i) => (i % 2 ? i : undefined)), toArray() ); @@ -94,7 +94,7 @@ describe('debounceTimeBuffer()', () => { foo$ .pipe( debounceTimeBuffer(100), - map(items => items.reduce((sum, n) => sum + n)) + map((items) => items.reduce((sum, n) => sum + n)) ) .subscribe(dest); @@ -128,7 +128,7 @@ describe('debounceTimeBuffer()', () => { foo$ .pipe( debounceTimeBuffer(100), - map(items => items.reduce((sum, n) => sum + n)) + map((items) => items.reduce((sum, n) => sum + n)) ) .subscribe(dest); diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.ts index f37bebb49efe9..c6385c22518aa 100644 --- a/packages/kbn-optimizer/src/common/rxjs_helpers.ts +++ b/packages/kbn-optimizer/src/common/rxjs_helpers.ts @@ -39,7 +39,7 @@ export const pipeClosure = (fn: Operator): Operator => { * supporting TypeScript */ export const maybe = (): Operator => { - return mergeMap(item => (item === undefined ? Rx.EMPTY : [item])); + return mergeMap((item) => (item === undefined ? Rx.EMPTY : [item])); }; /** @@ -64,7 +64,7 @@ export const debounceTimeBuffer = (ms: number) => pipeClosure((source$: Rx.Observable) => { const buffer: T[] = []; return source$.pipe( - tap(item => buffer.push(item)), + tap((item) => buffer.push(item)), debounceTime(ms), map(() => { const items = Array.from(buffer); diff --git a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts index ff9addbb3172e..4776153935be5 100644 --- a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts +++ b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts @@ -85,39 +85,39 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { } }; - const initializingStates = msgs.filter(msg => msg.state.phase === 'initializing'); + const initializingStates = msgs.filter((msg) => msg.state.phase === 'initializing'); assert('produce at least one initializing event', initializingStates.length >= 1); const bundleCacheStates = msgs.filter( - msg => + (msg) => (msg.event?.type === 'bundle cached' || msg.event?.type === 'bundle not cached') && msg.state.phase === 'initializing' ); assert('produce two bundle cache events while initializing', bundleCacheStates.length === 2); - const initializedStates = msgs.filter(msg => msg.state.phase === 'initialized'); + const initializedStates = msgs.filter((msg) => msg.state.phase === 'initialized'); assert('produce at least one initialized event', initializedStates.length >= 1); - const workerStarted = msgs.filter(msg => msg.event?.type === 'worker started'); + const workerStarted = msgs.filter((msg) => msg.event?.type === 'worker started'); assert('produce one worker started event', workerStarted.length === 1); - const runningStates = msgs.filter(msg => msg.state.phase === 'running'); + const runningStates = msgs.filter((msg) => msg.state.phase === 'running'); assert( 'produce two or three "running" states', runningStates.length === 2 || runningStates.length === 3 ); - const bundleNotCachedEvents = msgs.filter(msg => msg.event?.type === 'bundle not cached'); + const bundleNotCachedEvents = msgs.filter((msg) => msg.event?.type === 'bundle not cached'); assert('produce two "bundle not cached" events', bundleNotCachedEvents.length === 2); - const successStates = msgs.filter(msg => msg.state.phase === 'success'); + const successStates = msgs.filter((msg) => msg.state.phase === 'success'); assert( 'produce one or two "compiler success" states', successStates.length === 1 || successStates.length === 2 ); const otherStates = msgs.filter( - msg => + (msg) => msg.state.phase !== 'initializing' && msg.state.phase !== 'success' && msg.state.phase !== 'running' && @@ -126,7 +126,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { ); assert('produce zero unexpected states', otherStates.length === 0, otherStates); - const foo = config.bundles.find(b => b.id === 'foo')!; + const foo = config.bundles.find((b) => b.id === 'foo')!; expect(foo).toBeTruthy(); foo.cache.refresh(); expect(foo.cache.getModuleCount()).toBe(4); @@ -139,7 +139,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { ] `); - const bar = config.bundles.find(b => b.id === 'bar')!; + const bar = config.bundles.find((b) => b.id === 'bar')!; expect(bar).toBeTruthy(); bar.cache.refresh(); expect(bar.cache.getModuleCount()).toBe( @@ -173,7 +173,7 @@ it('uses cache on second run and exist cleanly', async () => { const msgs = await runOptimizer(config) .pipe( - tap(state => { + tap((state) => { if (state.event?.type === 'worker stdio') { // eslint-disable-next-line no-console console.log('worker', state.event.stream, state.event.chunk.toString('utf8')); @@ -183,7 +183,7 @@ it('uses cache on second run and exist cleanly', async () => { ) .toPromise(); - expect(msgs.map(m => m.state.phase)).toMatchInlineSnapshot(` + expect(msgs.map((m) => m.state.phase)).toMatchInlineSnapshot(` Array [ "initializing", "initializing", @@ -202,9 +202,7 @@ it('prepares assets for distribution', async () => { dist: true, }); - await runOptimizer(config) - .pipe(logOptimizerState(log, config), toArray()) - .toPromise(); + await runOptimizer(config).pipe(logOptimizerState(log, config), toArray()).toPromise(); expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle'); expectFileMatchesSnapshotWithCompression( diff --git a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts index 1bfd8d3fd073a..14ff320173d60 100644 --- a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts +++ b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts @@ -35,7 +35,7 @@ const MOCK_REPO_DIR = Path.resolve(TMP_DIR, 'mock_repo'); expect.addSnapshotSerializer({ print: () => '', - test: v => v instanceof Bundle, + test: (v) => v instanceof Bundle, }); expect.addSnapshotSerializer(createAbsolutePathSerializer(MOCK_REPO_DIR)); diff --git a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts index c02a857883a98..91d0f308e0ef6 100644 --- a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts +++ b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts @@ -96,7 +96,7 @@ it('notifies of changes and completes once all bundles have changed', async () = // first we change foo and bar, and after 1 second get that change comes though if (i === 1) { expect(event.bundles).toHaveLength(2); - const [bar, foo] = event.bundles.sort(ascending(b => b.id)); + const [bar, foo] = event.bundles.sort(ascending((b) => b.id)); expect(bar).toHaveProperty('id', 'bar'); expect(foo).toHaveProperty('id', 'foo'); } @@ -110,7 +110,7 @@ it('notifies of changes and completes once all bundles have changed', async () = // finally we change box and car together if (i === 5) { expect(event.bundles).toHaveLength(2); - const [bar, foo] = event.bundles.sort(ascending(b => b.id)); + const [bar, foo] = event.bundles.sort(ascending((b) => b.id)); expect(bar).toHaveProperty('id', 'box'); expect(foo).toHaveProperty('id', 'car'); } diff --git a/packages/kbn-optimizer/src/log_optimizer_state.ts b/packages/kbn-optimizer/src/log_optimizer_state.ts index 5217581d1b413..cbec159bd27a0 100644 --- a/packages/kbn-optimizer/src/log_optimizer_state.ts +++ b/packages/kbn-optimizer/src/log_optimizer_state.ts @@ -33,7 +33,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) { let loggedInit = false; return update$.pipe( - tap(update => { + tap((update) => { const { event, state } = update; if (event?.type === 'worker stdio') { diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts index dd4d5c294dfc8..4671276797049 100644 --- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts +++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts @@ -35,7 +35,7 @@ const summarizeBundles = (w: Assignments) => const readConfigs = (workers: Assignments[]) => workers.map( - (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map(b => b.id).join(',')}` + (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map((b) => b.id).join(',')}` ); const assertReturnVal = (workers: Assignments[]) => { diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts index 001783b167c7a..e1bcb22230bf9 100644 --- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts +++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts @@ -70,16 +70,16 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * counts and sort them by [moduleCount, id] */ const bundlesWithCountsDesc = bundles - .filter(b => b.cache.getModuleCount() !== undefined) + .filter((b) => b.cache.getModuleCount() !== undefined) .sort( descending( - b => b.cache.getModuleCount(), - b => b.id + (b) => b.cache.getModuleCount(), + (b) => b.id ) ); const bundlesWithoutModuleCounts = bundles - .filter(b => b.cache.getModuleCount() === undefined) - .sort(descending(b => b.id)); + .filter((b) => b.cache.getModuleCount() === undefined) + .sort(descending((b) => b.id)); /** * assign largest bundles to the smallest worker until it is @@ -87,7 +87,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * with module counts are assigned */ while (bundlesWithCountsDesc.length) { - const [smallestWorker, nextSmallestWorker] = workers.sort(ascending(w => w.moduleCount)); + const [smallestWorker, nextSmallestWorker] = workers.sort(ascending((w) => w.moduleCount)); while (!nextSmallestWorker || smallestWorker.moduleCount <= nextSmallestWorker.moduleCount) { const bundle = bundlesWithCountsDesc.shift(); @@ -104,7 +104,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * assign bundles without module counts to workers round-robin * starting with the smallest workers */ - workers.sort(ascending(w => w.moduleCount)); + workers.sort(ascending((w) => w.moduleCount)); while (bundlesWithoutModuleCounts.length) { for (const worker of workers) { const bundle = bundlesWithoutModuleCounts.shift(); diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts index 7351a3787f760..d5b0b8491f727 100644 --- a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts +++ b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts @@ -35,7 +35,7 @@ jest.mock('./get_changes.ts', () => ({ })); jest.mock('./get_mtimes.ts', () => ({ - getMtimes: async (paths: string[]) => new Map(paths.map(path => [path, 12345])), + getMtimes: async (paths: string[]) => new Map(paths.map((path) => [path, 12345])), })); jest.mock('execa'); diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.ts index 11288afa28969..e024af125312d 100644 --- a/packages/kbn-optimizer/src/optimizer/cache_keys.ts +++ b/packages/kbn-optimizer/src/optimizer/cache_keys.ts @@ -182,7 +182,7 @@ export async function getOptimizerCacheKey(config: OptimizerConfig) { }; const mtimes = await getMtimes(modifiedPaths); - for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending(e => e[0]))) { + for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending((e) => e[0]))) { if (typeof mtime === 'number') { cacheKeys.modifiedTimes[path] = mtime; } diff --git a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts index 9ac156cb5b8de..07777c323637a 100644 --- a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts +++ b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts @@ -33,15 +33,15 @@ export async function getMtimes(paths: Iterable) { // map paths to [path, mtimeMs] entries with concurrency of // 100 at a time, ignoring missing paths mergeMap( - path => + (path) => stat$(path).pipe( - map(stat => [path, stat.mtimeMs] as const), + map((stat) => [path, stat.mtimeMs] as const), catchError((error: any) => (error?.code === 'ENOENT' ? Rx.EMPTY : Rx.throwError(error))) ), 100 ), toArray(), - map(entries => new Map(entries)) + map((entries) => new Map(entries)) ) .toPromise(); } diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts index 36dc0ca64c6ca..2174c488ad6cc 100644 --- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts +++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts @@ -44,7 +44,7 @@ it('returns a bundle for core and each plugin', () => { }, ], '/repo' - ).map(b => b.toSpec()) + ).map((b) => b.toSpec()) ).toMatchInlineSnapshot(` Array [ Object { diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts index 4741cc3c30af7..b75a8a6edc264 100644 --- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts +++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts @@ -25,9 +25,9 @@ import { KibanaPlatformPlugin } from './kibana_platform_plugins'; export function getPluginBundles(plugins: KibanaPlatformPlugin[], repoRoot: string) { return plugins - .filter(p => p.isUiPlugin) + .filter((p) => p.isUiPlugin) .map( - p => + (p) => new Bundle({ type: 'plugin', id: p.id, diff --git a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts index b4b02649259a2..8b39b5fe8d3b6 100644 --- a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts +++ b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts @@ -32,7 +32,7 @@ export function handleOptimizerCompletion(config: OptimizerConfig) { return update$.pipe( tap({ - next: update => { + next: (update) => { prevState = update.state; }, complete: () => { diff --git a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts index 2165878e92ff4..992feab6cd364 100644 --- a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts +++ b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts @@ -36,15 +36,15 @@ export function findKibanaPlatformPlugins(scanDirs: string[], paths: string[]) { .sync( Array.from( new Set([ - ...scanDirs.map(dir => `${dir}/*/kibana.json`), - ...paths.map(path => `${path}/kibana.json`), + ...scanDirs.map((dir) => `${dir}/*/kibana.json`), + ...paths.map((path) => `${path}/kibana.json`), ]) ), { absolute: true, } ) - .map(path => + .map((path) => // absolute paths returned from globby are using normalize or something so the path separators are `/` even on windows, Path.resolve solves this readKibanaPlatformPlugin(Path.resolve(path)) ); diff --git a/packages/kbn-optimizer/src/optimizer/observe_worker.ts b/packages/kbn-optimizer/src/optimizer/observe_worker.ts index bfc853e5a6b75..f5c944cefb76f 100644 --- a/packages/kbn-optimizer/src/optimizer/observe_worker.ts +++ b/packages/kbn-optimizer/src/optimizer/observe_worker.ts @@ -47,7 +47,7 @@ interface ProcResource extends Rx.Unsubscribable { const isNumeric = (input: any) => String(input).match(/^[0-9]+$/); let inspectPortCounter = 9230; -const inspectFlagIndex = process.execArgv.findIndex(flag => flag.startsWith('--inspect')); +const inspectFlagIndex = process.execArgv.findIndex((flag) => flag.startsWith('--inspect')); let inspectFlag: string | undefined; if (inspectFlagIndex !== -1) { const argv = process.execArgv[inspectFlagIndex]; @@ -74,7 +74,7 @@ function usingWorkerProc( ) { return Rx.using( (): ProcResource => { - const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map(b => b.toSpec()))]; + const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map((b) => b.toSpec()))]; const proc = fork(require.resolve('../worker/run_worker'), args, { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], @@ -94,7 +94,7 @@ function usingWorkerProc( }; }, - resource => { + (resource) => { const { proc } = resource as ProcResource; return fn(proc); } @@ -107,7 +107,7 @@ function observeStdio$(stream: Readable, name: WorkerStdio['stream']) { Rx.race( Rx.fromEvent(stream, 'end'), Rx.fromEvent(stream, 'error').pipe( - map(error => { + map((error) => { throw error; }) ) @@ -134,7 +134,7 @@ export function observeWorker( workerConfig: WorkerConfig, bundles: Bundle[] ): Rx.Observable { - return usingWorkerProc(config, workerConfig, bundles, proc => { + return usingWorkerProc(config, workerConfig, bundles, (proc) => { let lastMsg: WorkerMsg; return Rx.merge( @@ -161,7 +161,7 @@ export function observeWorker( Rx.race( // throw into stream on error events Rx.fromEvent(proc, 'error').pipe( - map(error => { + map((error) => { throw new Error(`worker failed to spawn: ${error.message}`); }) ), diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts index d6336cf867470..4ed241f3b9b2e 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts @@ -106,7 +106,7 @@ export class OptimizerConfig { ...(examples ? [Path.resolve('examples'), Path.resolve('x-pack/examples')] : []), Path.resolve(repoRoot, '../kibana-extra'), ]; - if (!pluginScanDirs.every(p => Path.isAbsolute(p))) { + if (!pluginScanDirs.every((p) => Path.isAbsolute(p))) { throw new TypeError('pluginScanDirs must all be absolute paths'); } @@ -118,7 +118,7 @@ export class OptimizerConfig { } const pluginPaths = options.pluginPaths || []; - if (!pluginPaths.every(s => Path.isAbsolute(s))) { + if (!pluginPaths.every((s) => Path.isAbsolute(s))) { throw new TypeError('pluginPaths must all be absolute paths'); } diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts index ac2a9b8ce1f8b..1572f459e6ee5 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts @@ -80,7 +80,7 @@ function createOptimizerState( * calculate the total state, given a set of compiler messages */ function getStatePhase(states: CompilerMsg[]) { - const types = states.map(s => s.type); + const types = states.map((s) => s.type); if (types.includes('running')) { return 'running'; @@ -90,7 +90,7 @@ function getStatePhase(states: CompilerMsg[]) { return 'issue'; } - if (types.every(s => s === 'compiler success')) { + if (types.every((s) => s === 'compiler success')) { return 'success'; } @@ -173,7 +173,7 @@ export function createOptimizerStateSummarizer( event.type === 'running' ) { const compilerStates: CompilerMsg[] = [ - ...state.compilerStates.filter(c => c.bundleId !== event.bundleId), + ...state.compilerStates.filter((c) => c.bundleId !== event.bundleId), event, ]; return createOptimizerState(state, { diff --git a/packages/kbn-optimizer/src/optimizer/run_workers.ts b/packages/kbn-optimizer/src/optimizer/run_workers.ts index e91b0d25fd72b..1f277f011004d 100644 --- a/packages/kbn-optimizer/src/optimizer/run_workers.ts +++ b/packages/kbn-optimizer/src/optimizer/run_workers.ts @@ -50,15 +50,15 @@ export function runWorkers( return Rx.concat( // first batch of bundles are based on how up-to-date the cache is bundleCache$.pipe( - maybeMap(event => (event.type === 'bundle not cached' ? event.bundle : undefined)), + maybeMap((event) => (event.type === 'bundle not cached' ? event.bundle : undefined)), toArray() ), // subsequent batches are defined by changeEvent$ - changeEvent$.pipe(maybeMap(c => (c.type === 'changes' ? c.bundles : undefined))) + changeEvent$.pipe(maybeMap((c) => (c.type === 'changes' ? c.bundles : undefined))) ).pipe( - mergeMap(bundles => + mergeMap((bundles) => Rx.from(assignBundlesToWorkers(bundles, config.maxWorkerCount)).pipe( - mergeMap(assignment => + mergeMap((assignment) => observeWorker(config, config.getWorkerConfig(optimizerCacheKey), assignment.bundles) ) ) diff --git a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts index 9149c483786fc..fdac4e0204fbe 100644 --- a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts +++ b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts @@ -38,7 +38,7 @@ function recursiveGetNextChange$( return !bundles.length ? Rx.EMPTY : watcher.getNextChange$(bundles, startTime).pipe( - mergeMap(event => { + mergeMap((event) => { if (event.type === 'changes detected') { return Rx.of(event); } @@ -48,7 +48,7 @@ function recursiveGetNextChange$( recursiveGetNextChange$( watcher, - bundles.filter(b => !event.bundles.includes(b)), + bundles.filter((b) => !event.bundles.includes(b)), Date.now() ) ); @@ -74,11 +74,11 @@ export function watchBundlesForChanges$( initialStartTime: number ) { return bundleCacheEvent$.pipe( - maybeMap(event => (event.type === 'bundle cached' ? event.bundle : undefined)), + maybeMap((event) => (event.type === 'bundle cached' ? event.bundle : undefined)), toArray(), - mergeMap(bundles => + mergeMap((bundles) => bundles.length - ? Watcher.using(watcher => recursiveGetNextChange$(watcher, bundles, initialStartTime)) + ? Watcher.using((watcher) => recursiveGetNextChange$(watcher, bundles, initialStartTime)) : Rx.EMPTY ) ); diff --git a/packages/kbn-optimizer/src/optimizer/watcher.ts b/packages/kbn-optimizer/src/optimizer/watcher.ts index 343f391921383..54c548755af5c 100644 --- a/packages/kbn-optimizer/src/optimizer/watcher.ts +++ b/packages/kbn-optimizer/src/optimizer/watcher.ts @@ -43,7 +43,7 @@ export class Watcher { static using(fn: (watcher: Watcher) => Rx.Observable) { return Rx.using( () => new Watcher(), - resource => fn(resource as Watcher) + (resource) => fn(resource as Watcher) ); } @@ -69,14 +69,14 @@ export class Watcher { // debounce and bufffer change events for 1 second to create // final change notification this.change$.pipe( - map(event => event[0]), + map((event) => event[0]), debounceTimeBuffer(1000), map( (changes): Changes => ({ type: 'changes', - bundles: bundles.filter(bundle => { + bundles: bundles.filter((bundle) => { const referencedFiles = bundle.cache.getReferencedFiles(); - return changes.some(change => referencedFiles?.includes(change)); + return changes.some((change) => referencedFiles?.includes(change)); }), }) ), diff --git a/packages/kbn-optimizer/src/report_optimizer_stats.ts b/packages/kbn-optimizer/src/report_optimizer_stats.ts index 06161fb2567b9..5f3153bff5175 100644 --- a/packages/kbn-optimizer/src/report_optimizer_stats.ts +++ b/packages/kbn-optimizer/src/report_optimizer_stats.ts @@ -29,14 +29,14 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize let lastState: OptimizerState | undefined; return update$.pipe( materialize(), - mergeMap(async n => { + mergeMap(async (n) => { if (n.kind === 'N' && n.value?.state) { lastState = n.value?.state; } if (n.kind === 'C' && lastState) { await reporter.metrics( - config.bundles.map(bundle => { + config.bundles.map((bundle) => { // make the cache read from the cache file since it was likely updated by the worker bundle.cache.refresh(); diff --git a/packages/kbn-optimizer/src/worker/run_compilers.ts b/packages/kbn-optimizer/src/worker/run_compilers.ts index 0dfce4b5addba..4ab289d031d72 100644 --- a/packages/kbn-optimizer/src/worker/run_compilers.ts +++ b/packages/kbn-optimizer/src/worker/run_compilers.ts @@ -65,8 +65,8 @@ const observeCompiler = ( * Called by webpack as a single run compilation is starting */ const started$ = Rx.merge( - Rx.fromEventPattern(cb => beforeRun.tap(PLUGIN_NAME, cb)), - Rx.fromEventPattern(cb => watchRun.tap(PLUGIN_NAME, cb)) + Rx.fromEventPattern((cb) => beforeRun.tap(PLUGIN_NAME, cb)), + Rx.fromEventPattern((cb) => watchRun.tap(PLUGIN_NAME, cb)) ).pipe(mapTo(compilerMsgs.running())); /** @@ -74,8 +74,8 @@ const observeCompiler = ( * needAdditionalPass property is set then another compilation * is about to be started, so we shouldn't send complete quite yet */ - const complete$ = Rx.fromEventPattern(cb => done.tap(PLUGIN_NAME, cb)).pipe( - maybeMap(stats => { + const complete$ = Rx.fromEventPattern((cb) => done.tap(PLUGIN_NAME, cb)).pipe( + maybeMap((stats) => { // @ts-ignore not included in types, but it is real https://github.com/webpack/webpack/blob/ab4fa8ddb3f433d286653cd6af7e3aad51168649/lib/Watching.js#L58 if (stats.compilation.needAdditionalPass) { return undefined; @@ -134,7 +134,7 @@ const observeCompiler = ( ); } - const files = Array.from(referencedFiles).sort(ascending(p => p)); + const files = Array.from(referencedFiles).sort(ascending((p) => p)); const mtimes = new Map( files.map((path): [string, number | undefined] => { try { @@ -167,8 +167,10 @@ const observeCompiler = ( * prevets assets from being emitted, and prevents watching * from continuing. */ - const error$ = Rx.fromEventPattern(cb => compiler.hooks.failed.tap(PLUGIN_NAME, cb)).pipe( - map(error => { + const error$ = Rx.fromEventPattern((cb) => + compiler.hooks.failed.tap(PLUGIN_NAME, cb) + ).pipe( + map((error) => { throw compilerMsgs.error(error); }) ); @@ -184,7 +186,7 @@ const observeCompiler = ( * Run webpack compilers */ export const runCompilers = (workerConfig: WorkerConfig, bundles: Bundle[]) => { - const multiCompiler = webpack(bundles.map(def => getWebpackConfig(def, workerConfig))); + const multiCompiler = webpack(bundles.map((def) => getWebpackConfig(def, workerConfig))); return Rx.merge( /** diff --git a/packages/kbn-optimizer/src/worker/run_worker.ts b/packages/kbn-optimizer/src/worker/run_worker.ts index cbec4c3f44c7d..f83c69477f471 100644 --- a/packages/kbn-optimizer/src/worker/run_worker.ts +++ b/packages/kbn-optimizer/src/worker/run_worker.ts @@ -82,10 +82,10 @@ Rx.defer(() => { return runCompilers(workerConfig, bundles); }).subscribe( - msg => { + (msg) => { send(msg); }, - error => { + (error) => { if (isWorkerMsg(error)) { send(error); } else { diff --git a/packages/kbn-optimizer/src/worker/theme_loader.ts b/packages/kbn-optimizer/src/worker/theme_loader.ts index 6d6686a5bde1b..5d02462ef1bb8 100644 --- a/packages/kbn-optimizer/src/worker/theme_loader.ts +++ b/packages/kbn-optimizer/src/worker/theme_loader.ts @@ -21,7 +21,7 @@ import webpack from 'webpack'; import { stringifyRequest } from 'loader-utils'; // eslint-disable-next-line import/no-default-export -export default function(this: webpack.loader.LoaderContext) { +export default function (this: webpack.loader.LoaderContext) { return ` if (window.__kbnDarkMode__) { require(${stringifyRequest(this, `${this.resourcePath}?dark`)}) diff --git a/packages/kbn-optimizer/src/worker/webpack.config.ts b/packages/kbn-optimizer/src/worker/webpack.config.ts index 49bcc6e7e704c..0c9a5b0a75687 100644 --- a/packages/kbn-optimizer/src/worker/webpack.config.ts +++ b/packages/kbn-optimizer/src/worker/webpack.config.ts @@ -64,7 +64,7 @@ function dynamicExternals(bundle: Bundle, context: string, request: string) { // ignore requests that don't include a /{dirname}/public for one of our // "static" bundles as a cheap way to avoid doing path resolution // for paths that couldn't possibly resolve to what we're looking for - const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some(p => + const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some((p) => request.includes(`/${p.dirname}/public`) ); if (!reqToStaticBundle) { @@ -100,7 +100,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) { output: { path: bundle.outputDir, filename: `[name].${bundle.type}.js`, - devtoolModuleFilenameTemplate: info => + devtoolModuleFilenameTemplate: (info) => `/${bundle.type}:${bundle.id}/${Path.relative( bundle.sourceRoot, info.absoluteResourcePath @@ -121,7 +121,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) { externals: [ UiSharedDeps.externals, - function(context, request, cb) { + function (context, request, cb) { try { cb(undefined, dynamicExternals(bundle, context, request)); } catch (error) { diff --git a/packages/kbn-plugin-generator/index.js b/packages/kbn-plugin-generator/index.js index 5f20569886d88..e61037e42d63f 100644 --- a/packages/kbn-plugin-generator/index.js +++ b/packages/kbn-plugin-generator/index.js @@ -61,7 +61,7 @@ exports.run = function run(argv) { name, targetPath, }, - }).catch(error => { + }).catch((error) => { console.error(chalk`{red fatal error}!`); console.error(error.stack); process.exit(1); diff --git a/packages/kbn-plugin-generator/sao_template/sao.js b/packages/kbn-plugin-generator/sao_template/sao.js index 9073ce865a963..7fc29b1e6bd0a 100755 --- a/packages/kbn-plugin-generator/sao_template/sao.js +++ b/packages/kbn-plugin-generator/sao_template/sao.js @@ -59,7 +59,7 @@ async function eslintPlugin(dir) { } } -module.exports = function({ name, targetPath }) { +module.exports = function ({ name, targetPath }) { return { prompts: { customPath: { @@ -99,7 +99,7 @@ module.exports = function({ name, targetPath }) { }, generateTranslations: { type: 'confirm', - when: answers => { + when: (answers) => { // only for 3rd party plugins return !answers.customPath && answers.generateApp; }, @@ -112,7 +112,7 @@ module.exports = function({ name, targetPath }) { generateScss: { type: 'confirm', message: 'Should SCSS be used?', - when: answers => answers.generateApp, + when: (answers) => answers.generateApp, default: true, }, generateEslint: { @@ -135,7 +135,7 @@ module.exports = function({ name, targetPath }) { 'eslintrc.js': '.eslintrc.js', 'i18nrc.json': '.i18nrc.json', }, - data: answers => { + data: (answers) => { const pathToPlugin = answers.customPath ? resolve(answers.customPath, camelCase(name), 'public') : resolve(targetPath, 'public'); diff --git a/packages/kbn-plugin-helpers/src/cli.ts b/packages/kbn-plugin-helpers/src/cli.ts index ee1bca0fe3ac2..b894f854a484f 100644 --- a/packages/kbn-plugin-helpers/src/cli.ts +++ b/packages/kbn-plugin-helpers/src/cli.ts @@ -35,7 +35,7 @@ enableCollectingUnknownOptions( .description('Start kibana and have it include this plugin') .on('--help', docs('start')) .action( - createCommanderAction('start', command => ({ + createCommanderAction('start', (command) => ({ flags: command.unknownOptions, })) ) @@ -75,7 +75,7 @@ program .option('-p, --plugins ', "Manually specify which plugins' test bundles to run") .on('--help', docs('test/karma')) .action( - createCommanderAction('testKarma', command => ({ + createCommanderAction('testKarma', (command) => ({ dev: Boolean(command.dev), plugins: command.plugins, })) diff --git a/packages/kbn-plugin-helpers/src/lib/docs.ts b/packages/kbn-plugin-helpers/src/lib/docs.ts index 68c095209e817..fb05fd0c5c2ce 100644 --- a/packages/kbn-plugin-helpers/src/lib/docs.ts +++ b/packages/kbn-plugin-helpers/src/lib/docs.ts @@ -28,7 +28,7 @@ function indent(txt: string, n: number) { export function docs(name: string) { const md = readFileSync(resolve(__dirname, '../../src/tasks', name, 'README.md'), 'utf8'); - return function() { + return function () { /* eslint-disable-next-line no-console */ console.log(`\n Docs:\n\n${indent(md, 4)}\n\n`); }; diff --git a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts index 77fa7f2fcae84..0d692aed06305 100644 --- a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts +++ b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts @@ -22,7 +22,7 @@ import { Command } from 'commander'; export function enableCollectingUnknownOptions(command: Command) { const origParse = command.parseOptions; command.allowUnknownOption(); - command.parseOptions = function(argv: string[]) { + command.parseOptions = function (argv: string[]) { const opts = origParse.call(this, argv); this.unknownOptions = opts.unknown; return opts; diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js index f596576fe7466..d9f20129e85f9 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js @@ -91,7 +91,7 @@ describe('calling create_build', () => { expect(mockBuild.mock.calls).toHaveLength(1); const { files } = nameArgs(mockBuild.mock.calls[0]); - plugin.buildSourcePatterns.forEach(file => expect(files).toContain(file)); + plugin.buildSourcePatterns.forEach((file) => expect(files).toContain(file)); }); it('uses only files passed in', async () => { @@ -104,7 +104,7 @@ describe('calling create_build', () => { expect(mockBuild.mock.calls).toHaveLength(1); const { files } = nameArgs(mockBuild.mock.calls[0]); - options.files.forEach(file => expect(files).toContain(file)); + options.files.forEach((file) => expect(files).toContain(file)); }); it('rejects returned promise when build fails', async () => { diff --git a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts index 255b2e6ef9992..aaecd11ad82af 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts +++ b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts @@ -26,7 +26,7 @@ export function rewritePackageJson( buildVersion: string, kibanaVersion: string ) { - return Through2Map.obj(function(file: File) { + return Through2Map.obj(function (file: File) { if (file.basename === 'package.json' && file.dirname === buildSource) { const pkg = JSON.parse(file.contents!.toString('utf8')); diff --git a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts index 75affb6da8c6f..5018fd7598180 100644 --- a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts +++ b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts @@ -35,7 +35,7 @@ export function startTask({ plugin, options }: TaskContext) { let args = nodeOptions.concat([script, '--dev', '--plugin-path', plugin.root]); if (Array.isArray(plugin.includePlugins)) { - plugin.includePlugins.forEach(path => { + plugin.includePlugins.forEach((path) => { args = args.concat(['--plugin-path', path]); }); } diff --git a/packages/kbn-pm/src/cli.ts b/packages/kbn-pm/src/cli.ts index c2f49356957f7..94f348e1835ed 100644 --- a/packages/kbn-pm/src/cli.ts +++ b/packages/kbn-pm/src/cli.ts @@ -28,8 +28,8 @@ import { log } from './utils/log'; function help() { const availableCommands = Object.keys(commands) - .map(commandName => commands[commandName]) - .map(command => `${command.name} - ${command.description}`); + .map((commandName) => commands[commandName]) + .map((command) => `${command.name} - ${command.description}`); log.write(dedent` usage: kbn [] diff --git a/packages/kbn-pm/src/commands/bootstrap.ts b/packages/kbn-pm/src/commands/bootstrap.ts index d0aa220f25f66..6146aeab21db4 100644 --- a/packages/kbn-pm/src/commands/bootstrap.ts +++ b/packages/kbn-pm/src/commands/bootstrap.ts @@ -69,7 +69,7 @@ export const BootstrapCommand: ICommand = { log.write(chalk.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); const checksums = options.cache ? await getAllChecksums(kbn, log) : false; - await parallelizeBatches(batchedProjects, async project => { + await parallelizeBatches(batchedProjects, async (project) => { if (project.hasScript('kbn:bootstrap')) { const cacheFile = new BootstrapCacheFile(kbn, project, checksums); if (cacheFile.isValid()) { diff --git a/packages/kbn-pm/src/commands/run.ts b/packages/kbn-pm/src/commands/run.ts index 2f4d9e8453d09..989bfef19c380 100644 --- a/packages/kbn-pm/src/commands/run.ts +++ b/packages/kbn-pm/src/commands/run.ts @@ -43,7 +43,7 @@ export const RunCommand: ICommand = { chalk.bold(`\nRunning script [${chalk.green(scriptName)}] in batched topological order\n`) ); - await parallelizeBatches(batchedProjects, async pkg => { + await parallelizeBatches(batchedProjects, async (pkg) => { if (pkg.hasScript(scriptName)) { await pkg.runScriptStreaming(scriptName, scriptArgs); } diff --git a/packages/kbn-pm/src/commands/watch.ts b/packages/kbn-pm/src/commands/watch.ts index b5c493372b04f..2e18b02a1c860 100644 --- a/packages/kbn-pm/src/commands/watch.ts +++ b/packages/kbn-pm/src/commands/watch.ts @@ -83,7 +83,7 @@ export const WatchCommand: ICommand = { batchedProjects.push([projects.get(kibanaProjectName)!]); } - await parallelizeBatches(batchedProjects, async pkg => { + await parallelizeBatches(batchedProjects, async (pkg) => { const completionHint = await waitUntilWatchIsReady( pkg.runScriptStreaming(watchScriptName).stdout ); diff --git a/packages/kbn-pm/src/production/build_production_projects.ts b/packages/kbn-pm/src/production/build_production_projects.ts index 0d4be8b016077..689bf51cd7bdf 100644 --- a/packages/kbn-pm/src/production/build_production_projects.ts +++ b/packages/kbn-pm/src/production/build_production_projects.ts @@ -46,7 +46,7 @@ export async function buildProductionProjects({ const projectGraph = buildProjectGraph(projects); const batchedProjects = topologicallyBatchProjects(projects, projectGraph); - const projectNames = [...projects.values()].map(project => project.name); + const projectNames = [...projects.values()].map((project) => project.name); log.write(`Preparing production build for [${projectNames.join(', ')}]`); for (const batch of batchedProjects) { @@ -82,7 +82,7 @@ async function getProductionProjects(rootPath: string, onlyOSS?: boolean) { productionProjects.delete('kibana'); if (onlyOSS) { - productionProjects.forEach(project => { + productionProjects.forEach((project) => { if (project.getBuildConfig().oss === false) { productionProjects.delete(project.json.name); } diff --git a/packages/kbn-pm/src/run.ts b/packages/kbn-pm/src/run.ts index 44bf5a91ee1b1..c3879c701d785 100644 --- a/packages/kbn-pm/src/run.ts +++ b/packages/kbn-pm/src/run.ts @@ -71,7 +71,7 @@ export async function runCommand(command: ICommand, config: Omit 0) { - const metaOutput = keys.map(key => { + const metaOutput = keys.map((key) => { const value = e.meta[key]; return `${key}: ${value}`; }); diff --git a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts index 7d87179f34605..282483e10ccf2 100644 --- a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts +++ b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts @@ -39,7 +39,7 @@ export class BootstrapCacheFile { // sort deps by name so that the key is stable .sort((a, b) => a.name.localeCompare(b.name)) // get the cacheKey for each project, return undefined if the cache key couldn't be determined - .map(p => { + .map((p) => { const cacheKey = checksums.get(p.name); if (cacheKey) { return `${p.name}:${cacheKey}`; @@ -47,7 +47,7 @@ export class BootstrapCacheFile { }); // if any of the relevant cache keys are undefined then the projectCacheKey must be too - this.expectedValue = projectAndDepCacheKeys.some(k => !k) + this.expectedValue = projectAndDepCacheKeys.some((k) => !k) ? undefined : [ `# this is only human readable for debugging, please don't try to parse this`, diff --git a/packages/kbn-pm/src/utils/fs.ts b/packages/kbn-pm/src/utils/fs.ts index 9484c3a61e608..44fc59bdeba96 100644 --- a/packages/kbn-pm/src/utils/fs.ts +++ b/packages/kbn-pm/src/utils/fs.ts @@ -49,7 +49,7 @@ async function statTest(path: string, block: (stats: fs.Stats) => boolean) { * @param path */ export async function isSymlink(path: string) { - return await statTest(path, stats => stats.isSymbolicLink()); + return await statTest(path, (stats) => stats.isSymbolicLink()); } /** @@ -57,7 +57,7 @@ export async function isSymlink(path: string) { * @param path */ export async function isDirectory(path: string) { - return await statTest(path, stats => stats.isDirectory()); + return await statTest(path, (stats) => stats.isDirectory()); } /** @@ -65,7 +65,7 @@ export async function isDirectory(path: string) { * @param path */ export async function isFile(path: string) { - return await statTest(path, stats => stats.isFile()); + return await statTest(path, (stats) => stats.isFile()); } /** diff --git a/packages/kbn-pm/src/utils/kibana.ts b/packages/kbn-pm/src/utils/kibana.ts index 58af98b2a92db..7fca4bd01822b 100644 --- a/packages/kbn-pm/src/utils/kibana.ts +++ b/packages/kbn-pm/src/utils/kibana.ts @@ -103,11 +103,11 @@ export class Kibana { const allProjects = this.getAllProjects(); const filteredProjects: ProjectMap = new Map(); - const pkgJsonPaths = Array.from(allProjects.values()).map(p => p.packageJsonLocation); + const pkgJsonPaths = Array.from(allProjects.values()).map((p) => p.packageJsonLocation); const filteredPkgJsonGlobs = getProjectPaths({ ...options, rootPath: this.kibanaProject.path, - }).map(g => Path.resolve(g, 'package.json')); + }).map((g) => Path.resolve(g, 'package.json')); const matchingPkgJsonPaths = multimatch(pkgJsonPaths, filteredPkgJsonGlobs); for (const project of allProjects.values()) { diff --git a/packages/kbn-pm/src/utils/link_project_executables.test.ts b/packages/kbn-pm/src/utils/link_project_executables.test.ts index a6334ec850860..a19e1fd66f334 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.test.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.test.ts @@ -70,7 +70,7 @@ const projectGraph = buildProjectGraph(projectsByName); function getFsMockCalls() { const fs = require('./fs'); const fsMockCalls: { [key: string]: any[][] } = {}; - Object.keys(fs).map(key => { + Object.keys(fs).map((key) => { if (jest.isMockFunction(fs[key])) { fsMockCalls[key] = fs[key].mock.calls; } diff --git a/packages/kbn-pm/src/utils/link_project_executables.ts b/packages/kbn-pm/src/utils/link_project_executables.ts index 25fb11f17f782..b403dfb2ecf2e 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.ts @@ -55,9 +55,7 @@ export async function linkProjectExecutables( const dest = resolve(binsDir, name); // Get relative project path with normalized path separators. - const projectRelativePath = relative(project.path, srcPath) - .split(sep) - .join('/'); + const projectRelativePath = relative(project.path, srcPath).split(sep).join('/'); log.write(chalk`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); diff --git a/packages/kbn-pm/src/utils/parallelize.test.ts b/packages/kbn-pm/src/utils/parallelize.test.ts index fa23ecbb8c1e7..e85b40e0c67d8 100644 --- a/packages/kbn-pm/src/utils/parallelize.test.ts +++ b/packages/kbn-pm/src/utils/parallelize.test.ts @@ -22,7 +22,7 @@ import { parallelizeBatches } from './parallelize'; // As promises resolve async, we use this helper to wait for all promises that // have been resolved to complete (aka call `then`). const tick = () => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, 0); }); @@ -32,7 +32,7 @@ test('parallelizes batches', async () => { const baz = createPromiseWithResolve(); const batches = [[foo, bar], [baz]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { obj.called = true; await obj.promise; }); @@ -82,7 +82,7 @@ test('schedules at most 4 calls at the same time (concurrency)', async () => { const foobar = createPromiseWithResolve(); const batches = [[foo, bar, baz, quux, foobar]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { obj.called = true; await obj.promise; }); @@ -113,7 +113,7 @@ test('rejects if any promise rejects', async () => { const baz = createPromiseWithResolve(); const batches = [[foo, bar], [baz]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { await obj.promise; }); diff --git a/packages/kbn-pm/src/utils/project.ts b/packages/kbn-pm/src/utils/project.ts index 7b0bbed5c3f46..91a3a5365b60e 100644 --- a/packages/kbn-pm/src/utils/project.ts +++ b/packages/kbn-pm/src/utils/project.ts @@ -229,10 +229,10 @@ export class Project { // check for any cross-project dependency for (const name of Object.keys(workspacesInfo)) { const workspace = workspacesInfo[name]; - workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w)); + workspace.workspaceDependencies.forEach((w) => unusedWorkspaces.delete(w)); } - unusedWorkspaces.forEach(name => { + unusedWorkspaces.forEach((name) => { const { dependencies, devDependencies } = this.json; const nodeModulesPath = Path.resolve(this.nodeModulesLocation, name); const isDependency = dependencies && dependencies.hasOwnProperty(name); diff --git a/packages/kbn-pm/src/utils/project_checksums.ts b/packages/kbn-pm/src/utils/project_checksums.ts index 7d939e715d411..46dde1b32c158 100644 --- a/packages/kbn-pm/src/utils/project_checksums.ts +++ b/packages/kbn-pm/src/utils/project_checksums.ts @@ -49,8 +49,8 @@ async function getChangesForProjects(projects: ProjectMap, kbn: Kibana, log: Too '--exclude-standard', '--', ...Array.from(projects.values()) - .filter(p => kbn.isPartOfRepo(p)) - .map(p => p.path), + .filter((p) => kbn.isPartOfRepo(p)) + .map((p) => p.path), ], { cwd: kbn.getAbsolute(), @@ -265,7 +265,7 @@ export async function getAllChecksums(kbn: Kibana, log: ToolingLog) { const cacheKeys: ChecksumMap = new Map(); await Promise.all( - Array.from(projects.values()).map(async project => { + Array.from(projects.values()).map(async (project) => { cacheKeys.set( project.name, await getChecksum(project, changesByProject.get(project), yarnLock, kbn, log) diff --git a/packages/kbn-pm/src/utils/projects.test.ts b/packages/kbn-pm/src/utils/projects.test.ts index ba093b9d5eba1..068c72286872a 100644 --- a/packages/kbn-pm/src/utils/projects.test.ts +++ b/packages/kbn-pm/src/utils/projects.test.ts @@ -208,7 +208,7 @@ describe('#topologicallyBatchProjects', () => { test('batches projects topologically based on their project dependencies', async () => { const batches = topologicallyBatchProjects(projects, graph); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toMatchSnapshot(); }); @@ -219,7 +219,7 @@ describe('#topologicallyBatchProjects', () => { const batches = topologicallyBatchProjects(projects, graph); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toMatchSnapshot(); }); @@ -228,7 +228,7 @@ describe('#topologicallyBatchProjects', () => { test('batches projects topologically based on their project dependencies and workspaces', async () => { const batches = topologicallyBatchProjects(projects, graph, { batchByWorkspace: true }); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toEqual([['kibana'], ['bar', 'foo'], ['baz', 'zorge'], ['quux']]); }); diff --git a/packages/kbn-pm/src/utils/projects.ts b/packages/kbn-pm/src/utils/projects.ts index a6f174b1fc5a1..1c3bf0fa3091a 100644 --- a/packages/kbn-pm/src/utils/projects.ts +++ b/packages/kbn-pm/src/utils/projects.ts @@ -137,7 +137,9 @@ export function topologicallyBatchProjects( const batches = []; if (batchByWorkspace) { - const workspaceRootProject = Array.from(projectsToBatch.values()).find(p => p.isWorkspaceRoot); + const workspaceRootProject = Array.from(projectsToBatch.values()).find( + (p) => p.isWorkspaceRoot + ); if (!workspaceRootProject) { throw new CliError(`There was no yarn workspace root found.`); @@ -167,7 +169,7 @@ export function topologicallyBatchProjects( const batch = []; for (const projectName of projectsLeftToBatch) { const projectDeps = projectGraph.get(projectName)!; - const needsDependenciesBatched = projectDeps.some(dep => projectsLeftToBatch.has(dep.name)); + const needsDependenciesBatched = projectDeps.some((dep) => projectsLeftToBatch.has(dep.name)); if (!needsDependenciesBatched) { batch.push(projectsToBatch.get(projectName)!); @@ -188,7 +190,7 @@ export function topologicallyBatchProjects( batches.push(batch); - batch.forEach(project => projectsLeftToBatch.delete(project.name)); + batch.forEach((project) => projectsLeftToBatch.delete(project.name)); } return batches; @@ -211,7 +213,7 @@ export function includeTransitiveProjects( ? project.productionDependencies : project.allDependencies; - Object.keys(dependencies).forEach(dep => { + Object.keys(dependencies).forEach((dep) => { if (allProjects.has(dep)) { toProcess.push(allProjects.get(dep)!); } diff --git a/packages/kbn-pm/src/utils/watch.ts b/packages/kbn-pm/src/utils/watch.ts index 0ec8b50d83905..1998c5199fb73 100644 --- a/packages/kbn-pm/src/utils/watch.ts +++ b/packages/kbn-pm/src/utils/watch.ts @@ -56,20 +56,20 @@ function getWatchHandlers( }: IWatchOptions ) { const typescriptHandler = buildOutput$.pipe( - first(data => data.includes('$ tsc')), + first((data) => data.includes('$ tsc')), map(() => buildOutput$.pipe( - first(data => data.includes('Compilation complete.')), + first((data) => data.includes('Compilation complete.')), mapTo('tsc') ) ) ); const webpackHandler = buildOutput$.pipe( - first(data => data.includes('$ webpack')), + first((data) => data.includes('$ webpack')), map(() => buildOutput$.pipe( - first(data => data.includes('Chunk Names')), + first((data) => data.includes('Chunk Names')), mapTo('webpack') ) ) @@ -100,7 +100,7 @@ export function waitUntilWatchIsReady(stream: NodeJS.EventEmitter, opts: IWatchO return Rx.race(getWatchHandlers(buildOutput$, opts)) .pipe( - mergeMap(whenReady => whenReady), + mergeMap((whenReady) => whenReady), finalize(() => { stream.removeListener('data', onDataListener); stream.removeListener('end', onEndListener); diff --git a/packages/kbn-pm/src/utils/workspaces.ts b/packages/kbn-pm/src/utils/workspaces.ts index 22fa8636aea90..830a713e84ad4 100644 --- a/packages/kbn-pm/src/utils/workspaces.ts +++ b/packages/kbn-pm/src/utils/workspaces.ts @@ -48,7 +48,7 @@ export async function workspacePackagePaths(rootPath: string): Promise for (const pattern of workspacesPathsPatterns) { if (pattern.startsWith('!')) { const pathToRemove = path.join(rootPath, pattern.slice(1), 'package.json'); - workspaceProjectsPaths = workspaceProjectsPaths.filter(p => p !== pathToRemove); + workspaceProjectsPaths = workspaceProjectsPaths.filter((p) => p !== pathToRemove); } } diff --git a/packages/kbn-spec-to-console/bin/spec_to_console.js b/packages/kbn-spec-to-console/bin/spec_to_console.js index 20b42c67f3b89..432890a9cb903 100644 --- a/packages/kbn-spec-to-console/bin/spec_to_console.js +++ b/packages/kbn-spec-to-console/bin/spec_to_console.js @@ -46,7 +46,7 @@ console.log(); console.log(files); console.log(); -files.forEach(file => { +files.forEach((file) => { const spec = JSON.parse(fs.readFileSync(file)); const convertedSpec = convert(spec); if (!Object.keys(convertedSpec).length) { diff --git a/packages/kbn-spec-to-console/lib/convert.js b/packages/kbn-spec-to-console/lib/convert.js index 9648ef0b85a4f..bd0dbb429cff3 100644 --- a/packages/kbn-spec-to-console/lib/convert.js +++ b/packages/kbn-spec-to-console/lib/convert.js @@ -22,7 +22,7 @@ const convertMethods = require('./convert/methods'); const convertPaths = require('./convert/paths'); const convertParts = require('./convert/parts'); -module.exports = spec => { +module.exports = (spec) => { const result = {}; /** * TODO: @@ -34,7 +34,7 @@ module.exports = spec => { * from being used in autocompletion. It would be really nice if we could use this information * instead of just not including it. */ - Object.keys(spec).forEach(api => { + Object.keys(spec).forEach((api) => { const source = spec[api]; if (!source.url) { @@ -42,7 +42,7 @@ module.exports = spec => { } if (source.url.path) { - if (source.url.paths.every(path => Boolean(path.deprecated))) { + if (source.url.paths.every((path) => Boolean(path.deprecated))) { return; } } @@ -61,10 +61,10 @@ module.exports = spec => { if (source.url.paths) { // We filter out all deprecated url patterns here. - const paths = source.url.paths.filter(path => !path.deprecated); + const paths = source.url.paths.filter((path) => !path.deprecated); patterns = convertPaths(paths); - paths.forEach(pathsObject => { - pathsObject.methods.forEach(method => methodSet.add(method)); + paths.forEach((pathsObject) => { + pathsObject.methods.forEach((method) => methodSet.add(method)); if (pathsObject.parts) { for (const partName of Object.keys(pathsObject.parts)) { urlComponents[partName] = pathsObject.parts[partName]; @@ -79,7 +79,7 @@ module.exports = spec => { if (Object.keys(urlComponents).length) { const components = convertParts(urlComponents); const hasComponents = - Object.keys(components).filter(c => { + Object.keys(components).filter((c) => { return Boolean(components[c]); }).length > 0; if (hasComponents) { diff --git a/packages/kbn-spec-to-console/lib/convert/methods.js b/packages/kbn-spec-to-console/lib/convert/methods.js index b4ab8f467ae1f..89d193dd38071 100644 --- a/packages/kbn-spec-to-console/lib/convert/methods.js +++ b/packages/kbn-spec-to-console/lib/convert/methods.js @@ -17,6 +17,6 @@ * under the License. */ -module.exports = methods => { +module.exports = (methods) => { return methods; }; diff --git a/packages/kbn-spec-to-console/lib/convert/params.js b/packages/kbn-spec-to-console/lib/convert/params.js index 0d1747ae4f685..00169b12322ed 100644 --- a/packages/kbn-spec-to-console/lib/convert/params.js +++ b/packages/kbn-spec-to-console/lib/convert/params.js @@ -17,9 +17,9 @@ * under the License. */ -module.exports = params => { +module.exports = (params) => { const result = {}; - Object.keys(params).forEach(param => { + Object.keys(params).forEach((param) => { const { type, description = '', options = [] } = params[param]; const [, defaultValue] = description.match(/\(default: (.*)\)/) || []; switch (type) { @@ -35,7 +35,7 @@ module.exports = params => { case 'enum': // This is to clean up entries like: "d (Days)". We only want the "d" part. if (param === 'time') { - result[param] = options.map(option => option.split(' ')[0]); + result[param] = options.map((option) => option.split(' ')[0]); } else { result[param] = options; } diff --git a/packages/kbn-spec-to-console/lib/convert/parts.js b/packages/kbn-spec-to-console/lib/convert/parts.js index 040d04a0c1dc4..96cd3c94e796d 100644 --- a/packages/kbn-spec-to-console/lib/convert/parts.js +++ b/packages/kbn-spec-to-console/lib/convert/parts.js @@ -19,9 +19,9 @@ const replacePattern = require('../replace_pattern'); -module.exports = parts => { +module.exports = (parts) => { const result = {}; - Object.keys(parts).forEach(part => { + Object.keys(parts).forEach((part) => { const key = replacePattern(part, { exact: true }); const options = parts[part].options; if (options && options.length) { diff --git a/packages/kbn-spec-to-console/lib/convert/paths.js b/packages/kbn-spec-to-console/lib/convert/paths.js index 6c65bf48b9b06..af8897c2782f2 100644 --- a/packages/kbn-spec-to-console/lib/convert/paths.js +++ b/packages/kbn-spec-to-console/lib/convert/paths.js @@ -19,8 +19,8 @@ const replacePattern = require('../replace_pattern'); -module.exports = patterns => { - return patterns.map(patternObject => { +module.exports = (patterns) => { + return patterns.map((patternObject) => { return replacePattern(patternObject.path, { brackets: true }); }); }; diff --git a/packages/kbn-spec-to-console/lib/replace_pattern.js b/packages/kbn-spec-to-console/lib/replace_pattern.js index 29d16be3cc70f..4da75db78086d 100644 --- a/packages/kbn-spec-to-console/lib/replace_pattern.js +++ b/packages/kbn-spec-to-console/lib/replace_pattern.js @@ -21,7 +21,7 @@ const map = require('./static/map_interpolation'); module.exports = (pattern, { brackets, exact } = {}) => { let newPattern = pattern; - Object.keys(map).forEach(key => { + Object.keys(map).forEach((key) => { const replaceFrom = brackets ? `{${key}}` : key; const replaceTo = brackets ? `{${map[key]}}` : map[key]; if (exact) { diff --git a/packages/kbn-storybook/index.js b/packages/kbn-storybook/index.js index b595de8ea1c07..c7dae20902f1a 100644 --- a/packages/kbn-storybook/index.js +++ b/packages/kbn-storybook/index.js @@ -27,7 +27,7 @@ const { generateStorybookEntry } = require('./lib/storybook_entry'); const { REPO_ROOT, ASSET_DIR, CURRENT_CONFIG } = require('./lib/constants'); const { buildDll } = require('./lib/dll'); -exports.runStorybookCli = config => { +exports.runStorybookCli = (config) => { const { name, storyGlobs } = config; run( async ({ flags, log, procRunner }) => { diff --git a/packages/kbn-storybook/lib/storybook_entry.js b/packages/kbn-storybook/lib/storybook_entry.js index dececef47f40e..9eb1b0a458c6a 100644 --- a/packages/kbn-storybook/lib/storybook_entry.js +++ b/packages/kbn-storybook/lib/storybook_entry.js @@ -37,7 +37,7 @@ const STORE_ENTRY_DIR = dirname(STORY_ENTRY_PATH); exports.generateStorybookEntry = ({ log, storyGlobs }) => { const globs = ['built_assets/css/**/*.light.css', ...storyGlobs]; log.info('Storybook globs:\n', globs); - const norm = p => normalize(relative(STORE_ENTRY_DIR, p)); + const norm = (p) => normalize(relative(STORE_ENTRY_DIR, p)); return Rx.defer(() => glob(globs, { @@ -46,20 +46,20 @@ exports.generateStorybookEntry = ({ log, storyGlobs }) => { onlyFiles: true, }) ).pipe( - map(paths => { + map((paths) => { log.info('Discovered Storybook entry points:\n', paths); return new Set(paths.map(norm)); }), mergeMap( - paths => - new Rx.Observable(observer => { + (paths) => + new Rx.Observable((observer) => { observer.next(paths); const chokidar = watch(globs, { cwd: REPO_ROOT }) - .on('add', path => { + .on('add', (path) => { observer.next(paths.add(norm(resolve(REPO_ROOT, path)))); }) - .on('unlink', path => { + .on('unlink', (path) => { observer.next(paths.delete(norm(resolve(REPO_ROOT, path)))); }); diff --git a/packages/kbn-storybook/storybook_config/middleware.js b/packages/kbn-storybook/storybook_config/middleware.js index 046758948b2cf..9410bb66030d9 100644 --- a/packages/kbn-storybook/storybook_config/middleware.js +++ b/packages/kbn-storybook/storybook_config/middleware.js @@ -21,6 +21,6 @@ const serve = require('serve-static'); const path = require('path'); // Extend the Storybook Middleware to include a route to access Legacy UI assets -module.exports = function(router) { +module.exports = function (router) { router.get('/ui', serve(path.resolve(__dirname, '../../../src/core/server/core_app/assets'))); }; diff --git a/packages/kbn-storybook/storybook_config/mocks/noop.js b/packages/kbn-storybook/storybook_config/mocks/noop.js index aaddfb2ed8ac3..e78d222eaa560 100755 --- a/packages/kbn-storybook/storybook_config/mocks/noop.js +++ b/packages/kbn-storybook/storybook_config/mocks/noop.js @@ -17,4 +17,4 @@ * under the License. */ -export default function() {} +export default function () {} diff --git a/packages/kbn-storybook/storybook_config/webpack.config.js b/packages/kbn-storybook/storybook_config/webpack.config.js index 779d8a4153644..2dd051882bb4b 100644 --- a/packages/kbn-storybook/storybook_config/webpack.config.js +++ b/packages/kbn-storybook/storybook_config/webpack.config.js @@ -29,7 +29,7 @@ const { currentConfig } = require('../../../built_assets/storybook/current.confi module.exports = async ({ config }) => { // Find and alter the CSS rule to replace the Kibana public path string with a path // to the route we've added in middleware.js - const cssRule = config.module.rules.find(rule => rule.test.source.includes('.css$')); + const cssRule = config.module.rules.find((rule) => rule.test.source.includes('.css$')); cssRule.use.push({ loader: 'string-replace-loader', options: { diff --git a/packages/kbn-test-subj-selector/__tests__/index.js b/packages/kbn-test-subj-selector/__tests__/index.js index e18405b99ae52..23165cefec94a 100755 --- a/packages/kbn-test-subj-selector/__tests__/index.js +++ b/packages/kbn-test-subj-selector/__tests__/index.js @@ -20,8 +20,8 @@ const testSubjSelector = require('../'); const expect = require('@kbn/expect'); -describe('testSubjSelector()', function() { - it('converts subjectSelectors to cssSelectors', function() { +describe('testSubjSelector()', function () { + it('converts subjectSelectors to cssSelectors', function () { expect(testSubjSelector('foo bar')).to.eql('[data-test-subj="foo bar"]'); expect(testSubjSelector('foo > bar')).to.eql('[data-test-subj="foo"] [data-test-subj="bar"]'); expect(testSubjSelector('foo > bar baz')).to.eql( diff --git a/packages/kbn-test-subj-selector/index.js b/packages/kbn-test-subj-selector/index.js index 3984c15c00fef..2be59d78dc5ef 100755 --- a/packages/kbn-test-subj-selector/index.js +++ b/packages/kbn-test-subj-selector/index.js @@ -42,12 +42,7 @@ module.exports = function testSubjSelector(selector) { while (terms.length) { const term = terms.shift(); // split each term by joins/& and map to css selectors - cssSelectors.push( - term - .split('&') - .map(termToCssSelector) - .join('') - ); + cssSelectors.push(term.split('&').map(termToCssSelector).join('')); } return cssSelectors.join(' '); diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts index 0c824754b1237..7cbeb18a5ebd4 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts @@ -25,12 +25,8 @@ import { createPatch } from 'diff'; // turns out Jest can't encode xml diffs in their JUnit reports... expect.addSnapshotSerializer({ - test: v => typeof v === 'string' && (v.includes('<') || v.includes('>')), - print: v => - v - .replace(//g, '›') - .replace(/^\s+$/gm, ''), + test: (v) => typeof v === 'string' && (v.includes('<') || v.includes('>')), + print: (v) => v.replace(//g, '›').replace(/^\s+$/gm, ''), }); jest.mock('fs', () => { diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts index 32ea5fa0f9033..6bc7556db8a47 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts @@ -49,7 +49,7 @@ export async function addMessagesToReport(options: { for (const testCase of makeFailedTestCaseIter(report)) { const { classname, name } = testCase.$; const messageList = messages - .filter(u => u.classname === classname && u.name === name) + .filter((u) => u.classname === classname && u.name === name) .reduce((acc, u) => `${acc}\n - ${u.message}`, ''); if (!messageList) { @@ -76,7 +76,7 @@ export async function addMessagesToReport(options: { const xml = builder .buildObject(report) .split('\n') - .map(line => (line.trim() === '' ? '' : line)) + .map((line) => (line.trim() === '' ? '' : line)) .join('\n'); if (dryRun) { diff --git a/packages/kbn-test/src/failed_tests_reporter/github_api.ts b/packages/kbn-test/src/failed_tests_reporter/github_api.ts index 7da79b5b67e63..a0e3bcafdf196 100644 --- a/packages/kbn-test/src/failed_tests_reporter/github_api.ts +++ b/packages/kbn-test/src/failed_tests_reporter/github_api.ts @@ -233,7 +233,7 @@ export class GithubApi { this.log.error(`Unable to reach github, waiting ${waitMs}ms to retry`); } - await new Promise(resolve => setTimeout(resolve, waitMs)); + await new Promise((resolve) => setTimeout(resolve, waitMs)); return await this.request( { ...options, diff --git a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts index 9324f9eb42aa5..b298c08f162bf 100644 --- a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts +++ b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts @@ -100,7 +100,7 @@ export function runFailedTestsReporterCli() { } let existingIssue: GithubIssueMini | undefined = await githubApi.findFailedTestIssue( - i => + (i) => getIssueMetadata(i.body, 'test.class') === failure.classname && getIssueMetadata(i.body, 'test.name') === failure.name ); diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js index 3c8daf4154236..133f4d2feb53e 100644 --- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js +++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js @@ -26,7 +26,7 @@ import { REPO_ROOT } from '@kbn/dev-utils'; const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js'); const BASIC_CONFIG = require.resolve('../fixtures/simple_project/config.js'); -describe('basic config file with a single app and test', function() { +describe('basic config file with a single app and test', function () { this.timeout(60 * 1000); it('runs and prints expected output', () => { diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js index d6e7b1ac58aa4..12e28d2702c5a 100644 --- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js +++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js @@ -27,7 +27,7 @@ import { REPO_ROOT } from '@kbn/dev-utils'; const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js'); const FAILURE_HOOKS_CONFIG = require.resolve('../fixtures/failure_hooks/config.js'); -describe('failure hooks', function() { +describe('failure hooks', function () { this.timeout(60 * 1000); it('runs and prints expected output', () => { diff --git a/packages/kbn-test/src/functional_test_runner/cli.ts b/packages/kbn-test/src/functional_test_runner/cli.ts index 276a51c3a6a99..fd5ee5ad3ae44 100644 --- a/packages/kbn-test/src/functional_test_runner/cli.ts +++ b/packages/kbn-test/src/functional_test_runner/cli.ts @@ -87,7 +87,7 @@ export function runFtrCli() { } }; - process.on('unhandledRejection', err => + process.on('unhandledRejection', (err) => teardown( err instanceof Error ? err : new Error(`non-Error type rejection value: ${inspect(err)}`) ) diff --git a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts index 3a66ba22ccf3d..03d4d7643607f 100644 --- a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts +++ b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts @@ -89,7 +89,7 @@ export class FunctionalTestRunner { // promise-like objects which never resolve, essentially disabling them // allowing us to load the test files and populate the mocha suites const readStubbedProviderSpec = (type: string, providers: any) => - readProviderSpec(type, providers).map(p => ({ + readProviderSpec(type, providers).map((p) => ({ ...p, fn: () => ({ then: () => {}, diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts index ad9247523797a..e38520f00e45b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts @@ -114,7 +114,7 @@ export class Config { throw new Error(`Unknown config key "${key}"`); } - return cloneDeep(get(this[$values], key, defaultValue), v => { + return cloneDeep(get(this[$values], key, defaultValue), (v) => { if (typeof v === 'function') { return v; } @@ -122,7 +122,7 @@ export class Config { } public getAll() { - return cloneDeep(this[$values], v => { + return cloneDeep(this[$values], (v) => { if (typeof v === 'function') { return v; } diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts index f4b91d154cbb8..29ec28175a851 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts @@ -30,12 +30,8 @@ const INSPECTING = const urlPartsSchema = () => Joi.object() .keys({ - protocol: Joi.string() - .valid('http', 'https') - .default('http'), - hostname: Joi.string() - .hostname() - .default('localhost'), + protocol: Joi.string().valid('http', 'https').default('http'), + hostname: Joi.string().hostname().default('localhost'), port: Joi.number(), auth: Joi.string().regex(/^[^:]+:.+$/, 'username and password separated by a colon'), username: Joi.string(), @@ -66,33 +62,21 @@ export const schema = Joi.object() suiteFiles: Joi.object() .keys({ - include: Joi.array() - .items(Joi.string()) - .default([]), - exclude: Joi.array() - .items(Joi.string()) - .default([]), + include: Joi.array().items(Joi.string()).default([]), + exclude: Joi.array().items(Joi.string()).default([]), }) .default(), suiteTags: Joi.object() .keys({ - include: Joi.array() - .items(Joi.string()) - .default([]), - exclude: Joi.array() - .items(Joi.string()) - .default([]), + include: Joi.array().items(Joi.string()).default([]), + exclude: Joi.array().items(Joi.string()).default([]), }) .default(), - services: Joi.object() - .pattern(ID_PATTERN, Joi.func().required()) - .default(), + services: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(), - pageObjects: Joi.object() - .pattern(ID_PATTERN, Joi.func().required()) - .default(), + pageObjects: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(), timeouts: Joi.object() .keys({ @@ -135,9 +119,7 @@ export const schema = Joi.object() browser: Joi.object() .keys({ - type: Joi.string() - .valid('chrome', 'firefox', 'ie', 'msedge') - .default('chrome'), + type: Joi.string().valid('chrome', 'firefox', 'ie', 'msedge').default('chrome'), logPollingMs: Joi.number().default(100), }) @@ -210,9 +192,7 @@ export const schema = Joi.object() .default(), // definition of apps that work with `common.navigateToApp()` - apps: Joi.object() - .pattern(ID_PATTERN, appUrlPartsSchema()) - .default(), + apps: Joi.object().pattern(ID_PATTERN, appUrlPartsSchema()).default(), // settings for the esArchiver module esArchiver: Joi.object() diff --git a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts index be033e063fb9d..fdf8b3c0ddfa8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts @@ -39,7 +39,7 @@ export class FailureMetadata { ); } - lifecycle.beforeEachRunnable.add(runnable => { + lifecycle.beforeEachRunnable.add((runnable) => { this.currentRunnable = runnable; }); } @@ -57,7 +57,7 @@ export class FailureMetadata { } addMessages(messages: string[]) { - this.add(current => ({ + this.add((current) => ({ messages: [...(Array.isArray(current.messages) ? current.messages : []), ...messages], })); } @@ -76,7 +76,7 @@ export class FailureMetadata { const slash = prefix.endsWith('/') ? '' : '/'; const urlPath = Path.relative(REPO_ROOT, repoPath) .split(Path.sep) - .map(c => encodeURIComponent(c)) + .map((c) => encodeURIComponent(c)) .join('/'); if (urlPath.startsWith('..')) { @@ -91,7 +91,7 @@ export class FailureMetadata { url, }; - this.add(current => ({ + this.add((current) => ({ screenshots: [...(Array.isArray(current.screenshots) ? current.screenshots : []), screenshot], })); diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts index 22b7363454361..ce242d44009f2 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts @@ -57,7 +57,7 @@ export class LifecycleEvent { } try { - await Promise.all(this.handlers.map(async fn => await fn(...args))); + await Promise.all(this.handlers.map(async (fn) => await fn(...args))); } finally { this.afterSubj.next(undefined); if (this.options.singular) { diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts index 94dd76884f2ca..d17c5503c42f8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts @@ -104,7 +104,7 @@ describe('without randomness', () => { const handler = jest.fn(async () => { order.push('handler start'); - await new Promise(resolve => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); order.push('handler done'); }); phase.add(handler); @@ -124,10 +124,10 @@ describe('without randomness', () => { const phase = new LifecyclePhase({ singular: true }); const beforeNotifs: Array> = []; - phase.before$.pipe(materialize()).subscribe(n => beforeNotifs.push(n)); + phase.before$.pipe(materialize()).subscribe((n) => beforeNotifs.push(n)); const afterNotifs: Array> = []; - phase.after$.pipe(materialize()).subscribe(n => afterNotifs.push(n)); + phase.after$.pipe(materialize()).subscribe((n) => afterNotifs.push(n)); await phase.trigger(); expect(beforeNotifs).toMatchInlineSnapshot(` diff --git a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts index 26a0e9617a7c7..588e32b5d274c 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts @@ -22,7 +22,7 @@ const globalLoadPath: Array<{ ident: string; description: string }> = []; function getPath(startAt = 0) { return globalLoadPath .slice(startAt) - .map(step => step.description) + .map((step) => step.description) .join(' -> '); } @@ -49,7 +49,7 @@ function addPathToMessage(message: string, startAt?: number) { * @return {Any} the value produced by load() */ export function loadTracer(ident: any, description: string, load: () => Promise | void) { - const isCircular = globalLoadPath.find(step => step.ident === ident); + const isCircular = globalLoadPath.find((step) => step.ident === ident); if (isCircular) { throw new Error(addPathToMessage(`Circular reference to "${description}"`)); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js index 5c08d566d3d73..ecf8f7af87ed8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js @@ -31,7 +31,7 @@ export function createAssignmentProxy(object, interceptor) { get(target, property) { if (property === 'revertProxiedAssignments') { - return function() { + return function () { for (const [property, value] of originalValues) { object[property] = value; } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js index 1cac852a7e713..5d3d8fe7d759b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js @@ -57,12 +57,12 @@ export function decorateMochaUi(lifecycle, context) { throw new Error(`Unexpected arguments to ${name}(${argumentsList.join(', ')})`); } - argumentsList[1] = function() { + argumentsList[1] = function () { before(async () => { await lifecycle.beforeTestSuite.trigger(this); }); - this.tags = tags => { + this.tags = (tags) => { this._tags = [].concat(this._tags || [], tags); }; diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js index 302d43fac3e61..f7aaabd5a4495 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js @@ -30,7 +30,7 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { mocha.excludedTests = []; // collect all the tests from some suite, including it's children - const collectTests = suite => + const collectTests = (suite) => suite.suites.reduce((acc, s) => acc.concat(collectTests(s)), suite.tests); // if include tags were provided, filter the tree once to @@ -38,8 +38,10 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { if (include.length) { log.info('Only running suites (and their sub-suites) if they include the tag(s):', include); - const isIncluded = suite => (!suite._tags ? false : suite._tags.some(t => include.includes(t))); - const isChildIncluded = suite => suite.suites.some(s => isIncluded(s) || isChildIncluded(s)); + const isIncluded = (suite) => + !suite._tags ? false : suite._tags.some((t) => include.includes(t)); + const isChildIncluded = (suite) => + suite.suites.some((s) => isIncluded(s) || isChildIncluded(s)); (function recurse(parentSuite) { const children = parentSuite.suites; @@ -73,7 +75,7 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { if (exclude.length) { log.info('Filtering out any suites that include the tag(s):', exclude); - const isNotExcluded = suite => !suite._tags || !suite._tags.some(t => exclude.includes(t)); + const isNotExcluded = (suite) => !suite._tags || !suite._tags.some((t) => exclude.includes(t)); (function recurse(parentSuite) { const children = parentSuite.suites; diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js index 9901f62ae71cf..6ecfadfd25d6d 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js @@ -26,21 +26,21 @@ import Test from 'mocha/lib/test'; import { filterSuitesByTags } from './filter_suites_by_tags'; function setup({ include, exclude }) { - return new Promise(resolve => { + return new Promise((resolve) => { const history = []; const mocha = new Mocha({ reporter: class { constructor(runner) { - runner.on('hook', hook => { + runner.on('hook', (hook) => { history.push(`hook: ${hook.fullTitle()}`); }); - runner.on('pass', test => { + runner.on('pass', (test) => { history.push(`test: ${test.fullTitle()}`); }); - runner.on('suite', suite => { + runner.on('suite', (suite) => { history.push(`suite: ${suite.fullTitle()}`); }); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js index 6ee65b1b7e394..5c23be6361866 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js @@ -32,7 +32,7 @@ import { decorateMochaUi } from './decorate_mocha_ui'; * @return {undefined} - mutates mocha, no return value */ export const loadTestFiles = ({ mocha, log, lifecycle, providers, paths, updateBaselines }) => { - const innerLoadTestFile = path => { + const innerLoadTestFile = (path) => { if (typeof path !== 'string' || !isAbsolute(path)) { throw new TypeError('loadTestFile() only accepts absolute paths'); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js index 0e8c1bc121e15..90bea1c3aa293 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js @@ -54,7 +54,7 @@ export function MochaReporterProvider({ getService }) { if (config.get('junit.enabled') && config.get('junit.reportName')) { setupJUnitReportGeneration(runner, { reportName: config.get('junit.reportName'), - getTestMetadata: t => failureMetadata.get(t), + getTestMetadata: (t) => failureMetadata.get(t), }); } } @@ -76,7 +76,7 @@ export function MochaReporterProvider({ getService }) { new ToolingLogTextWriter({ level: 'debug', writeTo: { - write: line => { + write: (line) => { // if the current runnable is a beforeEach hook then // `runner.suite` is set to the suite that defined the // hook, rather than the suite executing, so instead we @@ -104,7 +104,7 @@ export function MochaReporterProvider({ getService }) { log.write(''); }; - onHookStart = hook => { + onHookStart = (hook) => { log.write(`-> ${colors.suite(hook.title)}`); log.indent(2); }; @@ -113,7 +113,7 @@ export function MochaReporterProvider({ getService }) { log.indent(-2); }; - onSuiteStart = suite => { + onSuiteStart = (suite) => { if (!suite.root) { log.write('-: ' + colors.suite(suite.title)); } @@ -127,28 +127,28 @@ export function MochaReporterProvider({ getService }) { } }; - onTestStart = test => { + onTestStart = (test) => { log.write(`-> ${test.title}`); log.indent(2); }; - onTestEnd = test => { + onTestEnd = (test) => { snapshotLogsForRunnable(test); log.indent(-2); }; - onPending = test => { + onPending = (test) => { log.write('-> ' + colors.pending(test.title)); log.indent(2); }; - onPass = test => { + onPass = (test) => { const time = colors.speed(test.speed, ` (${ms(test.duration)})`); const pass = colors.pass(`${symbols.ok} pass`); log.write(`- ${pass} ${time} "${test.fullTitle()}"`); }; - onFail = runnable => { + onFail = (runnable) => { // NOTE: this is super gross // // - I started by trying to extract the Base.list() logic from mocha @@ -173,8 +173,8 @@ export function MochaReporterProvider({ getService }) { // drop the first two lines, (empty + test title) .slice(2) // move leading colors behind leading spaces - .map(line => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1')) - .map(line => ` ${line}`) + .map((line) => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1')) + .map((line) => ` ${line}`) .join('\n') ); diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts index 654f588fda858..a23a5fb1407a0 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts @@ -39,7 +39,7 @@ export async function runTests(lifecycle: Lifecycle, mocha: Mocha) { if (!runComplete) runner.abort(); }); - return new Promise(resolve => { + return new Promise((resolve) => { const respond = () => resolve(runner.failures); // if there are no tests, mocha.run() is sync diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js index 61851cece0e8f..3ac7a50cd28ea 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js @@ -42,7 +42,7 @@ export async function setupMocha(lifecycle, log, config, providers) { }); // global beforeEach hook in root suite triggers before all others - mocha.suite.beforeEach('global before each', async function() { + mocha.suite.beforeEach('global before each', async function () { await lifecycle.beforeEachTest.trigger(this.currentTest); }); @@ -62,15 +62,15 @@ export async function setupMocha(lifecycle, log, config, providers) { filterSuitesByTags({ log, mocha, - include: config.get('suiteFiles.include').map(file => relative(REPO_ROOT, file)), - exclude: config.get('suiteFiles.exclude').map(file => relative(REPO_ROOT, file)), + include: config.get('suiteFiles.include').map((file) => relative(REPO_ROOT, file)), + exclude: config.get('suiteFiles.exclude').map((file) => relative(REPO_ROOT, file)), }); filterSuitesByTags({ log, mocha, - include: config.get('suiteTags.include').map(tag => tag.replace(/-\d+$/, '')), - exclude: config.get('suiteTags.exclude').map(tag => tag.replace(/-\d+$/, '')), + include: config.get('suiteTags.include').map((tag) => tag.replace(/-\d+$/, '')), + exclude: config.get('suiteTags.exclude').map((tag) => tag.replace(/-\d+$/, '')), }); return mocha; diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts index 7bb1b2bc153c1..2d5644fbad290 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts @@ -34,7 +34,7 @@ export const createAsyncInstance = ( ): AsyncInstance => { let instance: T | symbol = INITIALIZING; - const initPromise = promiseForValue.then(v => (instance = v)); + const initPromise = promiseForValue.then((v) => (instance = v)); const loadingTarget = { init() { return initPromise; diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts index f9ad86be634fc..c58747e07dcf4 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts @@ -37,7 +37,7 @@ export class ProviderCollection { public getPageObjects = (names: string[]) => { const pageObjects: Record = {}; - names.forEach(name => (pageObjects[name] = this.getPageObject(name))); + names.forEach((name) => (pageObjects[name] = this.getPageObject(name))); return pageObjects; }; @@ -78,7 +78,7 @@ export class ProviderCollection { } private findProvider(type: string, name: string) { - return this.providers.find(p => p.type === type && p.name === name); + return this.providers.find((p) => p.type === type && p.name === name); } private getProvider(type: string, name: string) { diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts index be8e25f102b09..a29b220bc603b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts @@ -21,7 +21,7 @@ export type Providers = ReturnType; export type Provider = Providers extends Array ? X : unknown; export function readProviderSpec(type: string, providers: Record any>) { - return Object.keys(providers).map(name => { + return Object.keys(providers).map((name) => { return { type, name, diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts index 93a87f3496b54..1967e98306d42 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts @@ -23,7 +23,7 @@ import { ToolingLog } from '@kbn/dev-utils'; function printArgs(args: any[]): string { return args - .map(arg => { + .map((arg) => { if (typeof arg === 'string' || typeof arg === 'number' || arg instanceof Date) { return inspect(arg); } @@ -42,7 +42,7 @@ export function createVerboseInstance( name: string, instance: { [k: string]: any; [i: number]: any } ) { - if (!log.getWriters().some(l => (l as any).level.flags.verbose)) { + if (!log.getWriters().some((l) => (l as any).level.flags.verbose)) { return instance; } @@ -54,7 +54,7 @@ export function createVerboseInstance( return value; } - return function(this: any, ...args: any[]) { + return function (this: any, ...args: any[]) { log.verbose(`${name}.${prop}(${printArgs(args)})`); log.indent(2); diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts index b6c2c0a6d511d..f879408bf2beb 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts @@ -145,8 +145,8 @@ describe('SuiteTracker', () => { const { suiteTracker } = await runLifecycleWithMocks([root, parent, withTests]); const suites = suiteTracker.getAllFinishedSuites(); - const finishedRoot = suites.find(s => s.title === 'root'); - const finishedWithTests = suites.find(s => s.title !== 'root'); + const finishedRoot = suites.find((s) => s.title === 'root'); + const finishedWithTests = suites.find((s) => s.title !== 'root'); expect(finishedRoot).toBeTruthy(); expect(finishedRoot?.hasTests).toBeFalsy(); diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts index 8967251ea78de..b346be2d58dad 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts @@ -70,7 +70,7 @@ export class SuiteTracker { const config = relative(REPO_ROOT, configPathAbsolute); - lifecycle.beforeTestSuite.add(suite => { + lifecycle.beforeTestSuite.add((suite) => { const tracked = this.getTracked(suite); tracked.startTime = new Date(); }); @@ -92,7 +92,7 @@ export class SuiteTracker { lifecycle.testFailure.add(handleFailure); lifecycle.testHookFailure.add(handleFailure); - lifecycle.afterTestSuite.add(suite => { + lifecycle.afterTestSuite.add((suite) => { const tracked = this.getTracked(suite); tracked.endTime = new Date(); diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js index 7d2414305de8e..94d510915d8e5 100644 --- a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js +++ b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js @@ -73,8 +73,8 @@ const options = { export function displayHelp() { const helpOptions = Object.keys(options) - .filter(name => name !== '_') - .map(name => { + .filter((name) => name !== '_') + .map((name) => { const option = options[name]; return { ...option, @@ -82,7 +82,7 @@ export function displayHelp() { default: option.defaultHelp || '', }; }) - .map(option => { + .map((option) => { return `--${option.usage.padEnd(28)} ${option.desc} ${option.default}`; }) .join(`\n `); @@ -149,7 +149,7 @@ export function processOptions(userOptions, defaultConfigPaths) { return { ...userOptions, - configs: configs.map(c => resolve(c)), + configs: configs.map((c) => resolve(c)), createLogger, extraKbnOpts: userOptions._, }; diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js index 27335739d290e..cf49fc77e479f 100644 --- a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js +++ b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js @@ -30,7 +30,7 @@ import { processOptions, displayHelp } from './args'; * if no config option is passed */ export async function runTestsCli(defaultConfigPaths) { - await runCli(displayHelp, async userOptions => { + await runCli(displayHelp, async (userOptions) => { const options = processOptions(userOptions, defaultConfigPaths); await runTests(options); }); diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js index c221ad42fcad1..e604e86de8b3a 100644 --- a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js +++ b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js @@ -45,8 +45,8 @@ const options = { export function displayHelp() { const helpOptions = Object.keys(options) - .filter(name => name !== '_') - .map(name => { + .filter((name) => name !== '_') + .map((name) => { const option = options[name]; return { ...option, @@ -54,7 +54,7 @@ export function displayHelp() { default: option.defaultHelp || '', }; }) - .map(option => { + .map((option) => { return `--${option.usage.padEnd(30)} ${option.desc} ${option.default}`; }) .join(`\n `); diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js index 5716441798aa4..d4499ee76e313 100644 --- a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js +++ b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js @@ -27,7 +27,7 @@ import { processOptions, displayHelp } from './args'; * if no config option is passed */ export async function startServersCli(defaultConfigPath) { - await runCli(displayHelp, async userOptions => { + await runCli(displayHelp, async (userOptions) => { const options = processOptions(userOptions, defaultConfigPath); await startServers(options); }); diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.js b/packages/kbn-test/src/functional_tests/lib/run_cli.js index 56f6f36f5388f..51a970e1a305d 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_cli.js +++ b/packages/kbn-test/src/functional_tests/lib/run_cli.js @@ -53,12 +53,7 @@ export async function runCli(getHelpText, run) { if (!(error instanceof CliError)) { // first line in the stack trace is the message, skip it as we log it directly and color it red if (error.stack) { - console.log( - error.stack - .split('\n') - .slice(1) - .join('\n') - ); + console.log(error.stack.split('\n').slice(1).join('\n')); } else { console.log(' (no stack trace)'); } diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js index 235f50f0d9dd7..959f965917530 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js +++ b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js @@ -25,7 +25,7 @@ const mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(() => {}); const actualProcessArgv = process.argv; -const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); beforeEach(() => { process.argv = actualProcessArgv.slice(0, 2); @@ -72,7 +72,7 @@ it('waits for promise returned from run function to resolve before resolving', a let resolveMockRun; const mockRun = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { resolveMockRun = resolve; }) ); diff --git a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js index 5f58190078f0d..3d174791fffc1 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js +++ b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js @@ -63,7 +63,7 @@ export async function runElasticsearch({ config, options }) { function getRelativeCertificateAuthorityPath(esConfig = []) { const caConfig = esConfig.find( - config => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0 + (config) => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0 ); return caConfig ? caConfig.split('=')[1] : undefined; } diff --git a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js index a5744d6498801..fb9f8f7a52408 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js +++ b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js @@ -58,9 +58,9 @@ function collectCliArgs(config, { installDir, extraKbnOpts }) { return pipe( serverArgs, - args => (installDir ? args.filter(a => a !== '--oss') : args), - args => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]), - args => args.concat(extraKbnOpts || []) + (args) => (installDir ? args.filter((a) => a !== '--oss') : args), + (args) => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]), + (args) => args.concat(extraKbnOpts || []) ); } @@ -79,7 +79,7 @@ function filterCliArgs(args) { // the current val. If so, skip this val. if ( !allowsDuplicate(val) && - findIndexFrom(args, ++ind, opt => opt.split('=')[0] === val.split('=')[0]) > -1 + findIndexFrom(args, ++ind, (opt) => opt.split('=')[0] === val.split('=')[0]) > -1 ) { return acc; } @@ -112,7 +112,7 @@ function isBasePathSettingOverridden(args, val, ind) { const basePathKeys = ['--no-base-path', '--server.basePath']; if (basePathKeys.includes(key)) { - if (findIndexFrom(args, ++ind, opt => basePathKeys.includes(opt.split('=')[0])) > -1) { + if (findIndexFrom(args, ++ind, (opt) => basePathKeys.includes(opt.split('=')[0])) > -1) { return true; } } diff --git a/packages/kbn-test/src/functional_tests/tasks.js b/packages/kbn-test/src/functional_tests/tasks.js index 8645923a13d30..7d4fc84d47bda 100644 --- a/packages/kbn-test/src/functional_tests/tasks.js +++ b/packages/kbn-test/src/functional_tests/tasks.js @@ -34,7 +34,7 @@ import { import { readConfigFile } from '../functional_test_runner/lib'; -const makeSuccessMessage = options => { +const makeSuccessMessage = (options) => { const installDirFlag = options.installDir ? ` --kibana-install-dir=${options.installDir}` : ''; return ( @@ -92,7 +92,7 @@ export async function runTests(options) { continue; } - await withProcRunner(log, async procs => { + await withProcRunner(log, async (procs) => { const config = await readConfigFile(log, configPath); let es; @@ -128,7 +128,7 @@ export async function startServers(options) { log, }; - await withProcRunner(log, async procs => { + await withProcRunner(log, async (procs) => { const config = await readConfigFile(log, options.config); const es = await runElasticsearch({ config, options: opts }); diff --git a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js index 6edd0a551ebd0..00a11432dd9e8 100644 --- a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js +++ b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js @@ -49,8 +49,8 @@ describe('dev/mocha/junit report generation', () => { }); mocha.addFile(resolve(PROJECT_DIR, 'test.js')); - await new Promise(resolve => mocha.run(resolve)); - const report = await fcb(cb => + await new Promise((resolve) => mocha.run(resolve)); + const report = await fcb((cb) => parseString(readFileSync(makeJunitReportPath(PROJECT_DIR, 'test')), cb) ); diff --git a/packages/kbn-test/src/mocha/junit_report_generation.js b/packages/kbn-test/src/mocha/junit_report_generation.js index b56741b48d367..7e39c32ee4db8 100644 --- a/packages/kbn-test/src/mocha/junit_report_generation.js +++ b/packages/kbn-test/src/mocha/junit_report_generation.js @@ -39,26 +39,26 @@ export function setupJUnitReportGeneration(runner, options = {}) { const stats = {}; const results = []; - const getDuration = node => + const getDuration = (node) => node.startTime && node.endTime ? ((node.endTime - node.startTime) / 1000).toFixed(3) : null; - const findAllTests = suite => + const findAllTests = (suite) => suite.suites.reduce((acc, suite) => acc.concat(findAllTests(suite)), suite.tests); - const setStartTime = node => { + const setStartTime = (node) => { node.startTime = dateNow(); }; - const setEndTime = node => { + const setEndTime = (node) => { node.endTime = dateNow(); }; - const getFullTitle = node => { + const getFullTitle = (node) => { const parentTitle = node.parent && getFullTitle(node.parent); return parentTitle ? `${parentTitle} ${node.title}` : node.title; }; - const getPath = node => { + const getPath = (node) => { if (node.file) { return relative(rootDirectory, node.file); } @@ -75,7 +75,7 @@ export function setupJUnitReportGeneration(runner, options = {}) { runner.on('hook', setStartTime); runner.on('hook end', setEndTime); runner.on('test', setStartTime); - runner.on('pass', node => results.push({ node })); + runner.on('pass', (node) => results.push({ node })); runner.on('pass', setEndTime); runner.on('fail', (node, error) => results.push({ failed: true, error, node })); runner.on('fail', setEndTime); @@ -89,16 +89,16 @@ export function setupJUnitReportGeneration(runner, options = {}) { } // filter out just the failures - const failures = results.filter(result => result.failed); + const failures = results.filter((result) => result.failed); // any failure that isn't for a test is for a hook - const failedHooks = failures.filter(result => !allTests.includes(result.node)); + const failedHooks = failures.filter((result) => !allTests.includes(result.node)); // mocha doesn't emit 'pass' or 'fail' when it skips a test // or a test is pending, so we find them ourselves const skippedResults = allTests - .filter(node => node.pending || !results.find(result => result.node === node)) - .map(node => ({ skipped: true, node })); + .filter((node) => node.pending || !results.find((result) => result.node === node)) + .map((node) => ({ skipped: true, node })); const builder = xmlBuilder.create( 'testsuites', @@ -124,7 +124,7 @@ export function setupJUnitReportGeneration(runner, options = {}) { }); } - [...results, ...skippedResults].forEach(result => { + [...results, ...skippedResults].forEach((result) => { const el = addTestcaseEl(result.node); if (result.failed) { diff --git a/packages/kbn-test/src/mocha/run_mocha_cli.js b/packages/kbn-test/src/mocha/run_mocha_cli.js index 77f40aded1d7f..3c77fef963a76 100644 --- a/packages/kbn-test/src/mocha/run_mocha_cli.js +++ b/packages/kbn-test/src/mocha/run_mocha_cli.js @@ -85,7 +85,7 @@ export function runMochaCli() { ], } ) - .forEach(file => { + .forEach((file) => { process.argv.push(file); }); } diff --git a/packages/kbn-ui-framework/Gruntfile.js b/packages/kbn-ui-framework/Gruntfile.js index cf0c1643055eb..177fd1f153155 100644 --- a/packages/kbn-ui-framework/Gruntfile.js +++ b/packages/kbn-ui-framework/Gruntfile.js @@ -26,7 +26,7 @@ const debounce = require('lodash/function/debounce'); const platform = require('os').platform(); const isPlatformWindows = /^win/.test(platform); -module.exports = function(grunt) { +module.exports = function (grunt) { grunt.initConfig({ clean: { target: ['target'], @@ -62,7 +62,7 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('prodBuild', ['clean:target', 'copy:makeProdBuild', 'babel:prodBuild']); - grunt.registerTask('docSiteBuild', function() { + grunt.registerTask('docSiteBuild', function () { const done = this.async(); const serverCmd = { @@ -94,17 +94,17 @@ module.exports = function(grunt) { uiFrameworkServerBuild.then(done); }); - grunt.registerTask('docSiteStart', function() { + grunt.registerTask('docSiteStart', function () { const done = this.async(); Promise.all([uiFrameworkWatch(), uiFrameworkServerStart()]).then(done); }); - grunt.registerTask('compileCssLight', function() { + grunt.registerTask('compileCssLight', function () { const done = this.async(); uiFrameworkCompileLight().then(done); }); - grunt.registerTask('compileCssDark', function() { + grunt.registerTask('compileCssDark', function () { const done = this.async(); uiFrameworkCompileDark().then(done); }); @@ -146,19 +146,19 @@ module.exports = function(grunt) { const src = 'src/kui_light.scss'; const dest = 'dist/kui_light.css'; - return new Promise(resolve => { + return new Promise((resolve) => { sass.render( { file: src, }, - function(error, result) { + function (error, result) { if (error) { grunt.log.error(error); } postcss([postcssConfig]) .process(result.css, { from: src, to: dest }) - .then(result => { + .then((result) => { grunt.file.write(dest, result.css); if (result.map) { @@ -176,19 +176,19 @@ module.exports = function(grunt) { const src = 'src/kui_dark.scss'; const dest = 'dist/kui_dark.css'; - return new Promise(resolve => { + return new Promise((resolve) => { sass.render( { file: src, }, - function(error, result) { + function (error, result) { if (error) { grunt.log.error(error); } postcss([postcssConfig]) .process(result.css, { from: src, to: dest }) - .then(result => { + .then((result) => { grunt.file.write(dest, result.css); if (result.map) { diff --git a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js index 205be7920aa60..1836d00af4ab3 100644 --- a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js +++ b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js @@ -25,7 +25,7 @@ export const registerSection = (id, name) => ({ name, }); -export const unregisterSection = id => ({ +export const unregisterSection = (id) => ({ type: ActionTypes.UNREGISTER_SECTION, id, }); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js index f5845becbe77f..41aeb74d24b6b 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js @@ -19,4 +19,4 @@ import React from 'react'; -export const GuideCode = props => {props.children}; +export const GuideCode = (props) => {props.children}; diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js index b1d2f8e031f7c..b387a89b7072c 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js @@ -65,7 +65,7 @@ export class GuideCodeViewer extends Component { 'is-code-viewer-open': this.props.isOpen, }); - const codeSections = this.props.source.map(sourceObject => + const codeSections = this.props.source.map((sourceObject) => this.renderSection(sourceObject.type, sourceObject.code) ); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js index 93470ac6de128..d968e014370f8 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js @@ -68,7 +68,7 @@ export class GuideDemo extends Component { }); return ( -
(this.content = c)} {...rest}> +
(this.content = c)} {...rest}> {children}
); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js index b49880e0e3bfa..62d1e3ac8bedd 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js @@ -19,7 +19,7 @@ import React from 'react'; -export const GuideLink = props => ( +export const GuideLink = (props) => ( {props.children} diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js index f31a3b10eef4e..49225c96ba5e5 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js @@ -120,7 +120,7 @@ export class GuideNav extends Component { }); const componentNavItems = this.props.components - .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) + .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) .map((item, index) => { const icon = item.hasReact ?
: undefined; return ( @@ -135,7 +135,7 @@ export class GuideNav extends Component { }); const sandboxNavItems = this.props.sandboxes - .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) + .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) .map((item, index) => { const icon = item.hasReact ?
: undefined; return ( diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js index 5d8e6993abe4e..0a7442fce4723 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js @@ -21,7 +21,7 @@ import { connect } from 'react-redux'; import { getSections } from '../../store'; import { GuidePage } from './guide_page'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ sections: getSections(state), }); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js index bd7dc0705c6d9..9aeca1b30e03d 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js @@ -20,7 +20,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -export const GuidePageSideNav = props => { +export const GuidePageSideNav = (props) => { return (
{props.title}
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js index 26c68dfe87951..820e4728da86d 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js @@ -19,4 +19,4 @@ import React from 'react'; -export const GuideText = props =>
{props.children}
; +export const GuideText = (props) =>
{props.children}
; diff --git a/packages/kbn-ui-framework/doc_site/src/index.js b/packages/kbn-ui-framework/doc_site/src/index.js index 5473024ae93c9..f7f1df059a041 100644 --- a/packages/kbn-ui-framework/doc_site/src/index.js +++ b/packages/kbn-ui-framework/doc_site/src/index.js @@ -58,16 +58,16 @@ const routes = [ ]; // Update document title with route name. -const onRouteEnter = route => { +const onRouteEnter = (route) => { const leafRoute = route.routes[route.routes.length - 1]; document.title = leafRoute.name ? `Kibana UI Framework - ${leafRoute.name}` : 'Kibana UI Framework'; }; -const syncTitleWithRoutes = routesList => { +const syncTitleWithRoutes = (routesList) => { if (!routesList) return; - routesList.forEach(route => { + routesList.forEach((route) => { route.onEnter = onRouteEnter; // eslint-disable-line no-param-reassign if (route.indexRoute) { // Index routes have a weird relationship with their "parent" routes, diff --git a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js index 32912d5eb9c86..510a7fea7a026 100644 --- a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js +++ b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js @@ -159,14 +159,14 @@ export default { return allRoutes; }, getPreviousRoute: function getPreviousRoute(routeName) { - const index = allRoutes.findIndex(item => { + const index = allRoutes.findIndex((item) => { return item.name === routeName; }); return index >= 0 ? allRoutes[index - 1] : undefined; }, getNextRoute: function getNextRoute(routeName) { - const index = allRoutes.findIndex(item => { + const index = allRoutes.findIndex((item) => { return item.name === routeName; }); diff --git a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js index f016857ff4414..2e0678f569774 100644 --- a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js +++ b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js @@ -32,7 +32,7 @@ function one(str) { } function each(items, src, dest) { - return items.map(item => { + return items.map((item) => { const _item = item; _item[dest] = one(_item[src]); return _item; diff --git a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js index 6b61c009c5186..a86580903de68 100644 --- a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js +++ b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js @@ -40,7 +40,7 @@ export default function sectionsReducer(state = defaultState, action) { case ActionTypes.UNREGISTER_SECTION: { const sections = state.sections.slice(); - const index = sections.findIndex(section => section.id === action.id); + const index = sections.findIndex((section) => section.id === action.id); sections.splice(index, 1); return { diff --git a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js index a71b2ff28ee65..9f2f1dec56055 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js @@ -36,7 +36,7 @@ import BarThreeSections from './bar_three_sections'; import barThreeSectionsSource from '!!raw-loader!./bar_three_sections'; const barThreeSectionsHtml = renderToHtml(BarThreeSections); -export default props => ( +export default (props) => ( (
{ + onSubmit={(e) => { e.preventDefault(); window.alert('Submit'); }} @@ -40,7 +40,7 @@ export default () => (
{ + onSubmit={(e) => { e.preventDefault(); window.alert('Submit'); }} diff --git a/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js b/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js index daea2978aeffb..4943748ab1830 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js @@ -71,7 +71,7 @@ const elementsHtml = renderToHtml(Elements); import sizesHtml from './button_sizes.html'; -export default props => ( +export default (props) => ( { + onToggleContent = (ev) => { ev.preventDefault(); - this.setState(state => ({ + this.setState((state) => ({ isExpanded: !state.isExpanded, })); }; diff --git a/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js b/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js index d008a0d5f23f7..52e8a91b17aa9 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js @@ -32,7 +32,7 @@ import CollapseButtonAria from './collapse_button_aria'; import collapseButtonAriaSource from '!!raw-loader!./collapse_button_aria'; const collapseButtonAriaHtml = renderToHtml(CollapseButtonAria); -export default props => ( +export default (props) => ( ( +export default (props) => ( this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} isDisabled />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js index 0717459151584..88edfc5242564 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js @@ -59,7 +59,7 @@ import CheckBox from './check_box'; import checkBoxSource from '!!raw-loader!./check_box'; const checkBoxHtml = renderToHtml(CheckBox); -export default props => ( +export default (props) => ( - this.handleChange(event, 'value1')}> + this.handleChange(event, 'value1')} + > @@ -44,7 +47,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} isDisabled > @@ -52,7 +55,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} isInvalid > @@ -60,7 +63,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} size="small" > @@ -68,7 +71,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} size="large" > diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js index b56051071a6da..0d4e876d996a2 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js @@ -40,38 +40,38 @@ class KuiTextAreaExample extends Component { this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} />
this.handleChange(event, 'value6')} + onChange={(event) => this.handleChange(event, 'value6')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js index aba16bae1269b..65c7fa765a359 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js @@ -33,7 +33,7 @@ class KuiTextAreaNonResizableExample extends Component { return ( this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} isNonResizable /> ); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js index a3cebcb07bf2b..5bb3fabe22fa5 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js @@ -40,39 +40,39 @@ class KuiTextInputExample extends Component { this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} />
this.handleChange(event, 'value6')} + onChange={(event) => this.handleChange(event, 'value6')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js index 9c76a8b3a1d3a..7b1a5d2785cac 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js @@ -28,7 +28,7 @@ import FieldGroup from './field_group'; import fieldGroupSource from '!!raw-loader!./field_group'; const fieldGroupHtml = renderToHtml(FieldGroup); -export default props => ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( item.title.toLowerCase(), + getValue: (item) => item.title.toLowerCase(), isAscending: true, }, { name: 'description', - getValue: item => item.description.toLowerCase(), + getValue: (item) => item.description.toLowerCase(), isAscending: true, }, ], @@ -70,7 +70,7 @@ export class FluidTable extends Component { ); } - onSort = prop => { + onSort = (prop) => { this.sortableProperties.sortOn(prop); this.setState({ @@ -79,7 +79,7 @@ export class FluidTable extends Component { }; renderRows() { - return this.items.map(item => ( + return this.items.map((item) => ( {item.title} diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js index fece33c16980a..38eaa7b396ef5 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js @@ -137,7 +137,7 @@ export class ListingTable extends Component { ]; } - onItemSelectionChanged = selectedRowIds => { + onItemSelectionChanged = (selectedRowIds) => { this.setState({ selectedRowIds }); }; diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table.js b/packages/kbn-ui-framework/doc_site/src/views/table/table.js index 45f6e389e7234..0c55d1dc5ed51 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/table.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/table.js @@ -85,12 +85,12 @@ export class Table extends Component { [ { name: 'title', - getValue: item => item.title.toLowerCase(), + getValue: (item) => item.title.toLowerCase(), isAscending: true, }, { name: 'status', - getValue: item => item.status.toLowerCase(), + getValue: (item) => item.status.toLowerCase(), isAscending: true, }, ], @@ -98,7 +98,7 @@ export class Table extends Component { ); } - onSort = prop => { + onSort = (prop) => { this.sortableProperties.sortOn(prop); this.setState({ @@ -106,35 +106,35 @@ export class Table extends Component { }); }; - toggleItem = item => { - this.setState(previousState => { + toggleItem = (item) => { + this.setState((previousState) => { const rowToSelectedStateMap = new Map(previousState.rowToSelectedStateMap); rowToSelectedStateMap.set(item, !rowToSelectedStateMap.get(item)); return { rowToSelectedStateMap }; }); }; - isItemChecked = item => { + isItemChecked = (item) => { return this.state.rowToSelectedStateMap.get(item); }; - togglePopover = item => { - this.setState(previousState => { + togglePopover = (item) => { + this.setState((previousState) => { const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap); rowToOpenActionsPopoverMap.set(item, !rowToOpenActionsPopoverMap.get(item)); return { rowToOpenActionsPopoverMap }; }); }; - closePopover = item => { - this.setState(previousState => { + closePopover = (item) => { + this.setState((previousState) => { const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap); rowToOpenActionsPopoverMap.set(item, false); return { rowToOpenActionsPopoverMap }; }); }; - isPopoverOpen = item => { + isPopoverOpen = (item) => { return this.state.rowToOpenActionsPopoverMap.get(item); }; @@ -146,7 +146,7 @@ export class Table extends Component { renderRows() { const rows = []; - this.items.forEach(item => { + this.items.forEach((item) => { const classes = classNames({ 'kuiTableRowCell--wrap': item.isWrapped, }); diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js index 9ed449ea9767b..07e328c4e5e83 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js @@ -52,7 +52,7 @@ import { ListingTableLoadingItems } from './listing_table_loading_items'; import listingTableLoadingItemsSource from '!!raw-loader!./listing_table_loading_items'; // eslint-disable-line import/default const listingTableLoadingItemsHtml = renderToHtml(ListingTableLoadingItems); -export default props => ( +export default (props) => ( { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); diff --git a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js index 0d3663167520e..125fd0fb53ae3 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js @@ -35,7 +35,7 @@ import Tabs from './tabs'; import tabsSource from '!!raw-loader!./tabs'; const tabsHtml = renderToHtml(Tabs); -export default props => ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( diff --git a/packages/kbn-ui-framework/generator-kui/app/component.js b/packages/kbn-ui-framework/generator-kui/app/component.js index 1cf03b89d54f7..bcb561f6fa729 100644 --- a/packages/kbn-ui-framework/generator-kui/app/component.js +++ b/packages/kbn-ui-framework/generator-kui/app/component.js @@ -39,7 +39,7 @@ module.exports = class extends Generator { }, ], }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/app/documentation.js b/packages/kbn-ui-framework/generator-kui/app/documentation.js index c2735f1ce978b..3cbc0263789c6 100644 --- a/packages/kbn-ui-framework/generator-kui/app/documentation.js +++ b/packages/kbn-ui-framework/generator-kui/app/documentation.js @@ -43,7 +43,7 @@ module.exports = class extends Generator { }, ], }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/component/index.js b/packages/kbn-ui-framework/generator-kui/component/index.js index 3abf84b7a2073..56c49fe6fa471 100644 --- a/packages/kbn-ui-framework/generator-kui/component/index.js +++ b/packages/kbn-ui-framework/generator-kui/component/index.js @@ -49,7 +49,7 @@ module.exports = class extends Generator { type: 'confirm', default: true, }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; if (!answers.name || !answers.name.trim()) { @@ -62,7 +62,7 @@ module.exports = class extends Generator { writing() { const config = this.config; - const writeComponent = isStatelessFunction => { + const writeComponent = (isStatelessFunction) => { const componentName = utils.makeComponentName(config.name); const cssClassName = utils.lowerCaseFirstLetter(componentName); const fileName = config.name; diff --git a/packages/kbn-ui-framework/generator-kui/documentation/index.js b/packages/kbn-ui-framework/generator-kui/documentation/index.js index daaaf32c8fd22..03f8d5813b251 100644 --- a/packages/kbn-ui-framework/generator-kui/documentation/index.js +++ b/packages/kbn-ui-framework/generator-kui/documentation/index.js @@ -47,7 +47,7 @@ module.exports = class extends Generator { name: 'folderName', type: 'input', store: true, - default: answers => answers.name, + default: (answers) => answers.name, }); prompts.push({ @@ -58,7 +58,7 @@ module.exports = class extends Generator { }); } - return this.prompt(prompts).then(answers => { + return this.prompt(prompts).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/utils.js b/packages/kbn-ui-framework/generator-kui/utils.js index c51393121777e..0f7b910451767 100644 --- a/packages/kbn-ui-framework/generator-kui/utils.js +++ b/packages/kbn-ui-framework/generator-kui/utils.js @@ -21,7 +21,7 @@ function makeComponentName(str, usePrefix = true) { const words = str.split('_'); const componentName = words - .map(function(word) { + .map(function (word) { return upperCaseFirstLetter(word); }) .join(''); @@ -30,13 +30,13 @@ function makeComponentName(str, usePrefix = true) { } function lowerCaseFirstLetter(str) { - return str.replace(/\w\S*/g, function(txt) { + return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toLowerCase() + txt.substr(1); }); } function upperCaseFirstLetter(str) { - return str.replace(/\w\S*/g, function(txt) { + return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1); }); } diff --git a/packages/kbn-ui-framework/src/components/button/button.js b/packages/kbn-ui-framework/src/components/button/button.js index b18ca87a27b1e..e95b9209343ae 100644 --- a/packages/kbn-ui-framework/src/components/button/button.js +++ b/packages/kbn-ui-framework/src/components/button/button.js @@ -133,7 +133,7 @@ const KuiLinkButton = ({ children, ...rest }) => { - const onClick = e => { + const onClick = (e) => { if (disabled) { e.preventDefault(); } diff --git a/packages/kbn-ui-framework/src/components/button/button.test.js b/packages/kbn-ui-framework/src/components/button/button.test.js index d664ce85f9a37..db74308d9de8d 100644 --- a/packages/kbn-ui-framework/src/components/button/button.test.js +++ b/packages/kbn-ui-framework/src/components/button/button.test.js @@ -48,7 +48,7 @@ describe('KuiButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render(); diff --git a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js index 49eaff03efd40..630d5598cab9c 100644 --- a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js +++ b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js @@ -22,7 +22,7 @@ import React from 'react'; import classNames from 'classnames'; -const KuiButtonGroup = props => { +const KuiButtonGroup = (props) => { const classes = classNames('kuiButtonGroup', { 'kuiButtonGroup--united': props.isUnited, }); diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js index 736e349396b7e..256d7c4a1786e 100644 --- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js +++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js @@ -24,7 +24,7 @@ import classNames from 'classnames'; const ICON_TYPES = ['create', 'delete', 'previous', 'next', 'loading', 'settings', 'menu']; -const KuiButtonIcon = props => { +const KuiButtonIcon = (props) => { const typeToClassNameMap = { create: 'fa-plus', delete: 'fa-trash', diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js index e270f26644393..553fef1432487 100644 --- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js +++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js @@ -33,7 +33,7 @@ describe('KuiButtonIcon', () => { describe('Props', () => { describe('type', () => { - ICON_TYPES.forEach(type => { + ICON_TYPES.forEach((type) => { describe(`${type}`, () => { test(`renders the ${type} class`, () => { const $buttonIcon = render(); diff --git a/packages/kbn-ui-framework/src/components/button/link_button.test.js b/packages/kbn-ui-framework/src/components/button/link_button.test.js index 4f77af3febf54..4489dc1a46d2a 100644 --- a/packages/kbn-ui-framework/src/components/button/link_button.test.js +++ b/packages/kbn-ui-framework/src/components/button/link_button.test.js @@ -49,7 +49,7 @@ describe('KuiLinkButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render( diff --git a/packages/kbn-ui-framework/src/components/button/submit_button.test.js b/packages/kbn-ui-framework/src/components/button/submit_button.test.js index fc30523649c12..77ad9eb40c55f 100644 --- a/packages/kbn-ui-framework/src/components/button/submit_button.test.js +++ b/packages/kbn-ui-framework/src/components/button/submit_button.test.js @@ -47,7 +47,7 @@ describe('KuiSubmitButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render(); diff --git a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js index f6245ef654bb9..8ce225038b8b7 100644 --- a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js +++ b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js @@ -27,7 +27,7 @@ import { DIRECTIONS, KuiCollapseButton } from './collapse_button'; describe('KuiCollapseButton', () => { describe('Props', () => { describe('direction', () => { - DIRECTIONS.forEach(direction => { + DIRECTIONS.forEach((direction) => { describe(`${direction}`, () => { test(`renders the ${direction} class`, () => { const component = ; diff --git a/packages/kbn-ui-framework/src/components/form/select/select.test.js b/packages/kbn-ui-framework/src/components/form/select/select.test.js index 81c1e4d9a0ff2..056bc88016d51 100644 --- a/packages/kbn-ui-framework/src/components/form/select/select.test.js +++ b/packages/kbn-ui-framework/src/components/form/select/select.test.js @@ -77,7 +77,7 @@ describe('KuiSelect', () => { }); describe('size', () => { - SELECT_SIZE.forEach(size => { + SELECT_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js index eddb655094088..d87b7b76789de 100644 --- a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js +++ b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js @@ -87,7 +87,7 @@ describe('KuiTextArea', () => { }); describe('size', () => { - TEXTAREA_SIZE.forEach(size => { + TEXTAREA_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js index 9ef3c420bba68..41d3726582fb5 100644 --- a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js +++ b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js @@ -89,7 +89,7 @@ describe('KuiTextInput', () => { }); describe('size', () => { - TEXTINPUT_SIZE.forEach(size => { + TEXTINPUT_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js index 3478c159cbbb9..82b2afba7bc40 100644 --- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js +++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js @@ -57,7 +57,7 @@ export function KuiListingTable({ if (areAllRowsSelected()) { onItemSelectionChanged([]); } else { - onItemSelectionChanged(rows.map(row => row.id)); + onItemSelectionChanged(rows.map((row) => row.id)); } } diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js index b47a1275d1565..2607caeba0dbb 100644 --- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js +++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js @@ -22,7 +22,7 @@ import { mount, shallow } from 'enzyme'; import { requiredProps, takeMountedSnapshot } from '../../../test'; import { KuiListingTable } from './listing_table'; -const getProps = customProps => { +const getProps = (customProps) => { const defaultProps = { header: ['Breed', 'Description'], rows: [ @@ -59,20 +59,14 @@ test('renders KuiListingTable', () => { test('selecting a row calls onItemSelectionChanged', () => { const props = getProps(); const component = shallow(); - component - .find('KuiListingTableRow') - .at(1) - .prop('onSelectionChanged')('1'); + component.find('KuiListingTableRow').at(1).prop('onSelectionChanged')('1'); expect(props.onItemSelectionChanged).toHaveBeenCalledWith(['1']); }); test('selectedRowIds is preserved when onItemSelectionChanged is called', () => { const props = getProps({ selectedRowIds: ['3'] }); const component = shallow(); - component - .find('KuiListingTableRow') - .at(0) - .prop('onSelectionChanged')('1'); + component.find('KuiListingTableRow').at(0).prop('onSelectionChanged')('1'); expect(props.onItemSelectionChanged).toHaveBeenCalledWith(expect.arrayContaining(['1', '3'])); }); diff --git a/packages/kbn-ui-framework/src/components/typography/typography.test.js b/packages/kbn-ui-framework/src/components/typography/typography.test.js index 7155483354e48..b341a2c442fb2 100644 --- a/packages/kbn-ui-framework/src/components/typography/typography.test.js +++ b/packages/kbn-ui-framework/src/components/typography/typography.test.js @@ -35,7 +35,7 @@ describe('KuiTitle', () => { }); describe('renders size', () => { - SIZES.forEach(size => { + SIZES.forEach((size) => { test(size, () => { const component = render( diff --git a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js index 6537f0d157997..164910341f027 100644 --- a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js +++ b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js @@ -27,5 +27,5 @@ import uuid from 'uuid'; */ export function htmlIdGenerator(idPrefix) { const prefix = idPrefix || uuid.v1(); - return suffix => `${prefix}_${suffix || uuid.v1()}`; + return (suffix) => `${prefix}_${suffix || uuid.v1()}`; } diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js index 4b08b20b68cbf..6c445bf8b747b 100644 --- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js +++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js @@ -73,7 +73,7 @@ export class SortableProperties { * @returns {SortableProperty|undefined} */ getSortablePropertyByName(propertyName) { - return this.sortableProperties.find(property => property.name === propertyName); + return this.sortableProperties.find((property) => property.name === propertyName); } /** diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js index 223724edac8b8..0037787830ac2 100644 --- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js +++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js @@ -22,19 +22,19 @@ import { SortableProperties } from './sortable_properties'; describe('SortProperties', () => { const name = { name: 'name', - getValue: bird => bird.name, + getValue: (bird) => bird.name, isAscending: true, }; const size = { name: 'size', - getValue: bird => bird.size, + getValue: (bird) => bird.size, isAscending: false, }; const color = { name: 'color', - getValue: bird => bird.color, + getValue: (bird) => bird.color, isAscending: true, }; diff --git a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js index 4d87930d434b5..d4567ebb800fe 100644 --- a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js +++ b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js @@ -23,7 +23,7 @@ * containing both React components and HTML elements. This function removes the React components, * leaving only HTML elements in the snapshot. */ -export const takeMountedSnapshot = mountedComponent => { +export const takeMountedSnapshot = (mountedComponent) => { const html = mountedComponent.html(); const template = document.createElement('template'); template.innerHTML = html; // eslint-disable-line no-unsanitized/property diff --git a/packages/kbn-ui-shared-deps/public_path_loader.js b/packages/kbn-ui-shared-deps/public_path_loader.js index 6b7a27c9ca52b..fceebd6d6b3a1 100644 --- a/packages/kbn-ui-shared-deps/public_path_loader.js +++ b/packages/kbn-ui-shared-deps/public_path_loader.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(source) { +module.exports = function (source) { const options = this.query; return `__webpack_public_path__ = window.__kbnPublicPath__['${options.key}'];${source}`; }; diff --git a/packages/kbn-ui-shared-deps/scripts/build.js b/packages/kbn-ui-shared-deps/scripts/build.js index e45b3dbed1748..af4e3481e624d 100644 --- a/packages/kbn-ui-shared-deps/scripts/build.js +++ b/packages/kbn-ui-shared-deps/scripts/build.js @@ -38,7 +38,7 @@ run( ); /** @param {webpack.Stats} stats */ - const onCompilationComplete = stats => { + const onCompilationComplete = (stats) => { const took = Math.round((stats.endTime - stats.startTime) / 1000); if (!stats.hasErrors() && !stats.hasWarnings()) { @@ -55,7 +55,7 @@ run( }; if (flags.watch) { - compiler.hooks.done.tap('report on stats', stats => { + compiler.hooks.done.tap('report on stats', (stats) => { try { onCompilationComplete(stats); } catch (error) { @@ -72,7 +72,7 @@ run( log.info('Running webpack compilation...'); }); - compiler.watch({}, error => { + compiler.watch({}, (error) => { if (error) { log.error('Fatal webpack error'); log.error(error); diff --git a/packages/kbn-ui-shared-deps/webpack.config.js b/packages/kbn-ui-shared-deps/webpack.config.js index 02987b8a19201..7295f2e88c530 100644 --- a/packages/kbn-ui-shared-deps/webpack.config.js +++ b/packages/kbn-ui-shared-deps/webpack.config.js @@ -55,7 +55,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ path: UiSharedDeps.distDir, filename: '[name].js', sourceMapFilename: '[file].map', - devtoolModuleFilenameTemplate: info => + devtoolModuleFilenameTemplate: (info) => `kbn-ui-shared-deps/${Path.relative(REPO_ROOT, info.absoluteResourcePath)}`, library: '__kbnSharedDeps__', }, @@ -104,7 +104,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ cacheGroups: { 'kbn-ui-shared-deps.@elastic': { name: 'kbn-ui-shared-deps.@elastic', - test: m => m.resource && m.resource.includes('@elastic'), + test: (m) => m.resource && m.resource.includes('@elastic'), chunks: 'all', enforce: true, }, diff --git a/packages/kbn-utility-types/index.ts b/packages/kbn-utility-types/index.ts index 657d9f547de66..9a8a81460f410 100644 --- a/packages/kbn-utility-types/index.ts +++ b/packages/kbn-utility-types/index.ts @@ -82,9 +82,9 @@ export type Values = T extends any[] ? T[number] : T extends object ? T[keyof * type. This is necessary in the case of distinguishing one collection from * another. */ -export type UnionToIntersection = (U extends any -? (k: U) => void -: never) extends (k: infer I) => void +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( + k: infer I +) => void ? I : never; diff --git a/scripts/es.js b/scripts/es.js index 4f15cc11801e3..93f1d69350bac 100644 --- a/scripts/es.js +++ b/scripts/es.js @@ -32,7 +32,7 @@ kbnEs 'base-path': resolve(__dirname, '../.es'), ssl: false, }) - .catch(function(e) { + .catch(function (e) { console.error(e); process.exitCode = 1; }); diff --git a/scripts/test_hardening.js b/scripts/test_hardening.js index c0a20a9ff6cb4..0bc0d1c045ac0 100644 --- a/scripts/test_hardening.js +++ b/scripts/test_hardening.js @@ -28,10 +28,10 @@ program .description( 'Run the tests in test/harden directory. If no files are provided, all files within the directory will be run.' ) - .action(function(globs) { + .action(function (globs) { if (globs.length === 0) globs.push(path.join('test', 'harden', '*')); - globs.forEach(function(glob) { - syncGlob(glob).forEach(function(filename) { + globs.forEach(function (glob) { + syncGlob(glob).forEach(function (filename) { if (path.basename(filename)[0] === '_') return; console.log(process.argv[0], filename); execFileSync(process.argv[0], [filename], { stdio: 'inherit' }); diff --git a/src/apm.js b/src/apm.js index e3f4d84d9b523..6c10539c6b7d3 100644 --- a/src/apm.js +++ b/src/apm.js @@ -85,7 +85,7 @@ function getConfig(serviceName) { */ const isKibanaDistributable = Boolean(build && build.distributable === true); -module.exports = function(serviceName = name) { +module.exports = function (serviceName = name) { if (process.env.kbnWorkerType === 'optmzr') return; const conf = getConfig(serviceName); diff --git a/src/cli/cli.js b/src/cli/cli.js index b6598520352a6..50a8d4c7f7f01 100644 --- a/src/cli/cli.js +++ b/src/cli/cli.js @@ -40,13 +40,13 @@ serveCommand(program); program .command('help ') .description('Get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli/cluster/cluster_manager.test.ts b/src/cli/cluster/cluster_manager.test.ts index 707778861fb59..66f68f815edac 100644 --- a/src/cli/cluster/cluster_manager.test.ts +++ b/src/cli/cluster/cluster_manager.test.ts @@ -153,7 +153,7 @@ describe('CLI cluster manager', () => { const events: Array = []; delayUntil().subscribe( () => events.push('next'), - error => events.push(error), + (error) => events.push(error), () => events.push('complete') ); diff --git a/src/cli/cluster/cluster_manager.ts b/src/cli/cluster/cluster_manager.ts index 3b3e4d78320d2..fc94f8d585a02 100644 --- a/src/cli/cluster/cluster_manager.ts +++ b/src/cli/cluster/cluster_manager.ts @@ -37,7 +37,7 @@ process.env.kbnWorkerType = 'managr'; const firstAllTrue = (...sources: Array>) => Rx.combineLatest(...sources).pipe( - filter(values => values.every(v => v === true)), + filter((values) => values.every((v) => v === true)), take(1), mapTo(undefined) ); @@ -75,7 +75,7 @@ export class ClusterManager { .pipe( map(({ state }) => state.phase === 'success' || state.phase === 'issue'), tap({ - error: error => { + error: (error) => { this.log.bad('New platform optimizer error', error.stack); process.exit(1); }, @@ -139,9 +139,9 @@ export class ClusterManager { .subscribe(this.optimizerReady$); // broker messages between workers - this.workers.forEach(worker => { - worker.on('broadcast', msg => { - this.workers.forEach(to => { + this.workers.forEach((worker) => { + worker.on('broadcast', (msg) => { + this.workers.forEach((to) => { if (to !== worker && to.online) { to.fork!.send(msg); } @@ -156,7 +156,7 @@ export class ClusterManager { this.server.on('reloadLoggingConfigFromServerWorker', () => { process.emit('message' as any, { reloadLoggingConfig: true } as any); - this.workers.forEach(worker => { + this.workers.forEach((worker) => { worker.fork!.send({ reloadLoggingConfig: true }); }); }); @@ -182,7 +182,7 @@ export class ClusterManager { const extraPaths = [...pluginPaths, ...scanDirs]; const pluginInternalDirsIgnore = scanDirs - .map(scanDir => resolve(scanDir, '*')) + .map((scanDir) => resolve(scanDir, '*')) .concat(pluginPaths) .reduce( (acc, path) => @@ -212,10 +212,7 @@ export class ClusterManager { shouldRedirectFromOldBasePath: (path: string) => { // strip `s/{id}` prefix when checking for need to redirect if (path.startsWith('s/')) { - path = path - .split('/') - .slice(2) - .join('/'); + path = path.split('/').slice(2).join('/'); } const isApp = path.startsWith('app/'); @@ -253,7 +250,7 @@ export class ClusterManager { fromRoot('x-pack/legacy/server'), fromRoot('config'), ...extraPaths, - ].map(path => resolve(path)) + ].map((path) => resolve(path)) ) ); diff --git a/src/cli/cluster/worker.ts b/src/cli/cluster/worker.ts index c73d3edbf7df7..dc6e6d5676651 100644 --- a/src/cli/cluster/worker.ts +++ b/src/cli/cluster/worker.ts @@ -136,7 +136,7 @@ export class Worker extends EventEmitter { this.processBinder.destroy(); // wait until the cluster reports this fork has exited, then resolve - await new Promise(resolve => this.once('fork:exit', resolve)); + await new Promise((resolve) => this.once('fork:exit', resolve)); } } @@ -179,7 +179,7 @@ export class Worker extends EventEmitter { flushChangeBuffer() { const files = _.unique(this.changes.splice(0)); const prefix = files.length > 1 ? '\n - ' : ''; - return files.reduce(function(list, file) { + return files.reduce(function (list, file) { return `${list || ''}${prefix}"${file}"`; }, ''); } @@ -188,7 +188,7 @@ export class Worker extends EventEmitter { if (this.fork) { // once "exit" event is received with 0 status, start() is called again this.shutdown(); - await new Promise(cb => this.once('online', cb)); + await new Promise((cb) => this.once('online', cb)); return; } @@ -214,6 +214,6 @@ export class Worker extends EventEmitter { this.processBinder.on('exit', () => this.shutdown()); // wait for the fork to report it is online before resolving - await new Promise(cb => this.once('fork:online', cb)); + await new Promise((cb) => this.once('fork:online', cb)); } } diff --git a/src/cli/command.js b/src/cli/command.js index 6f083bb2a1fa2..f4781fcab1e20 100644 --- a/src/cli/command.js +++ b/src/cli/command.js @@ -23,7 +23,7 @@ import Chalk from 'chalk'; import help from './help'; import { Command } from 'commander'; -Command.prototype.error = function(err) { +Command.prototype.error = function (err) { if (err && err.message) err = err.message; console.log( @@ -37,7 +37,7 @@ ${help(this, ' ')} process.exit(64); // eslint-disable-line no-process-exit }; -Command.prototype.defaultHelp = function() { +Command.prototype.defaultHelp = function () { console.log( ` ${help(this, ' ')} @@ -48,7 +48,7 @@ ${help(this, ' ')} process.exit(64); // eslint-disable-line no-process-exit }; -Command.prototype.unknownArgv = function(argv) { +Command.prototype.unknownArgv = function (argv) { if (argv) this.__unknownArgv = argv; return this.__unknownArgv ? this.__unknownArgv.slice(0) : []; }; @@ -57,11 +57,11 @@ Command.prototype.unknownArgv = function(argv) { * setup the command to accept arbitrary configuration via the cli * @return {[type]} [description] */ -Command.prototype.collectUnknownOptions = function() { +Command.prototype.collectUnknownOptions = function () { const title = `Extra ${this._name} options`; this.allowUnknownOption(); - this.getUnknownOptions = function() { + this.getUnknownOptions = function () { const opts = {}; const unknowns = this.unknownArgv(); @@ -95,17 +95,17 @@ Command.prototype.collectUnknownOptions = function() { return this; }; -Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function(parse, argv) { +Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function (parse, 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) { +Command.prototype.action = _.wrap(Command.prototype.action, function (action, fn) { + return action.call(this, function (...args) { const ret = fn.apply(this, args); if (ret && typeof ret.then === 'function') { - ret.then(null, function(e) { + ret.then(null, function (e) { console.log('FATAL CLI ERROR', e.stack); process.exit(1); }); diff --git a/src/cli/help.js b/src/cli/help.js index a2dc638d2b6ee..656944d85b254 100644 --- a/src/cli/help.js +++ b/src/cli/help.js @@ -24,7 +24,7 @@ export default function help(command, spaces) { return command.outputHelp(); } - const defCmd = _.find(command.commands, function(cmd) { + const defCmd = _.find(command.commands, function (cmd) { return cmd._name === 'serve'; }); @@ -53,12 +53,12 @@ function indent(str, n) { function commandsSummary(program) { const cmds = _.compact( - program.commands.map(function(cmd) { + program.commands.map(function (cmd) { const name = cmd._name; if (name === '*') return; const opts = cmd.options.length ? ' [options]' : ''; const args = cmd._args - .map(function(arg) { + .map(function (arg) { return humanReadableArgName(arg); }) .join(' '); @@ -67,11 +67,11 @@ function commandsSummary(program) { }) ); - const cmdLColWidth = cmds.reduce(function(width, cmd) { + const cmdLColWidth = cmds.reduce(function (width, cmd) { return Math.max(width, cmd[0].length); }, 0); - return cmds.reduce(function(help, cmd) { + return cmds.reduce(function (help, cmd) { return `${help || ''}${_.padRight(cmd[0], cmdLColWidth)} ${cmd[1] || ''}\n`; }, ''); } diff --git a/src/cli/repl/index.js b/src/cli/repl/index.js index 37a51b4d1ec9e..0b27fafcef84e 100644 --- a/src/cli/repl/index.js +++ b/src/cli/repl/index.js @@ -72,7 +72,7 @@ function prettyPrint(text, o, depth) { // This lets us handle promises more gracefully than the default REPL, // which doesn't show the results. function promiseFriendlyWriter({ displayPrompt, getPrintDepth }) { - return result => promisePrint(result, displayPrompt, getPrintDepth); + return (result) => promisePrint(result, displayPrompt, getPrintDepth); } function promisePrint(result, displayPrompt, getPrintDepth) { @@ -83,8 +83,8 @@ function promisePrint(result, displayPrompt, getPrintDepth) { Promise.resolve() .then(() => console.log('Waiting for promise...')) .then(() => result) - .then(o => prettyPrint('Promise Resolved: \n', o, depth)) - .catch(err => prettyPrint('Promise Rejected: \n', err, depth)) + .then((o) => prettyPrint('Promise Resolved: \n', o, depth)) + .catch((err) => prettyPrint('Promise Rejected: \n', err, depth)) .then(displayPrompt); return ''; } diff --git a/src/cli/repl/repl.test.js b/src/cli/repl/repl.test.js index 9abb43c338290..3a032d415e5f2 100644 --- a/src/cli/repl/repl.test.js +++ b/src/cli/repl/repl.test.js @@ -17,7 +17,7 @@ * under the License. */ -jest.mock('repl', () => ({ start: opts => ({ opts, context: {} }) }), { virtual: true }); +jest.mock('repl', () => ({ start: (opts) => ({ opts, context: {} }) }), { virtual: true }); describe('repl', () => { const originalConsoleLog = console.log; @@ -25,7 +25,7 @@ describe('repl', () => { beforeEach(() => { global.console.log = jest.fn(); - require('repl').start = opts => { + require('repl').start = (opts) => { let resetHandler; const replServer = { opts, @@ -188,7 +188,7 @@ describe('repl', () => { async function waitForPrompt(replServer, fn) { let resolveDone; - const done = new Promise(resolve => (resolveDone = resolve)); + const done = new Promise((resolve) => (resolveDone = resolve)); replServer.displayPrompt = () => { resolveDone(); }; diff --git a/src/cli/serve/integration_tests/invalid_config.test.ts b/src/cli/serve/integration_tests/invalid_config.test.ts index da6684fae8cef..fd6fa1bf192fc 100644 --- a/src/cli/serve/integration_tests/invalid_config.test.ts +++ b/src/cli/serve/integration_tests/invalid_config.test.ts @@ -29,10 +29,10 @@ interface LogEntry { type: string; } -describe('cli invalid config support', function() { +describe('cli invalid config support', function () { it( 'exits with statusCode 64 and logs a single line when config is invalid', - function() { + function () { // Unused keys only throw once LegacyService starts, so disable migrations so that Core // will finish the start lifecycle without a running Elasticsearch instance. const { error, status, stdout } = spawnSync( @@ -47,9 +47,9 @@ describe('cli invalid config support', function() { .toString('utf8') .split('\n') .filter(Boolean) - .map(line => JSON.parse(line) as LogEntry) - .filter(line => line.tags.includes('fatal')) - .map(obj => ({ + .map((line) => JSON.parse(line) as LogEntry) + .filter((line) => line.tags.includes('fatal')) + .map((obj) => ({ ...obj, pid: '## PID ##', '@timestamp': '## @timestamp ##', diff --git a/src/cli/serve/integration_tests/reload_logging_config.test.ts b/src/cli/serve/integration_tests/reload_logging_config.test.ts index 9ad8438c312a1..35391b9b58ecc 100644 --- a/src/cli/serve/integration_tests/reload_logging_config.test.ts +++ b/src/cli/serve/integration_tests/reload_logging_config.test.ts @@ -70,7 +70,7 @@ function watchFileUntil(path: string, matcher: RegExp, timeout: number) { } function containsJsonOnly(content: string[]) { - return content.every(line => line.startsWith('{')); + return content.every((line) => line.startsWith('{')); } function createConfigManager(configPath: string) { @@ -83,7 +83,7 @@ function createConfigManager(configPath: string) { }; } -describe('Server logging configuration', function() { +describe('Server logging configuration', function () { let child: undefined | Child.ChildProcess; beforeEach(() => { @@ -92,7 +92,7 @@ describe('Server logging configuration', function() { afterEach(async () => { if (child !== undefined) { - const exitPromise = new Promise(resolve => child?.once('exit', resolve)); + const exitPromise = new Promise((resolve) => child?.once('exit', resolve)); child.kill('SIGKILL'); await exitPromise; } @@ -110,7 +110,7 @@ describe('Server logging configuration', function() { describe('legacy logging', () => { it( 'should be reloadable via SIGHUP process signaling', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(legacyConfig, configFilePath); @@ -123,17 +123,13 @@ describe('Server logging configuration', function() { ]); const message$ = Rx.fromEvent(child.stdout, 'data').pipe( - map(messages => - String(messages) - .split('\n') - .filter(Boolean) - ) + map((messages) => String(messages).split('\n').filter(Boolean)) ); await message$ .pipe( // We know the sighup handler will be registered before this message logged - filter(messages => messages.some(m => m.includes('setting up root'))), + filter((messages) => messages.some((m) => m.includes('setting up root'))), take(1) ) .toPromise(); @@ -141,7 +137,7 @@ describe('Server logging configuration', function() { const lastMessage = await message$.pipe(take(1)).toPromise(); expect(containsJsonOnly(lastMessage)).toBe(true); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.json = false; return oldConfig; }); @@ -150,7 +146,7 @@ describe('Server logging configuration', function() { await message$ .pipe( - filter(messages => !containsJsonOnly(messages)), + filter((messages) => !containsJsonOnly(messages)), take(1) ) .toPromise(); @@ -160,7 +156,7 @@ describe('Server logging configuration', function() { it( 'should recreate file handle on SIGHUP', - async function() { + async function () { const logPath = Path.resolve(tempDir, 'kibana.log'); const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log'); @@ -188,24 +184,20 @@ describe('Server logging configuration', function() { describe('platform logging', () => { it( 'should be reloadable via SIGHUP process signaling', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(configFileLogConsole, configFilePath); child = Child.spawn(process.execPath, [kibanaPath, '--oss', '--config', configFilePath]); const message$ = Rx.fromEvent(child.stdout, 'data').pipe( - map(messages => - String(messages) - .split('\n') - .filter(Boolean) - ) + map((messages) => String(messages).split('\n').filter(Boolean)) ); await message$ .pipe( // We know the sighup handler will be registered before this message logged - filter(messages => messages.some(m => m.includes('setting up root'))), + filter((messages) => messages.some((m) => m.includes('setting up root'))), take(1) ) .toPromise(); @@ -213,7 +205,7 @@ describe('Server logging configuration', function() { const lastMessage = await message$.pipe(take(1)).toPromise(); expect(containsJsonOnly(lastMessage)).toBe(true); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.appenders.console.layout.kind = 'pattern'; return oldConfig; }); @@ -221,7 +213,7 @@ describe('Server logging configuration', function() { await message$ .pipe( - filter(messages => !containsJsonOnly(messages)), + filter((messages) => !containsJsonOnly(messages)), take(1) ) .toPromise(); @@ -230,14 +222,14 @@ describe('Server logging configuration', function() { ); it( 'should recreate file handle on SIGHUP', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(configFileLogFile, configFilePath); const logPath = Path.resolve(tempDir, 'kibana.log'); const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log'); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.appenders.file.path = logPath; return oldConfig; }); diff --git a/src/cli/serve/read_keystore.js b/src/cli/serve/read_keystore.js index c17091a11f5c1..cfe02735630f2 100644 --- a/src/cli/serve/read_keystore.js +++ b/src/cli/serve/read_keystore.js @@ -30,7 +30,7 @@ export function readKeystore(dataPath = getDataPath()) { const keys = Object.keys(keystore.data); const data = {}; - keys.forEach(key => { + keys.forEach((key) => { set(data, key, keystore.data[key]); }); diff --git a/src/cli/serve/serve.js b/src/cli/serve/serve.js index ff6c51e215c3c..8bc65f3da7111 100644 --- a/src/cli/serve/serve.js +++ b/src/cli/serve/serve.js @@ -52,9 +52,9 @@ const CAN_REPL = canRequire(REPL_PATH); const XPACK_DIR = resolve(__dirname, '../../../x-pack'); const XPACK_INSTALLED = canRequire(XPACK_DIR); -const pathCollector = function() { +const pathCollector = function () { const paths = []; - return function(path) { + return function (path) { paths.push(resolve(process.cwd(), path)); return paths; }; @@ -109,7 +109,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) { (customElasticsearchHosts.length > 0 && customElasticsearchHosts) || [ 'https://localhost:9200', ] - ).map(hostUrl => { + ).map((hostUrl) => { const parsedUrl = url.parse(hostUrl); if (parsedUrl.hostname !== 'localhost') { throw new Error( @@ -159,7 +159,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) { return rawConfig; } -export default function(program) { +export default function (program) { const command = program.command('serve'); command @@ -223,7 +223,7 @@ export default function(program) { .option('--no-dev-config', 'Prevents loading the kibana.dev.yml file in --dev mode'); } - command.action(async function(opts) { + command.action(async function (opts) { if (opts.dev && opts.devConfig !== false) { try { const kbnDevConfig = fromRoot('config/kibana.dev.yml'); @@ -262,7 +262,7 @@ export default function(program) { isClusterModeSupported: CAN_CLUSTER, isReplModeSupported: CAN_REPL, }, - applyConfigOverrides: rawConfig => applyConfigOverrides(rawConfig, opts, unknownOptions), + applyConfigOverrides: (rawConfig) => applyConfigOverrides(rawConfig, opts, unknownOptions), }); }); } diff --git a/src/cli_keystore/add.test.js b/src/cli_keystore/add.test.js index 72f15a5439ef0..320581b470c2b 100644 --- a/src/cli_keystore/add.test.js +++ b/src/cli_keystore/add.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('nonexistent')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('nonexistent'); }), writeFileSync: jest.fn(), diff --git a/src/cli_keystore/cli_keystore.js b/src/cli_keystore/cli_keystore.js index 7c90d88f7b0cd..e1561b343ef39 100644 --- a/src/cli_keystore/cli_keystore.js +++ b/src/cli_keystore/cli_keystore.js @@ -50,13 +50,13 @@ removeCli(program, keystore); program .command('help ') .description('get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli_keystore/create.test.js b/src/cli_keystore/create.test.js index 01355f51a0c55..33b5aa4bd07d8 100644 --- a/src/cli_keystore/create.test.js +++ b/src/cli_keystore/create.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('foo')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('foo'); }), writeFileSync: jest.fn(), diff --git a/src/cli_keystore/list.test.js b/src/cli_keystore/list.test.js index 3fb5014820865..857991b5ae3b9 100644 --- a/src/cli_keystore/list.test.js +++ b/src/cli_keystore/list.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('nonexistent')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('nonexistent'); }), })); diff --git a/src/cli_plugin/cli.js b/src/cli_plugin/cli.js index d1cdf983c0da4..da1068b54b4b5 100644 --- a/src/cli_plugin/cli.js +++ b/src/cli_plugin/cli.js @@ -43,13 +43,13 @@ removeCommand(program); program .command('help ') .description('get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli_plugin/install/cleanup.js b/src/cli_plugin/install/cleanup.js index eaa25962ef0e4..f31e028226c27 100644 --- a/src/cli_plugin/install/cleanup.js +++ b/src/cli_plugin/install/cleanup.js @@ -21,7 +21,7 @@ import del from 'del'; import fs from 'fs'; export function cleanPrevious(settings, logger) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { fs.statSync(settings.workingPath); diff --git a/src/cli_plugin/install/cleanup.test.js b/src/cli_plugin/install/cleanup.test.js index c6602636cb481..46089f61d5e83 100644 --- a/src/cli_plugin/install/cleanup.test.js +++ b/src/cli_plugin/install/cleanup.test.js @@ -24,32 +24,32 @@ import del from 'del'; import { cleanPrevious, cleanArtifacts } from './cleanup'; import Logger from '../lib/logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('pluginCleaner', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('pluginCleaner', function () { const settings = { workingPath: 'dummy', }; - describe('cleanPrevious', function() { + describe('cleanPrevious', function () { let errorStub; let logger; - beforeEach(function() { + beforeEach(function () { errorStub = sinon.stub(); logger = new Logger(settings); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); fs.statSync.restore(); del.sync.restore(); }); - it('should resolve if the working path does not exist', function() { + it('should resolve if the working path does not exist', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync').callsFake(() => { const error = new Error('ENOENT'); @@ -59,75 +59,75 @@ describe('kibana cli', function() { return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(false); }); }); - it('should rethrow any exception except ENOENT from fs.statSync', function() { + it('should rethrow any exception except ENOENT from fs.statSync', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync').throws(new Error('An Unhandled Error')); errorStub = sinon.stub(); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(true); }); }); - it('should log a message if there was a working directory', function() { + it('should log a message if there was a working directory', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync'); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(logger.log.calledWith('Found previous install attempt. Deleting...')).toBe( true ); }); }); - it('should rethrow any exception from del.sync', function() { + it('should rethrow any exception from del.sync', function () { sinon.stub(fs, 'statSync'); sinon.stub(del, 'sync').throws(new Error('I am an error thrown by del')); errorStub = sinon.stub(); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(true); }); }); - it('should resolve if the working path is deleted', function() { + it('should resolve if the working path is deleted', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync'); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(false); }); }); }); - describe('cleanArtifacts', function() { - beforeEach(function() {}); + describe('cleanArtifacts', function () { + beforeEach(function () {}); - afterEach(function() { + afterEach(function () { del.sync.restore(); }); - it('should attempt to delete the working directory', function() { + it('should attempt to delete the working directory', function () { sinon.stub(del, 'sync'); cleanArtifacts(settings); expect(del.sync.calledWith(settings.workingPath)).toBe(true); }); - it('should swallow any errors thrown by del.sync', function() { + it('should swallow any errors thrown by del.sync', function () { sinon.stub(del, 'sync').throws(new Error('Something bad happened.')); expect(() => cleanArtifacts(settings)).not.toThrow(); diff --git a/src/cli_plugin/install/download.js b/src/cli_plugin/install/download.js index fc1fe8323520b..10d20367c1b7b 100644 --- a/src/cli_plugin/install/download.js +++ b/src/cli_plugin/install/download.js @@ -80,7 +80,7 @@ export function download(settings, logger) { logger.log(`Attempting to transfer from ${sourceUrl}`); - return _downloadSingle(settings, logger, sourceUrl).catch(err => { + return _downloadSingle(settings, logger, sourceUrl).catch((err) => { const isUnsupportedProtocol = err instanceof UnsupportedProtocolError; const isDownloadResourceNotFound = err.message === 'ENOTFOUND'; if (isUnsupportedProtocol || isDownloadResourceNotFound) { diff --git a/src/cli_plugin/install/download.test.js b/src/cli_plugin/install/download.test.js index ef924f28a65e7..93e5e414fed74 100644 --- a/src/cli_plugin/install/download.test.js +++ b/src/cli_plugin/install/download.test.js @@ -28,8 +28,8 @@ import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } fr import { join } from 'path'; import http from 'http'; -describe('kibana cli', function() { - describe('plugin downloader', function() { +describe('kibana cli', function () { + describe('plugin downloader', function () { const testWorkingPath = join(__dirname, '.test.data.download'); const tempArchiveFilePath = join(testWorkingPath, 'archive.part'); @@ -57,46 +57,44 @@ describe('kibana cli', function() { throw new Error('expected the promise to reject'); } - beforeEach(function() { + beforeEach(function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); del.sync(testWorkingPath); Fs.mkdirSync(testWorkingPath, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(testWorkingPath); }); - describe('_downloadSingle', function() { - beforeEach(function() {}); + describe('_downloadSingle', function () { + beforeEach(function () {}); - describe('http downloader', function() { - it('should throw an ENOTFOUND error for a http ulr that returns 404', function() { - nock('http://example.com') - .get('/plugin.tar.gz') - .reply(404); + describe('http downloader', function () { + it('should throw an ENOTFOUND error for a http ulr that returns 404', function () { + nock('http://example.com').get('/plugin.tar.gz').reply(404); const sourceUrl = 'http://example.com/plugin.tar.gz'; - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err.message).toMatch(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); - it('should throw an UnsupportedProtocolError for an invalid url', function() { + it('should throw an UnsupportedProtocolError for an invalid url', function () { const sourceUrl = 'i am an invalid url'; - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err).toBeInstanceOf(UnsupportedProtocolError); expectWorkingPathEmpty(); }); }); - it('should download a file from a valid http url', function() { + it('should download a file from a valid http url', function () { const filePath = join(__dirname, '__fixtures__/replies/banana.jpg'); nock('http://example.com') @@ -109,40 +107,40 @@ describe('kibana cli', function() { const sourceUrl = 'http://example.com/plugin.zip'; - return _downloadSingle(settings, logger, sourceUrl).then(function() { + return _downloadSingle(settings, logger, sourceUrl).then(function () { expectWorkingPathNotEmpty(); }); }); }); - describe('local file downloader', function() { - it('should throw an ENOTFOUND error for an invalid local file', function() { + describe('local file downloader', function () { + it('should throw an ENOTFOUND error for an invalid local file', function () { const filePath = join(__dirname, '__fixtures__/replies/i-am-not-there.zip'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err.message).toMatch(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); - it('should copy a valid local file', function() { + it('should copy a valid local file', function () { const filePath = join(__dirname, '__fixtures__/replies/banana.jpg'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); - return _downloadSingle(settings, logger, sourceUrl).then(function() { + return _downloadSingle(settings, logger, sourceUrl).then(function () { expectWorkingPathNotEmpty(); }); }); }); }); - describe('_getFilePath', function() { - it('should decode paths', function() { + describe('_getFilePath', function () { + it('should decode paths', function () { expect(_getFilePath('Test%20folder/file.zip')).toBe('Test folder/file.zip'); }); - it('should remove the leading slash from windows paths', function() { + it('should remove the leading slash from windows paths', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); @@ -152,8 +150,8 @@ describe('kibana cli', function() { }); }); - describe('Windows file:// deprecation', function() { - it('should log a warning if a file:// path is used', function() { + describe('Windows file:// deprecation', function () { + it('should log a warning if a file:// path is used', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); const logger = { @@ -169,8 +167,8 @@ describe('kibana cli', function() { }); }); - describe('download', function() { - it('should loop through bad urls until it finds a good one.', function() { + describe('download', function () { + it('should loop through bad urls until it finds a good one.', function () { const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', @@ -190,7 +188,7 @@ describe('kibana cli', function() { .get('/goodfile.tar.gz') .replyWithFile(200, filePath); - return download(settings, logger).then(function() { + return download(settings, logger).then(function () { expect(logger.log.getCall(0).args[0]).toMatch(/badfile1.tar.gz/); expect(logger.log.getCall(1).args[0]).toMatch(/badfile2.tar.gz/); expect(logger.log.getCall(2).args[0]).toMatch(/I am a bad uri/); @@ -199,7 +197,7 @@ describe('kibana cli', function() { }); }); - it('should stop looping through urls when it finds a good one.', function() { + it('should stop looping through urls when it finds a good one.', function () { const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', @@ -221,7 +219,7 @@ describe('kibana cli', function() { .get('/badfile3.tar.gz') .reply(404); - return download(settings, logger).then(function() { + return download(settings, logger).then(function () { for (let i = 0; i < logger.log.callCount; i++) { expect(logger.log.getCall(i).args[0]).not.toMatch(/badfile3.tar.gz/); } @@ -229,7 +227,7 @@ describe('kibana cli', function() { }); }); - it("should throw an error when it doesn't find a good url.", function() { + it("should throw an error when it doesn't find a good url.", function () { settings.urls = [ 'http://example.com/badfile1.tar.gz', 'http://example.com/badfile2.tar.gz', @@ -247,25 +245,25 @@ describe('kibana cli', function() { .get('/badfile3.tar.gz') .reply(404); - return download(settings, logger).then(shouldReject, function(err) { + return download(settings, logger).then(shouldReject, function (err) { expect(err.message).toMatch(/no valid url specified/i); expectWorkingPathEmpty(); }); }); - afterAll(function() { + afterAll(function () { nock.cleanAll(); }); }); - describe('proxy support', function() { + describe('proxy support', function () { const proxyPort = 2626; const proxyUrl = `http://localhost:${proxyPort}`; let proxyHit = false; let proxyConnectHit = false; - const proxy = http.createServer(function(req, res) { + const proxy = http.createServer(function (req, res) { proxyHit = true; // Our test proxy simply returns an empty 200 response, since we only // care about the download promise being resolved. @@ -301,29 +299,29 @@ describe('kibana cli', function() { .replyWithFile(200, join(__dirname, '__fixtures__/replies/test_plugin.zip')); } - beforeAll(function(done) { + beforeAll(function (done) { proxy.listen(proxyPort, done); }); - beforeEach(function() { + beforeEach(function () { proxyHit = false; proxyConnectHit = false; }); - afterEach(function() { + afterEach(function () { delete process.env.http_proxy; delete process.env.https_proxy; delete process.env.no_proxy; }); - it('should use http_proxy env variable', function() { + it('should use http_proxy env variable', function () { process.env.http_proxy = proxyUrl; settings.urls = ['http://example.com/plugin.zip']; return download(settings, logger).then(expectProxyHit); }); - it('should use https_proxy for secure URLs', function() { + it('should use https_proxy for secure URLs', function () { process.env.https_proxy = proxyUrl; settings.urls = ['https://example.com/plugin.zip']; @@ -340,7 +338,7 @@ describe('kibana cli', function() { ); }); - it('should not use http_proxy for HTTPS urls', function() { + it('should not use http_proxy for HTTPS urls', function () { process.env.http_proxy = proxyUrl; settings.urls = ['https://example.com/plugin.zip']; @@ -349,7 +347,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should not use https_proxy for HTTP urls', function() { + it('should not use https_proxy for HTTP urls', function () { process.env.https_proxy = proxyUrl; settings.urls = ['http://example.com/plugin.zip']; @@ -358,7 +356,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support domains in no_proxy', function() { + it('should support domains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar, example.com'; settings.urls = ['http://example.com/plugin.zip']; @@ -368,7 +366,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support subdomains in no_proxy', function() { + it('should support subdomains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar,plugins.example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -378,7 +376,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should accept wildcard subdomains in no_proxy', function() { + it('should accept wildcard subdomains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar, .example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -388,7 +386,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support asterisk wildcard no_proxy syntax', function() { + it('should support asterisk wildcard no_proxy syntax', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = '*.example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -398,7 +396,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support implicit ports in no_proxy', function() { + it('should support implicit ports in no_proxy', function () { process.env.https_proxy = proxyUrl; process.env.no_proxy = 'example.com:443'; settings.urls = ['https://example.com/plugin.zip']; @@ -408,7 +406,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - afterAll(function(done) { + afterAll(function (done) { proxy.close(done); }); }); diff --git a/src/cli_plugin/install/downloaders/file.js b/src/cli_plugin/install/downloaders/file.js index eee8ddb21d6dd..56f83b03d5a90 100644 --- a/src/cli_plugin/install/downloaders/file.js +++ b/src/cli_plugin/install/downloaders/file.js @@ -43,7 +43,7 @@ async function copyFile({ readStream, writeStream, progress }) { writeStream.on('error', reject); // report progress as we transfer - readStream.on('data', chunk => { + readStream.on('data', (chunk) => { progress.progress(chunk.length); }); diff --git a/src/cli_plugin/install/downloaders/http.js b/src/cli_plugin/install/downloaders/http.js index 88dcdabe70dfd..0fc01453f2b4c 100644 --- a/src/cli_plugin/install/downloaders/http.js +++ b/src/cli_plugin/install/downloaders/http.js @@ -76,7 +76,7 @@ function downloadResponse({ resp, targetPath, progress }) { writeStream.on('error', reject); // report progress as we download - resp.on('data', chunk => { + resp.on('data', (chunk) => { progress.progress(chunk.length); }); diff --git a/src/cli_plugin/install/index.test.js b/src/cli_plugin/install/index.test.js index 6a64a673bb93e..39352f52f20fd 100644 --- a/src/cli_plugin/install/index.test.js +++ b/src/cli_plugin/install/index.test.js @@ -20,25 +20,25 @@ import sinon from 'sinon'; import index from './index'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('commander options', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('commander options', function () { const program = { - command: function() { + command: function () { return program; }, - description: function() { + description: function () { return program; }, - option: function() { + option: function () { return program; }, - action: function() { + action: function () { return program; }, }; - it('should define the command', function() { + it('should define the command', function () { sinon.spy(program, 'command'); index(program); @@ -47,7 +47,7 @@ describe('kibana cli', function() { program.command.restore(); }); - it('should define the description', function() { + it('should define the description', function () { sinon.spy(program, 'description'); index(program); @@ -56,7 +56,7 @@ describe('kibana cli', function() { program.description.restore(); }); - it('should define the command line options', function() { + it('should define the command line options', function () { const spy = sinon.spy(program, 'option'); const options = [/-q/, /-s/, /-c/, /-t/, /-d/]; @@ -77,7 +77,7 @@ describe('kibana cli', function() { expect(options).toHaveLength(0); }); - it('should call the action function', function() { + it('should call the action function', function () { sinon.spy(program, 'action'); index(program); diff --git a/src/cli_plugin/install/kibana.test.js b/src/cli_plugin/install/kibana.test.js index bbf364a755f8a..8c5dd00d09953 100644 --- a/src/cli_plugin/install/kibana.test.js +++ b/src/cli_plugin/install/kibana.test.js @@ -30,9 +30,9 @@ beforeEach(() => { jest.clearAllMocks(); }); -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('kibana', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('kibana', function () { const testWorkingPath = join(__dirname, '.test.data.kibana'); const tempArchiveFilePath = join(testWorkingPath, 'archive.part'); const pluginDir = join(__dirname, 'plugins'); @@ -48,21 +48,21 @@ describe('kibana cli', function() { const logger = new Logger(settings); - describe('assertVersion', function() { - beforeEach(function() { + describe('assertVersion', function () { + beforeEach(function () { del.sync(testWorkingPath); fs.mkdirSync(testWorkingPath, { recursive: true }); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(testWorkingPath); }); - it('should succeed with exact match', function() { + it('should succeed with exact match', function () { const settings = { workingPath: testWorkingPath, tempArchiveFile: tempArchiveFilePath, @@ -76,60 +76,60 @@ describe('kibana cli', function() { expect(() => assertVersion(settings)).not.toThrow(); }); - it('should throw an error if plugin is missing a kibana version.', function() { + it('should throw an error if plugin is missing a kibana version.', function () { expect(() => assertVersion(settings)).toThrow( /plugin package\.json is missing both a version property/i ); }); - it('should throw an error if plugin kibanaVersion does not match kibana version', function() { + it('should throw an error if plugin kibanaVersion does not match kibana version', function () { settings.plugins[0].kibanaVersion = '1.2.3.4'; expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i); }); - it('should not throw an error if plugin kibanaVersion matches kibana version', function() { + it('should not throw an error if plugin kibanaVersion matches kibana version', function () { settings.plugins[0].kibanaVersion = '1.0.0'; expect(() => assertVersion(settings)).not.toThrow(); }); - it('should ignore version info after the dash in checks on valid version', function() { + it('should ignore version info after the dash in checks on valid version', function () { settings.plugins[0].kibanaVersion = '1.0.0-foo-bar-version-1.2.3'; expect(() => assertVersion(settings)).not.toThrow(); }); - it('should ignore version info after the dash in checks on invalid version', function() { + it('should ignore version info after the dash in checks on invalid version', function () { settings.plugins[0].kibanaVersion = '2.0.0-foo-bar-version-1.2.3'; expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i); }); }); - describe('existingInstall', function() { + describe('existingInstall', function () { let processExitStub; - beforeEach(function() { + beforeEach(function () { processExitStub = sinon.stub(process, 'exit'); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { processExitStub.restore(); logger.log.restore(); logger.error.restore(); }); - it('should throw an error if the plugin already exists.', function() { + it('should throw an error if the plugin already exists.', function () { fs.statSync.mockImplementationOnce(() => true); existingInstall(settings, logger); expect(logger.error.firstCall.args[0]).toMatch(/already exists/); expect(process.exit.called).toBe(true); }); - it('should not throw an error if the plugin does not exist.', function() { + it('should not throw an error if the plugin does not exist.', function () { fs.statSync.mockImplementationOnce(() => { throw { code: 'ENOENT' }; }); diff --git a/src/cli_plugin/install/pack.test.js b/src/cli_plugin/install/pack.test.js index efe310a4fed40..05a60107f80ff 100644 --- a/src/cli_plugin/install/pack.test.js +++ b/src/cli_plugin/install/pack.test.js @@ -27,8 +27,8 @@ import { extract, getPackData } from './pack'; import { _downloadSingle } from './download'; import { join } from 'path'; -describe('kibana cli', function() { - describe('pack', function() { +describe('kibana cli', function () { + describe('pack', function () { let testNum = 0; const workingPathRoot = join(__dirname, '.test.data.pack'); let testWorkingPath; @@ -37,7 +37,7 @@ describe('kibana cli', function() { let logger; let settings; - beforeEach(function() { + beforeEach(function () { //These tests are dependent on the file system, and I had some inconsistent //behavior with del.sync show up. Until these tests are re-written to not //depend on the file system, I make sure that each test uses a different @@ -60,7 +60,7 @@ describe('kibana cli', function() { Fs.mkdirSync(testWorkingPath, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(workingPathRoot); @@ -77,10 +77,10 @@ describe('kibana cli', function() { throw new Error('expected the promise to reject'); } - describe('extract', function() { + describe('extract', function () { //Also only extracts the content from the kibana folder. //Ignores the others. - it('successfully extract a valid zip', function() { + it('successfully extract a valid zip', function () { return copyReplyFile('test_plugin.zip') .then(() => { return getPackData(settings, logger); @@ -104,8 +104,8 @@ describe('kibana cli', function() { }); }); - describe('getPackData', function() { - it('populate settings.plugins', function() { + describe('getPackData', function () { + it('populate settings.plugins', function () { return copyReplyFile('test_plugin.zip') .then(() => { return getPackData(settings, logger); @@ -118,7 +118,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugin.kibanaVersion', function() { + it('populate settings.plugin.kibanaVersion', function () { //kibana.version is defined in this package.json and is different than plugin version return copyReplyFile('test_plugin_different_version.zip') .then(() => { @@ -129,7 +129,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugin.kibanaVersion (default to plugin version)', function() { + it('populate settings.plugin.kibanaVersion (default to plugin version)', function () { //kibana.version is not defined in this package.json, defaults to plugin version return copyReplyFile('test_plugin.zip') .then(() => { @@ -140,7 +140,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugins with multiple plugins', function() { + it('populate settings.plugins with multiple plugins', function () { return copyReplyFile('test_plugin_many.zip') .then(() => { return getPackData(settings, logger); @@ -172,32 +172,32 @@ describe('kibana cli', function() { }); }); - it('throw an error if there is no kibana plugin', function() { + it('throw an error if there is no kibana plugin', function () { return copyReplyFile('test_plugin_no_kibana.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/No kibana plugins found in archive/i); }); }); - it('throw an error with a corrupt zip', function() { + it('throw an error with a corrupt zip', function () { return copyReplyFile('corrupt.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/error retrieving/i); }); }); - it('throw an error if there an invalid plugin name', function() { + it('throw an error if there an invalid plugin name', function () { return copyReplyFile('invalid_name.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/invalid plugin name/i); }); }); diff --git a/src/cli_plugin/install/progress.test.js b/src/cli_plugin/install/progress.test.js index 5430af75968bb..3b66e8b3dc86c 100644 --- a/src/cli_plugin/install/progress.test.js +++ b/src/cli_plugin/install/progress.test.js @@ -21,26 +21,26 @@ import sinon from 'sinon'; import Progress from './progress'; import Logger from '../lib/logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('progressReporter', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('progressReporter', function () { let logger; let progress; - beforeEach(function() { + beforeEach(function () { logger = new Logger({ silent: false, quiet: false }); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); progress = new Progress(logger); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); }); - describe('handleData', function() { - it('should show a max of 20 dots for full progress', function() { + describe('handleData', function () { + it('should show a max of 20 dots for full progress', function () { progress.init(1000); progress.progress(1000); progress.complete(); @@ -70,7 +70,7 @@ describe('kibana cli', function() { expect(logger.log.getCall(21).args[0]).toMatch(/complete/i); }); - it('should show dot for each 5% of completion', function() { + it('should show dot for each 5% of completion', function () { progress.init(1000); expect(logger.log.callCount).toBe(1); diff --git a/src/cli_plugin/install/rename.js b/src/cli_plugin/install/rename.js index 92adb21368007..1e5d94d474375 100644 --- a/src/cli_plugin/install/rename.js +++ b/src/cli_plugin/install/rename.js @@ -21,7 +21,7 @@ import { rename } from 'fs'; import { delay } from 'lodash'; export function renamePlugin(workingPath, finalPath) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { const start = Date.now(); const retryTime = 3000; const retryDelay = 100; diff --git a/src/cli_plugin/install/rename.test.js b/src/cli_plugin/install/rename.test.js index c725a1218cbd2..40df75adc5efa 100644 --- a/src/cli_plugin/install/rename.test.js +++ b/src/cli_plugin/install/rename.test.js @@ -22,63 +22,63 @@ import fs from 'fs'; import { renamePlugin } from './rename'; -describe('plugin folder rename', function() { +describe('plugin folder rename', function () { let renameStub; - beforeEach(function() { + beforeEach(function () { renameStub = sinon.stub(); }); - afterEach(function() { + afterEach(function () { fs.rename.restore(); }); - it('should rethrow any exceptions', function() { + it('should rethrow any exceptions', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb({ code: 'error', }); }); - return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) { + return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) { expect(err.code).toBe('error'); expect(renameStub.callCount).toBe(1); }); }); - it('should resolve if there are no errors', function() { + it('should resolve if there are no errors', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb(); }); return renamePlugin('/foo/bar', '/bar/foo') - .then(function() { + .then(function () { expect(renameStub.callCount).toBe(1); }) - .catch(function() { + .catch(function () { throw new Error("We shouldn't have any errors"); }); }); - describe('Windows', function() { + describe('Windows', function () { let platform; - beforeEach(function() { + beforeEach(function () { platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32', }); }); - afterEach(function() { + afterEach(function () { Object.defineProperty(process, 'platform', platform); }); - it('should retry on Windows EPERM errors for up to 3 seconds', function() { + it('should retry on Windows EPERM errors for up to 3 seconds', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb({ code: 'EPERM', }); }); - return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) { + return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) { expect(err.code).toBe('EPERM'); expect(renameStub.callCount).toBeGreaterThan(1); }); diff --git a/src/cli_plugin/install/settings.js b/src/cli_plugin/install/settings.js index 1f924caddf1b7..40c845fc37a9e 100644 --- a/src/cli_plugin/install/settings.js +++ b/src/cli_plugin/install/settings.js @@ -56,7 +56,7 @@ export function parse(command, options, kbnPackage) { settings.workingPath = resolve(settings.pluginDir, '.plugin.installing'); settings.tempArchiveFile = resolve(settings.workingPath, 'archive.part'); settings.tempPackageFile = resolve(settings.workingPath, 'package.json'); - settings.setPlugin = function(plugin) { + settings.setPlugin = function (plugin) { settings.plugin = plugin; settings.pluginPath = resolve(settings.pluginDir, settings.plugin.name); }; diff --git a/src/cli_plugin/install/settings.test.js b/src/cli_plugin/install/settings.test.js index 1f0aef4377b40..39ca07405ade2 100644 --- a/src/cli_plugin/install/settings.test.js +++ b/src/cli_plugin/install/settings.test.js @@ -21,23 +21,23 @@ import { fromRoot } from '../../core/server/utils'; import { resolve } from 'path'; import { parseMilliseconds, parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parseMilliseconds function', function() { - it('should return 0 for an empty string', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parseMilliseconds function', function () { + it('should return 0 for an empty string', function () { const value = ''; const result = parseMilliseconds(value); expect(result).toBe(0); }); - it('should return 0 for a number with an invalid unit of measure', function() { + it('should return 0 for a number with an invalid unit of measure', function () { const result = parseMilliseconds('1gigablasts'); expect(result).toBe(0); }); - it('should assume a number with no unit of measure is specified as milliseconds', function() { + it('should assume a number with no unit of measure is specified as milliseconds', function () { const result = parseMilliseconds(1); expect(result).toBe(1); @@ -45,53 +45,53 @@ describe('kibana cli', function() { expect(result2).toBe(1); }); - it('should interpret a number with "s" as the unit of measure as seconds', function() { + it('should interpret a number with "s" as the unit of measure as seconds', function () { const result = parseMilliseconds('5s'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "second" as the unit of measure as seconds', function() { + it('should interpret a number with "second" as the unit of measure as seconds', function () { const result = parseMilliseconds('5second'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "seconds" as the unit of measure as seconds', function() { + it('should interpret a number with "seconds" as the unit of measure as seconds', function () { const result = parseMilliseconds('5seconds'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "m" as the unit of measure as minutes', function() { + it('should interpret a number with "m" as the unit of measure as minutes', function () { const result = parseMilliseconds('9m'); expect(result).toBe(9 * 1000 * 60); }); - it('should interpret a number with "minute" as the unit of measure as minutes', function() { + it('should interpret a number with "minute" as the unit of measure as minutes', function () { const result = parseMilliseconds('9minute'); expect(result).toBe(9 * 1000 * 60); }); - it('should interpret a number with "minutes" as the unit of measure as minutes', function() { + it('should interpret a number with "minutes" as the unit of measure as minutes', function () { const result = parseMilliseconds('9minutes'); expect(result).toBe(9 * 1000 * 60); }); }); - describe('parse function', function() { + describe('parse function', function () { const command = 'plugin name'; let options = {}; const kbnPackage = { version: 1234 }; - beforeEach(function() { + beforeEach(function () { options = { pluginDir: fromRoot('plugins') }; }); - describe('timeout option', function() { - it('should default to 0 (milliseconds)', function() { + describe('timeout option', function () { + it('should default to 0 (milliseconds)', function () { const settings = parse(command, options, kbnPackage); expect(settings.timeout).toBe(0); }); - it('should set settings.timeout property', function() { + it('should set settings.timeout property', function () { options.timeout = 1234; const settings = parse(command, options, kbnPackage); @@ -99,14 +99,14 @@ describe('kibana cli', function() { }); }); - describe('quiet option', function() { - it('should default to false', function() { + describe('quiet option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.quiet).toBe(false); }); - it('should set settings.quiet property to true', function() { + it('should set settings.quiet property to true', function () { options.quiet = true; const settings = parse(command, options, kbnPackage); @@ -114,14 +114,14 @@ describe('kibana cli', function() { }); }); - describe('silent option', function() { - it('should default to false', function() { + describe('silent option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.silent).toBe(false); }); - it('should set settings.silent property to true', function() { + it('should set settings.silent property to true', function () { options.silent = true; const settings = parse(command, options, kbnPackage); @@ -129,14 +129,14 @@ describe('kibana cli', function() { }); }); - describe('config option', function() { - it('should default to ZLS', function() { + describe('config option', function () { + it('should default to ZLS', function () { const settings = parse(command, options, kbnPackage); expect(settings.config).toBe(''); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.config = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -144,14 +144,14 @@ describe('kibana cli', function() { }); }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options, kbnPackage); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.pluginDir = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -159,16 +159,16 @@ describe('kibana cli', function() { }); }); - describe('command value', function() { - it('should set settings.plugin property', function() { + describe('command value', function () { + it('should set settings.plugin property', function () { const settings = parse(command, options, kbnPackage); expect(settings.plugin).toBe(command); }); }); - describe('urls collection', function() { - it('should populate the settings.urls property', function() { + describe('urls collection', function () { + it('should populate the settings.urls property', function () { const settings = parse(command, options, kbnPackage); const expected = [ @@ -180,8 +180,8 @@ describe('kibana cli', function() { }); }); - describe('workingPath value', function() { - it('should set settings.workingPath property', function() { + describe('workingPath value', function () { + it('should set settings.workingPath property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing'); @@ -190,8 +190,8 @@ describe('kibana cli', function() { }); }); - describe('tempArchiveFile value', function() { - it('should set settings.tempArchiveFile property', function() { + describe('tempArchiveFile value', function () { + it('should set settings.tempArchiveFile property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing', 'archive.part'); @@ -200,8 +200,8 @@ describe('kibana cli', function() { }); }); - describe('tempPackageFile value', function() { - it('should set settings.tempPackageFile property', function() { + describe('tempPackageFile value', function () { + it('should set settings.tempPackageFile property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing', 'package.json'); diff --git a/src/cli_plugin/install/zip.js b/src/cli_plugin/install/zip.js index 03e6edb63b4ff..52eba2ea239a2 100644 --- a/src/cli_plugin/install/zip.js +++ b/src/cli_plugin/install/zip.js @@ -34,29 +34,29 @@ export function analyzeArchive(archive) { const regExp = new RegExp('(kibana[\\\\/][^\\\\/]+)[\\\\/]package.json', 'i'); return new Promise((resolve, reject) => { - yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) { + yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) { if (err) { return reject(err); } zipfile.readEntry(); - zipfile.on('entry', function(entry) { + zipfile.on('entry', function (entry) { const match = entry.fileName.match(regExp); if (!match) { return zipfile.readEntry(); } - zipfile.openReadStream(entry, function(err, readable) { + zipfile.openReadStream(entry, function (err, readable) { const chunks = []; if (err) { return reject(err); } - readable.on('data', chunk => chunks.push(chunk)); + readable.on('data', (chunk) => chunks.push(chunk)); - readable.on('end', function() { + readable.on('end', function () { const contents = Buffer.concat(chunks).toString(); const pkg = JSON.parse(contents); @@ -92,14 +92,14 @@ export function _isDirectory(filename) { export function extractArchive(archive, targetDir, extractPath) { return new Promise((resolve, reject) => { - yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) { + yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) { if (err) { return reject(err); } zipfile.readEntry(); zipfile.on('close', resolve); - zipfile.on('entry', function(entry) { + zipfile.on('entry', function (entry) { let fileName = entry.fileName; if (extractPath && fileName.startsWith(extractPath)) { @@ -113,7 +113,7 @@ export function extractArchive(archive, targetDir, extractPath) { } if (_isDirectory(fileName)) { - mkdir(fileName, { recursive: true }, function(err) { + mkdir(fileName, { recursive: true }, function (err) { if (err) { return reject(err); } @@ -122,13 +122,13 @@ export function extractArchive(archive, targetDir, extractPath) { }); } else { // file entry - zipfile.openReadStream(entry, function(err, readStream) { + zipfile.openReadStream(entry, function (err, readStream) { if (err) { return reject(err); } // ensure parent directory exists - mkdir(path.dirname(fileName), { recursive: true }, function(err) { + mkdir(path.dirname(fileName), { recursive: true }, function (err) { if (err) { return reject(err); } @@ -136,7 +136,7 @@ export function extractArchive(archive, targetDir, extractPath) { readStream.pipe( createWriteStream(fileName, { mode: entry.externalFileAttributes >>> 16 }) ); - readStream.on('end', function() { + readStream.on('end', function () { zipfile.readEntry(); }); }); diff --git a/src/cli_plugin/install/zip.test.js b/src/cli_plugin/install/zip.test.js index 8f75367ec8eb4..28367e9e24453 100644 --- a/src/cli_plugin/install/zip.test.js +++ b/src/cli_plugin/install/zip.test.js @@ -24,8 +24,8 @@ import glob from 'glob'; import fs from 'fs'; import { analyzeArchive, extractArchive, _isDirectory } from './zip'; -describe('kibana cli', function() { - describe('zip', function() { +describe('kibana cli', function () { + describe('zip', function () { const repliesPath = path.resolve(__dirname, '__fixtures__', 'replies'); const archivePath = path.resolve(repliesPath, 'test_plugin.zip'); @@ -40,7 +40,7 @@ describe('kibana cli', function() { del.sync(tempPath, { force: true }); }); - describe('analyzeArchive', function() { + describe('analyzeArchive', function () { it('returns array of plugins', async () => { const packages = await analyzeArchive(archivePath); const plugin = packages[0]; diff --git a/src/cli_plugin/lib/log_warnings.js b/src/cli_plugin/lib/log_warnings.js index 3adf0ba849c23..b4542acecb305 100644 --- a/src/cli_plugin/lib/log_warnings.js +++ b/src/cli_plugin/lib/log_warnings.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(settings, logger) { - process.on('warning', warning => { +export default function (settings, logger) { + process.on('warning', (warning) => { // deprecation warnings do no reflect a current problem for // the user and therefor should be filtered out. if (warning.name === 'DeprecationWarning') { diff --git a/src/cli_plugin/lib/logger.test.js b/src/cli_plugin/lib/logger.test.js index db8454f465b47..00cad1a9bbb11 100644 --- a/src/cli_plugin/lib/logger.test.js +++ b/src/cli_plugin/lib/logger.test.js @@ -20,21 +20,21 @@ import sinon from 'sinon'; import Logger from './logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('logger', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('logger', function () { let logger; - describe('logger.log', function() { - beforeEach(function() { + describe('logger.log', function () { + beforeEach(function () { sinon.stub(process.stdout, 'write'); }); - afterEach(function() { + afterEach(function () { process.stdout.write.restore(); }); - it('should log messages to the console and append a new line', function() { + it('should log messages to the console and append a new line', function () { logger = new Logger({ silent: false, quiet: false }); const message = 'this is my message'; @@ -45,7 +45,7 @@ describe('kibana cli', function() { expect(process.stdout.write.getCall(callCount - 1).args[0]).toBe('\n'); }); - it('should log messages to the console and append not append a new line', function() { + it('should log messages to the console and append not append a new line', function () { logger = new Logger({ silent: false, quiet: false }); for (let i = 0; i < 10; i++) { logger.log('.', true); @@ -68,7 +68,7 @@ describe('kibana cli', function() { expect(process.stdout.write.getCall(12).args[0]).toBe('\n'); }); - it('should not log any messages when quiet is set', function() { + it('should not log any messages when quiet is set', function () { logger = new Logger({ silent: false, quiet: true }); const message = 'this is my message'; @@ -82,7 +82,7 @@ describe('kibana cli', function() { expect(process.stdout.write.callCount).toBe(0); }); - it('should not log any messages when silent is set', function() { + it('should not log any messages when silent is set', function () { logger = new Logger({ silent: true, quiet: false }); const message = 'this is my message'; @@ -97,16 +97,16 @@ describe('kibana cli', function() { }); }); - describe('logger.error', function() { - beforeEach(function() { + describe('logger.error', function () { + beforeEach(function () { sinon.stub(process.stderr, 'write'); }); - afterEach(function() { + afterEach(function () { process.stderr.write.restore(); }); - it('should log error messages to the console and append a new line', function() { + it('should log error messages to the console and append a new line', function () { logger = new Logger({ silent: false, quiet: false }); const message = 'this is my error'; @@ -114,7 +114,7 @@ describe('kibana cli', function() { expect(process.stderr.write.calledWith(message + '\n')).toBe(true); }); - it('should log error messages to the console when quiet is set', function() { + it('should log error messages to the console when quiet is set', function () { logger = new Logger({ silent: false, quiet: true }); const message = 'this is my error'; @@ -122,7 +122,7 @@ describe('kibana cli', function() { expect(process.stderr.write.calledWith(message + '\n')).toBe(true); }); - it('should not log any error messages when silent is set', function() { + it('should not log any error messages when silent is set', function () { logger = new Logger({ silent: true, quiet: false }); const message = 'this is my error'; diff --git a/src/cli_plugin/list/list.js b/src/cli_plugin/list/list.js index d53e868b32e36..b34631e5dfd08 100644 --- a/src/cli_plugin/list/list.js +++ b/src/cli_plugin/list/list.js @@ -21,7 +21,7 @@ import { statSync, readdirSync, readFileSync } from 'fs'; import { join } from 'path'; export default function list(settings, logger) { - readdirSync(settings.pluginDir).forEach(filename => { + readdirSync(settings.pluginDir).forEach((filename) => { const stat = statSync(join(settings.pluginDir, filename)); if (stat.isDirectory() && filename[0] !== '.') { diff --git a/src/cli_plugin/list/list.test.js b/src/cli_plugin/list/list.test.js index c6480ca52b59a..071a253fa87fe 100644 --- a/src/cli_plugin/list/list.test.js +++ b/src/cli_plugin/list/list.test.js @@ -30,8 +30,8 @@ function createPlugin(name, version, pluginBaseDir) { appendFileSync(join(pluginDir, 'package.json'), '{"version": "' + version + '"}'); } -describe('kibana cli', function() { - describe('plugin lister', function() { +describe('kibana cli', function () { + describe('plugin lister', function () { const pluginDir = join(__dirname, '.test.data.list'); let logger; @@ -39,7 +39,7 @@ describe('kibana cli', function() { pluginDir: pluginDir, }; - beforeEach(function() { + beforeEach(function () { logger = new Logger(settings); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); @@ -47,13 +47,13 @@ describe('kibana cli', function() { mkdirSync(pluginDir, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(pluginDir); }); - it('list all of the folders in the plugin folder', function() { + it('list all of the folders in the plugin folder', function () { createPlugin('plugin1', '5.0.0-alpha2', pluginDir); createPlugin('plugin2', '3.2.1', pluginDir); createPlugin('plugin3', '1.2.3', pluginDir); @@ -65,7 +65,7 @@ describe('kibana cli', function() { expect(logger.log.calledWith('plugin3@1.2.3')).toBe(true); }); - it('ignore folders that start with a period', function() { + it('ignore folders that start with a period', function () { createPlugin('.foo', '1.0.0', pluginDir); createPlugin('plugin1', '5.0.0-alpha2', pluginDir); createPlugin('plugin2', '3.2.1', pluginDir); @@ -78,7 +78,7 @@ describe('kibana cli', function() { expect(logger.log.calledWith('.bar@1.0.0')).toBe(false); }); - it('list should only list folders', function() { + it('list should only list folders', function () { createPlugin('plugin1', '1.0.0', pluginDir); createPlugin('plugin2', '1.0.0', pluginDir); createPlugin('plugin3', '1.0.0', pluginDir); @@ -91,22 +91,22 @@ describe('kibana cli', function() { expect(logger.log.calledWith('plugin3@1.0.0')).toBe(true); }); - it('list should throw an exception if a plugin does not have a package.json', function() { + it('list should throw an exception if a plugin does not have a package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); mkdirSync(join(pluginDir, 'empty-plugin'), { recursive: true }); - expect(function() { + expect(function () { list(settings, logger); }).toThrowError('Unable to read package.json file for plugin empty-plugin'); }); - it('list should throw an exception if a plugin have an empty package.json', function() { + it('list should throw an exception if a plugin have an empty package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); const invalidPluginDir = join(pluginDir, 'invalid-plugin'); mkdirSync(invalidPluginDir, { recursive: true }); appendFileSync(join(invalidPluginDir, 'package.json'), ''); - expect(function() { + expect(function () { list(settings, logger); }).toThrowError('Unable to read package.json file for plugin invalid-plugin'); }); diff --git a/src/cli_plugin/list/settings.test.js b/src/cli_plugin/list/settings.test.js index 144b5d8661527..85e6cb88e82fd 100644 --- a/src/cli_plugin/list/settings.test.js +++ b/src/cli_plugin/list/settings.test.js @@ -20,24 +20,24 @@ import { fromRoot } from '../../core/server/utils'; import { parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parse function', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parse function', function () { let command; const options = {}; - beforeEach(function() { + beforeEach(function () { command = { pluginDir: fromRoot('plugins') }; }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { command.pluginDir = 'foo bar baz'; const settings = parse(command, options); diff --git a/src/cli_plugin/remove/remove.test.js b/src/cli_plugin/remove/remove.test.js index 032a17abe209e..4bf061820aa05 100644 --- a/src/cli_plugin/remove/remove.test.js +++ b/src/cli_plugin/remove/remove.test.js @@ -25,15 +25,15 @@ import remove from './remove'; import { join } from 'path'; import { writeFileSync, existsSync, mkdirSync } from 'fs'; -describe('kibana cli', function() { - describe('plugin remover', function() { +describe('kibana cli', function () { + describe('plugin remover', function () { const pluginDir = join(__dirname, '.test.data.remove'); let processExitStub; let logger; const settings = { pluginDir }; - beforeEach(function() { + beforeEach(function () { processExitStub = sinon.stub(process, 'exit'); logger = new Logger(settings); sinon.stub(logger, 'log'); @@ -42,14 +42,14 @@ describe('kibana cli', function() { mkdirSync(pluginDir, { recursive: true }); }); - afterEach(function() { + afterEach(function () { processExitStub.restore(); logger.log.restore(); logger.error.restore(); del.sync(pluginDir); }); - it('throw an error if the plugin is not installed.', function() { + it('throw an error if the plugin is not installed.', function () { settings.pluginPath = join(pluginDir, 'foo'); settings.plugin = 'foo'; @@ -58,7 +58,7 @@ describe('kibana cli', function() { expect(process.exit.called).toBe(true); }); - it('throw an error if the specified plugin is not a folder.', function() { + it('throw an error if the specified plugin is not a folder.', function () { writeFileSync(join(pluginDir, 'foo'), 'This is a file, and not a folder.'); remove(settings, logger); @@ -85,7 +85,7 @@ describe('kibana cli', function() { ); }); - it('delete the specified folder.', function() { + it('delete the specified folder.', function () { settings.pluginPath = join(pluginDir, 'foo'); mkdirSync(join(pluginDir, 'foo'), { recursive: true }); mkdirSync(join(pluginDir, 'bar'), { recursive: true }); diff --git a/src/cli_plugin/remove/settings.test.js b/src/cli_plugin/remove/settings.test.js index 5bb4b30cfff09..b3110e1ff0499 100644 --- a/src/cli_plugin/remove/settings.test.js +++ b/src/cli_plugin/remove/settings.test.js @@ -20,25 +20,25 @@ import { fromRoot } from '../../core/server/utils'; import { parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parse function', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parse function', function () { const command = 'plugin name'; let options = {}; const kbnPackage = { version: 1234 }; - beforeEach(function() { + beforeEach(function () { options = { pluginDir: fromRoot('plugins') }; }); - describe('quiet option', function() { - it('should default to false', function() { + describe('quiet option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.quiet).toBe(false); }); - it('should set settings.quiet property to true', function() { + it('should set settings.quiet property to true', function () { options.quiet = true; const settings = parse(command, options, kbnPackage); @@ -46,14 +46,14 @@ describe('kibana cli', function() { }); }); - describe('silent option', function() { - it('should default to false', function() { + describe('silent option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.silent).toBe(false); }); - it('should set settings.silent property to true', function() { + it('should set settings.silent property to true', function () { options.silent = true; const settings = parse(command, options, kbnPackage); @@ -61,14 +61,14 @@ describe('kibana cli', function() { }); }); - describe('config option', function() { - it('should default to ZLS', function() { + describe('config option', function () { + it('should default to ZLS', function () { const settings = parse(command, options, kbnPackage); expect(settings.config).toBe(''); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.config = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -76,14 +76,14 @@ describe('kibana cli', function() { }); }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options, kbnPackage); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.pluginDir = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -91,8 +91,8 @@ describe('kibana cli', function() { }); }); - describe('command value', function() { - it('should set settings.plugin property', function() { + describe('command value', function () { + it('should set settings.plugin property', function () { const settings = parse(command, options, kbnPackage); expect(settings.plugin).toBe(command); diff --git a/src/core/public/application/application_leave.test.ts b/src/core/public/application/application_leave.test.ts index e06183d8bb8d9..b560bbc0cbc25 100644 --- a/src/core/public/application/application_leave.test.ts +++ b/src/core/public/application/application_leave.test.ts @@ -31,16 +31,16 @@ describe('isConfirmAction', () => { describe('getLeaveAction', () => { it('returns the default action provided by the handler', () => { - expect(getLeaveAction(actions => actions.default())).toEqual({ + expect(getLeaveAction((actions) => actions.default())).toEqual({ type: AppLeaveActionType.default, }); }); it('returns the confirm action provided by the handler', () => { - expect(getLeaveAction(actions => actions.confirm('some message'))).toEqual({ + expect(getLeaveAction((actions) => actions.confirm('some message'))).toEqual({ type: AppLeaveActionType.confirm, text: 'some message', }); - expect(getLeaveAction(actions => actions.confirm('another message', 'a title'))).toEqual({ + expect(getLeaveAction((actions) => actions.confirm('another message', 'a title'))).toEqual({ type: AppLeaveActionType.confirm, text: 'another message', title: 'a title', diff --git a/src/core/public/application/application_service.mock.ts b/src/core/public/application/application_service.mock.ts index d2a827d381be5..e8d9e101bfa5a 100644 --- a/src/core/public/application/application_service.mock.ts +++ b/src/core/public/application/application_service.mock.ts @@ -64,7 +64,7 @@ const createInternalStartContractMock = (): jest.Mocked currentAppId$.next(appId)), + navigateToApp: jest.fn().mockImplementation((appId) => currentAppId$.next(appId)), registerMountContext: jest.fn(), }; }; diff --git a/src/core/public/application/application_service.test.ts b/src/core/public/application/application_service.test.ts index 04ff844ffc150..81212b922bd2b 100644 --- a/src/core/public/application/application_service.test.ts +++ b/src/core/public/application/application_service.test.ts @@ -92,7 +92,7 @@ describe('#setup()', () => { const setup = service.setup(setupDeps); const pluginId = Symbol('plugin'); - const updater$ = new BehaviorSubject(app => ({})); + const updater$ = new BehaviorSubject((app) => ({})); setup.register(pluginId, createApp({ id: 'app1', updater$ })); setup.register(pluginId, createApp({ id: 'app2' })); const { applications$ } = await service.start(startDeps); @@ -116,7 +116,7 @@ describe('#setup()', () => { }) ); - updater$.next(app => ({ + updater$.next((app) => ({ status: AppStatus.inaccessible, tooltip: 'App inaccessible due to reason', defaultPath: 'foo/bar', @@ -220,7 +220,7 @@ describe('#setup()', () => { setup.register(pluginId, createApp({ id: 'app1' })); setup.register(pluginId, createApp({ id: 'app2' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { if (app.id === 'app1') { return { status: AppStatus.inaccessible, @@ -260,7 +260,7 @@ describe('#setup()', () => { it(`properly combine with application's updater$`, async () => { const setup = service.setup(setupDeps); const pluginId = Symbol('plugin'); - const appStatusUpdater$ = new BehaviorSubject(app => ({ + const appStatusUpdater$ = new BehaviorSubject((app) => ({ status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, })); @@ -268,7 +268,7 @@ describe('#setup()', () => { setup.register(pluginId, createApp({ id: 'app2' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { if (app.id === 'app1') { return { status: AppStatus.accessible, @@ -311,7 +311,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, @@ -319,7 +319,7 @@ describe('#setup()', () => { }) ); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.accessible, navLinkStatus: AppNavLinkStatus.default, @@ -347,7 +347,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); - const statusUpdater = new BehaviorSubject(app => { + const statusUpdater = new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, @@ -357,7 +357,7 @@ describe('#setup()', () => { const start = await service.start(startDeps); let latestValue: ReadonlyMap = new Map(); - start.applications$.subscribe(apps => { + start.applications$.subscribe((apps) => { latestValue = apps; }); @@ -370,7 +370,7 @@ describe('#setup()', () => { }) ); - statusUpdater.next(app => { + statusUpdater.next((app) => { return { status: AppStatus.accessible, navLinkStatus: AppNavLinkStatus.hidden, @@ -393,7 +393,7 @@ describe('#setup()', () => { setup.registerLegacyApp(createLegacyApp({ id: 'app1' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.hidden, @@ -423,7 +423,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); - const updater = new BehaviorSubject(app => ({})); + const updater = new BehaviorSubject((app) => ({})); setup.registerAppUpdater(updater); const start = await service.start(startDeps); @@ -431,17 +431,17 @@ describe('#setup()', () => { expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined); MockHistory.push.mockClear(); - updater.next(app => ({ defaultPath: 'default-path' })); + updater.next((app) => ({ defaultPath: 'default-path' })); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/default-path', undefined); MockHistory.push.mockClear(); - updater.next(app => ({ defaultPath: 'another-path' })); + updater.next((app) => ({ defaultPath: 'another-path' })); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/another-path', undefined); MockHistory.push.mockClear(); - updater.next(app => ({})); + updater.next((app) => ({})); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined); MockHistory.push.mockClear(); @@ -816,11 +816,11 @@ describe('#start()', () => { const history = createMemoryHistory(); setupDeps.history = history; - const flushPromises = () => new Promise(resolve => setImmediate(resolve)); + const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); // Create an app and a promise that allows us to control when the app completes mounting const createWaitingApp = (props: Partial): [App, () => void] => { let finishMount: () => void; - const mountPromise = new Promise(resolve => (finishMount = resolve)); + const mountPromise = new Promise((resolve) => (finishMount = resolve)); const app = { id: 'some-id', title: 'some-title', diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index 6802c2363b9f8..c22904991161f 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -136,7 +136,7 @@ export class ApplicationService { const registerStatusUpdater = (application: string, updater$: Observable) => { const updaterId = Symbol(); - const subscription = updater$.subscribe(updater => { + const subscription = updater$.subscribe((updater) => { const nextValue = new Map(this.statusUpdaters$.getValue()); nextValue.set(updaterId, { application, @@ -160,7 +160,7 @@ export class ApplicationService { } else { handler = app.mount; } - return async params => { + return async (params) => { this.currentAppId$.next(app.id); return handler(params); }; @@ -201,7 +201,7 @@ export class ApplicationService { legacy: false, }); }, - registerLegacyApp: app => { + registerLegacyApp: (app) => { const appRoute = `/app/${app.id.split(':')[0]}`; if (this.registrationClosed) { @@ -262,7 +262,7 @@ export class ApplicationService { const applications$ = new BehaviorSubject(availableApps); this.statusUpdaters$ .pipe( - map(statusUpdaters => { + map((statusUpdaters) => { return new Map( [...availableApps].map(([id, app]) => [ id, @@ -271,10 +271,10 @@ export class ApplicationService { ); }) ) - .subscribe(apps => applications$.next(apps)); + .subscribe((apps) => applications$.next(apps)); const applicationStatuses$ = applications$.pipe( - map(apps => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))), + map((apps) => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))), shareReplay(1) ); @@ -282,7 +282,7 @@ export class ApplicationService { applications$, capabilities, currentAppId$: this.currentAppId$.pipe( - filter(appId => appId !== undefined), + filter((appId) => appId !== undefined), distinctUntilChanged(), takeUntil(this.stop$) ), @@ -314,7 +314,7 @@ export class ApplicationService { mounters={availableMounters} appStatuses$={applicationStatuses$} setAppLeaveHandler={this.setAppLeaveHandler} - setIsMounting={isMounting => httpLoadingCount$.next(isMounting ? 1 : 0)} + setIsMounting={(isMounting) => httpLoadingCount$.next(isMounting ? 1 : 0)} /> ); }, @@ -360,14 +360,14 @@ export class ApplicationService { this.stop$.next(); this.currentAppId$.complete(); this.statusUpdaters$.complete(); - this.subscriptions.forEach(sub => sub.unsubscribe()); + this.subscriptions.forEach((sub) => sub.unsubscribe()); window.removeEventListener('beforeunload', this.onBeforeUnload); } } const updateStatus = (app: T, statusUpdaters: AppUpdaterWrapper[]): T => { let changes: Partial = {}; - statusUpdaters.forEach(wrapper => { + statusUpdaters.forEach((wrapper) => { if (wrapper.application !== allApplicationsFilter && wrapper.application !== app.id) { return; } diff --git a/src/core/public/application/integration_tests/application_service.test.tsx b/src/core/public/application/integration_tests/application_service.test.tsx index e399fbc726977..89f90a9899dda 100644 --- a/src/core/public/application/integration_tests/application_service.test.tsx +++ b/src/core/public/application/integration_tests/application_service.test.tsx @@ -31,7 +31,7 @@ import { overlayServiceMock } from '../../overlays/overlay_service.mock'; import { AppMountParameters } from '../types'; import { ScopedHistory } from '../scoped_history'; -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); describe('ApplicationService', () => { let setupDeps: MockLifecycle<'setup'>; @@ -68,7 +68,7 @@ describe('ApplicationService', () => { const { register } = service.setup(setupDeps); let resolveMount: () => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolveMount = resolve; }); @@ -102,7 +102,7 @@ describe('ApplicationService', () => { const { register } = service.setup(setupDeps); let resolveMount: () => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolveMount = resolve; }); @@ -146,7 +146,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.default()); + onAppLeave((actions) => actions.default()); return () => undefined; }, }); @@ -178,7 +178,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.default()); + onAppLeave((actions) => actions.default()); return () => undefined; }, }); @@ -213,7 +213,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title')); + onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title')); return () => undefined; }, }); @@ -252,7 +252,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title')); + onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title')); return () => undefined; }, }); diff --git a/src/core/public/application/integration_tests/router.test.tsx b/src/core/public/application/integration_tests/router.test.tsx index 9f379859dc34f..2827b93f6d17e 100644 --- a/src/core/public/application/integration_tests/router.test.tsx +++ b/src/core/public/application/integration_tests/router.test.tsx @@ -45,7 +45,7 @@ describe('AppRouter', () => { const mountersToAppStatus$ = () => { return new BehaviorSubject( new Map( - [...mounters.keys()].map(id => [ + [...mounters.keys()].map((id) => [ id, id.startsWith('disabled') ? AppStatus.inaccessible : AppStatus.accessible, ]) diff --git a/src/core/public/application/integration_tests/utils.tsx b/src/core/public/application/integration_tests/utils.tsx index 6c1b81a26d63c..8590fb3c820ef 100644 --- a/src/core/public/application/integration_tests/utils.tsx +++ b/src/core/public/application/integration_tests/utils.tsx @@ -33,7 +33,7 @@ export const createRenderer = (element: ReactElement | null): Renderer => { const dom: Dom = element && mount({element}); return () => - new Promise(async resolve => { + new Promise(async (resolve) => { if (dom) { await act(async () => { dom.update(); diff --git a/src/core/public/application/scoped_history.test.ts b/src/core/public/application/scoped_history.test.ts index a56cffef1e2f2..2b217e54228c2 100644 --- a/src/core/public/application/scoped_history.test.ts +++ b/src/core/public/application/scoped_history.test.ts @@ -217,7 +217,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - h.listen(l => listenPaths.push(l.pathname)); + h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); h.push('/second-page'); h.push('/third-page'); @@ -237,7 +237,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - const unlisten = h.listen(l => listenPaths.push(l.pathname)); + const unlisten = h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); unlisten(); h.push('/second-page'); @@ -252,7 +252,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - h.listen(l => listenPaths.push(l.pathname)); + h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); gh.push('/app/other'); gh.push('/second-page'); diff --git a/src/core/public/application/scoped_history.ts b/src/core/public/application/scoped_history.ts index 9fa8f0b7f8148..1a7fafa5d85c4 100644 --- a/src/core/public/application/scoped_history.ts +++ b/src/core/public/application/scoped_history.ts @@ -324,7 +324,7 @@ export class ScopedHistory throw new Error(`Unrecognized history action: ${action}`); } - [...this.listeners].forEach(listener => { + [...this.listeners].forEach((listener) => { listener(this.stripBasePath(location), action); }); }); diff --git a/src/core/public/application/ui/app_container.test.tsx b/src/core/public/application/ui/app_container.test.tsx index 5d573d47bd420..229354a014103 100644 --- a/src/core/public/application/ui/app_container.test.tsx +++ b/src/core/public/application/ui/app_container.test.tsx @@ -37,14 +37,14 @@ describe('AppContainer', () => { }); const flushPromises = async () => { - await new Promise(async resolve => { + await new Promise(async (resolve) => { setImmediate(() => resolve()); }); }; const createResolver = (): [Promise, () => void] => { let resolve: () => void | undefined; - const promise = new Promise(r => { + const promise = new Promise((r) => { resolve = r; }); return [promise, resolve!]; diff --git a/src/core/public/application/ui/app_container.tsx b/src/core/public/application/ui/app_container.tsx index 4317ede547202..332c31c64b6ba 100644 --- a/src/core/public/application/ui/app_container.tsx +++ b/src/core/public/application/ui/app_container.tsx @@ -83,7 +83,7 @@ export const AppContainer: FunctionComponent = ({ appBasePath: mounter.appBasePath, history: createScopedHistory(appPath), element: elementRef.current!, - onAppLeave: handler => setAppLeaveHandler(appId, handler), + onAppLeave: (handler) => setAppLeaveHandler(appId, handler), })) || null; } catch (e) { // TODO: add error UI diff --git a/src/core/public/chrome/chrome_service.test.ts b/src/core/public/chrome/chrome_service.test.ts index b5cf900d9c39f..0bc305ed9e28c 100644 --- a/src/core/public/chrome/chrome_service.test.ts +++ b/src/core/public/chrome/chrome_service.test.ts @@ -56,7 +56,7 @@ function defaultStartDeps(availableApps?: App[]) { if (availableApps) { deps.application.applications$ = new Rx.BehaviorSubject>( - new Map(availableApps.map(app => [app.id, app])) + new Map(availableApps.map((app) => [app.id, app])) ); } @@ -133,10 +133,7 @@ describe('start', () => { describe('brand', () => { it('updates/emits the brand as it changes', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBrand$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBrand$().pipe(toArray()).toPromise(); chrome.setBrand({ logo: 'big logo', @@ -166,10 +163,7 @@ describe('start', () => { describe('visibility', () => { it('emits false when no application is mounted', async () => { const { chrome, service } = await start(); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); chrome.setIsVisible(true); chrome.setIsVisible(false); @@ -192,10 +186,7 @@ describe('start', () => { const { navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); await navigateToApp('alpha'); @@ -222,13 +213,10 @@ describe('start', () => { ]); const { applications$, navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); const availableApps = await applications$.pipe(take(1)).toPromise(); - [...availableApps.keys()].forEach(appId => navigateToApp(appId)); + [...availableApps.keys()].forEach((appId) => navigateToApp(appId)); service.stop(); await expect(promise).resolves.toMatchInlineSnapshot(` @@ -245,10 +233,7 @@ describe('start', () => { const startDeps = defaultStartDeps([new FakeApp('alpha', true)]); const { navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); await navigateToApp('alpha'); chrome.setIsVisible(true); @@ -267,10 +252,7 @@ describe('start', () => { describe('application classes', () => { it('updates/emits the application classes', async () => { const { chrome, service } = await start(); - const promise = chrome - .getApplicationClasses$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getApplicationClasses$().pipe(toArray()).toPromise(); chrome.addApplicationClass('foo'); chrome.addApplicationClass('foo'); @@ -318,10 +300,7 @@ describe('start', () => { describe('badge', () => { it('updates/emits the current badge', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBadge$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBadge$().pipe(toArray()).toPromise(); chrome.setBadge({ text: 'foo', tooltip: `foo's tooltip` }); chrome.setBadge({ text: 'bar', tooltip: `bar's tooltip` }); @@ -348,10 +327,7 @@ describe('start', () => { describe('breadcrumbs', () => { it('updates/emits the current set of breadcrumbs', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBreadcrumbs$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBreadcrumbs$().pipe(toArray()).toPromise(); chrome.setBreadcrumbs([{ text: 'foo' }, { text: 'bar' }]); chrome.setBreadcrumbs([{ text: 'foo' }]); @@ -389,10 +365,7 @@ describe('start', () => { describe('help extension', () => { it('updates/emits the current help extension', async () => { const { chrome, service } = await start(); - const promise = chrome - .getHelpExtension$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getHelpExtension$().pipe(toArray()).toPromise(); chrome.setHelpExtension({ appName: 'App name', content: () => () => undefined }); chrome.setHelpExtension(undefined); diff --git a/src/core/public/chrome/chrome_service.tsx b/src/core/public/chrome/chrome_service.tsx index a921e514050b2..fc7e78f209022 100644 --- a/src/core/public/chrome/chrome_service.tsx +++ b/src/core/public/chrome/chrome_service.tsx @@ -117,9 +117,9 @@ export class ChromeService { // in the sense that the chrome UI should not be displayed until a non-chromeless app is mounting or mounted of(true), application.currentAppId$.pipe( - flatMap(appId => + flatMap((appId) => application.applications$.pipe( - map(applications => { + map((applications) => { return !!appId && applications.has(appId) && !!applications.get(appId)!.chromeless; }) ) @@ -260,7 +260,7 @@ export class ChromeService { getApplicationClasses$: () => applicationClasses$.pipe( - map(set => [...set]), + map((set) => [...set]), takeUntil(this.stop$) ), diff --git a/src/core/public/chrome/doc_title/doc_title_service.ts b/src/core/public/chrome/doc_title/doc_title_service.ts index 9453abe54de66..c6e9ec7a40b77 100644 --- a/src/core/public/chrome/doc_title/doc_title_service.ts +++ b/src/core/public/chrome/doc_title/doc_title_service.ts @@ -86,7 +86,7 @@ export class DocTitleService { this.applyTitle(defaultTitle); }, __legacy: { - setBaseTitle: baseTitle => { + setBaseTitle: (baseTitle) => { this.baseTitle = baseTitle; }, }, diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts index c8f168bbcb2f7..ac556c1d1cc5d 100644 --- a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts +++ b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts @@ -30,12 +30,7 @@ describe('RecentlyAccessed#start()', () => { const navControls = getStart(); const nc = { mount: jest.fn() }; navControls.registerLeft(nc); - expect( - await navControls - .getLeft$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc]); + expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc]); }); it('sorts controls by order property', async () => { @@ -46,12 +41,7 @@ describe('RecentlyAccessed#start()', () => { navControls.registerLeft(nc1); navControls.registerLeft(nc2); navControls.registerLeft(nc3); - expect( - await navControls - .getLeft$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc2, nc1, nc3]); + expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]); }); }); @@ -60,12 +50,7 @@ describe('RecentlyAccessed#start()', () => { const navControls = getStart(); const nc = { mount: jest.fn() }; navControls.registerRight(nc); - expect( - await navControls - .getRight$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc]); + expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc]); }); it('sorts controls by order property', async () => { @@ -76,12 +61,7 @@ describe('RecentlyAccessed#start()', () => { navControls.registerRight(nc1); navControls.registerRight(nc2); navControls.registerRight(nc3); - expect( - await navControls - .getRight$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc2, nc1, nc3]); + expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]); }); }); }); diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.ts b/src/core/public/chrome/nav_controls/nav_controls_service.ts index 7f9c75595a4ce..167948e01cb36 100644 --- a/src/core/public/chrome/nav_controls/nav_controls_service.ts +++ b/src/core/public/chrome/nav_controls/nav_controls_service.ts @@ -74,12 +74,12 @@ export class NavControlsService { getLeft$: () => navControlsLeft$.pipe( - map(controls => sortBy([...controls.values()], 'order')), + map((controls) => sortBy([...controls.values()], 'order')), takeUntil(this.stop$) ), getRight$: () => navControlsRight$.pipe( - map(controls => sortBy([...controls.values()], 'order')), + map((controls) => sortBy([...controls.values()], 'order')), takeUntil(this.stop$) ), }; diff --git a/src/core/public/chrome/nav_links/nav_links_service.test.ts b/src/core/public/chrome/nav_links/nav_links_service.test.ts index 3d9a4bfdb6a56..8f610e238b0fd 100644 --- a/src/core/public/chrome/nav_links/nav_links_service.test.ts +++ b/src/core/public/chrome/nav_links/nav_links_service.test.ts @@ -90,7 +90,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).not.toContain('chromelessApp'); @@ -102,16 +102,16 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); }); it('emits multiple values', async () => { - const navLinkIds$ = start.getNavLinks$().pipe(map(links => links.map(l => l.id))); + const navLinkIds$ = start.getNavLinks$().pipe(map((links) => links.map((l) => l.id))); const emittedLinks: string[][] = []; - navLinkIds$.subscribe(r => emittedLinks.push(r)); + navLinkIds$.subscribe((r) => emittedLinks.push(r)); start.update('legacyApp1', { active: true }); service.stop(); @@ -122,10 +122,7 @@ describe('NavLinksService', () => { }); it('completes when service is stopped', async () => { - const last$ = start - .getNavLinks$() - .pipe(takeLast(1)) - .toPromise(); + const last$ = start.getNavLinks$().pipe(takeLast(1)).toPromise(); service.stop(); await expect(last$).resolves.toBeInstanceOf(Array); }); @@ -143,7 +140,7 @@ describe('NavLinksService', () => { describe('#getAll()', () => { it('returns a sorted array of navlinks', () => { - expect(start.getAll().map(l => l.id)).toEqual([ + expect(start.getAll().map((l) => l.id)).toEqual([ 'app2', 'legacyApp2', 'app1', @@ -171,7 +168,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); @@ -184,7 +181,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); @@ -197,7 +194,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['legacyApp1']); @@ -211,7 +208,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['legacyApp2']); @@ -236,7 +233,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.filter(l => l.hidden).map(l => l.id)) + map((links) => links.filter((l) => l.hidden).map((l) => l.id)) ) .toPromise(); expect(hiddenLinkIds).toEqual(['legacyApp1']); @@ -253,7 +250,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.filter(l => l.hidden).map(l => l.id)) + map((links) => links.filter((l) => l.hidden).map((l) => l.id)) ) .toPromise(); expect(hiddenLinkIds).toEqual(['legacyApp1']); @@ -262,21 +259,15 @@ describe('NavLinksService', () => { describe('#enableForcedAppSwitcherNavigation()', () => { it('flips #getForceAppSwitcherNavigation$()', async () => { - await expect( - start - .getForceAppSwitcherNavigation$() - .pipe(take(1)) - .toPromise() - ).resolves.toBe(false); + await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe( + false + ); start.enableForcedAppSwitcherNavigation(); - await expect( - start - .getForceAppSwitcherNavigation$() - .pipe(take(1)) - .toPromise() - ).resolves.toBe(true); + await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe( + true + ); }); }); }); diff --git a/src/core/public/chrome/nav_links/nav_links_service.ts b/src/core/public/chrome/nav_links/nav_links_service.ts index fec9322b0d77d..3095bb86b72e2 100644 --- a/src/core/public/chrome/nav_links/nav_links_service.ts +++ b/src/core/public/chrome/nav_links/nav_links_service.ts @@ -108,7 +108,7 @@ export class NavLinksService { public start({ application, http }: StartDeps): ChromeNavLinks { const appLinks$ = application.applications$.pipe( - map(apps => { + map((apps) => { return new Map( [...apps] .filter(([, app]) => !app.chromeless) @@ -129,7 +129,7 @@ export class NavLinksService { return linkUpdaters.reduce((links, updater) => updater(links), appLinks); }) ) - .subscribe(navlinks => { + .subscribe((navlinks) => { navLinks$.next(navlinks); }); @@ -158,7 +158,7 @@ export class NavLinksService { return; } - const updater: LinksUpdater = navLinks => + const updater: LinksUpdater = (navLinks) => new Map([...navLinks.entries()].filter(([linkId]) => linkId === id)); linkUpdaters$.next([...linkUpdaters$.value, updater]); @@ -169,7 +169,7 @@ export class NavLinksService { return; } - const updater: LinksUpdater = navLinks => + const updater: LinksUpdater = (navLinks) => new Map( [...navLinks.entries()].map(([linkId, link]) => { return [linkId, link.id === id ? link.update(values) : link] as [ @@ -200,7 +200,7 @@ export class NavLinksService { function sortNavLinks(navLinks: ReadonlyMap) { return sortBy( - [...navLinks.values()].map(link => link.properties), + [...navLinks.values()].map((link) => link.properties), 'order' ); } diff --git a/src/core/public/chrome/recently_accessed/persisted_log.ts b/src/core/public/chrome/recently_accessed/persisted_log.ts index 421f553f6a315..ca94e0bcddfaf 100644 --- a/src/core/public/chrome/recently_accessed/persisted_log.ts +++ b/src/core/public/chrome/recently_accessed/persisted_log.ts @@ -57,7 +57,7 @@ export class PersistedLog { const nextItems = [ val, // remove any duplicate items - ...[...this.items$.value].filter(item => !this.isEqual(item, val)), + ...[...this.items$.value].filter((item) => !this.isEqual(item, val)), ].slice(0, this.maxLength); // truncate // Persist the stack to storage @@ -73,7 +73,7 @@ export class PersistedLog { } public get$() { - return this.items$.pipe(map(items => cloneDeep(items))); + return this.items$.pipe(map((items) => cloneDeep(items))); } private loadItems() { diff --git a/src/core/public/chrome/ui/header/collapsible_nav.tsx b/src/core/public/chrome/ui/header/collapsible_nav.tsx index 60463d8dccc9b..8bca42db23517 100644 --- a/src/core/public/chrome/ui/header/collapsible_nav.tsx +++ b/src/core/public/chrome/ui/header/collapsible_nav.tsx @@ -50,7 +50,7 @@ function getOrderedCategories( ) { return sortBy( Object.keys(mainCategories), - categoryName => categoryDictionary[categoryName]?.order + (categoryName) => categoryDictionary[categoryName]?.order ); } @@ -94,7 +94,7 @@ export function CollapsibleNav({ storage = window.localStorage, }: Props) { const lockRef = useRef(null); - const groupedNavLinks = groupBy(navLinks, link => link?.category?.id); + const groupedNavLinks = groupBy(navLinks, (link) => link?.category?.id); const { undefined: unknowns = [], ...allCategorizedLinks } = groupedNavLinks; const categoryDictionary = getAllCategories(allCategorizedLinks); const orderedCategories = getOrderedCategories(allCategorizedLinks, categoryDictionary); @@ -156,7 +156,7 @@ export function CollapsibleNav({ title={i18n.translate('core.ui.recentlyViewed', { defaultMessage: 'Recently viewed' })} isCollapsible={true} initialIsOpen={getIsCategoryOpen('recentlyViewed', storage)} - onToggle={isCategoryOpen => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)} + onToggle={(isCategoryOpen) => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)} data-test-subj="collapsibleNavGroup-recentlyViewed" > {recentNavLinks.length > 0 ? ( @@ -218,7 +218,7 @@ export function CollapsibleNav({ title={category.label} isCollapsible={true} initialIsOpen={getIsCategoryOpen(category.id, storage)} - onToggle={isCategoryOpen => setIsCategoryOpen(category.id, isCategoryOpen, storage)} + onToggle={(isCategoryOpen) => setIsCategoryOpen(category.id, isCategoryOpen, storage)} data-test-subj={`collapsibleNavGroup-${category.id}`} > { super(props); let isLocked = false; - props.isLocked$.subscribe(initialIsLocked => (isLocked = initialIsLocked)); + props.isLocked$.subscribe((initialIsLocked) => (isLocked = initialIsLocked)); this.state = { appTitle: 'Kibana', @@ -142,7 +142,7 @@ export class Header extends Component { appTitle, isVisible, forceNavigation, - navLinks: navLinks.filter(navLink => !navLink.hidden), + navLinks: navLinks.filter((navLink) => !navLink.hidden), recentlyAccessed, navControlsLeft, navControlsRight, @@ -183,7 +183,7 @@ export class Header extends Component { kibanaDocLink, kibanaVersion, } = this.props; - const navLinks = this.state.navLinks.map(link => + const navLinks = this.state.navLinks.map((link) => createNavLink( link, this.props.legacyMode, @@ -192,7 +192,7 @@ export class Header extends Component { this.props.application.navigateToApp ) ); - const recentNavLinks = this.state.recentlyAccessed.map(link => + const recentNavLinks = this.state.recentlyAccessed.map((link) => createRecentNavLink(link, this.state.navLinks, this.props.basePath) ); diff --git a/src/core/public/chrome/ui/header/header_badge.tsx b/src/core/public/chrome/ui/header/header_badge.tsx index 4e529ad9a410b..d2d5e5d663300 100644 --- a/src/core/public/chrome/ui/header/header_badge.tsx +++ b/src/core/public/chrome/ui/header/header_badge.tsx @@ -77,7 +77,7 @@ export class HeaderBadge extends Component { } private subscribe() { - this.subscription = this.props.badge$.subscribe(badge => { + this.subscription = this.props.badge$.subscribe((badge) => { this.setState({ badge, }); diff --git a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx index 83840cff45d03..54cfc7131cb2b 100644 --- a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx +++ b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx @@ -70,7 +70,7 @@ export class HeaderBreadcrumbs extends Component { } private subscribe() { - this.subscription = this.props.breadcrumbs$.subscribe(breadcrumbs => { + this.subscription = this.props.breadcrumbs$.subscribe((breadcrumbs) => { this.setState({ breadcrumbs, }); diff --git a/src/core/public/chrome/ui/header/header_logo.tsx b/src/core/public/chrome/ui/header/header_logo.tsx index 4296064945455..147c7cf5dc4b1 100644 --- a/src/core/public/chrome/ui/header/header_logo.tsx +++ b/src/core/public/chrome/ui/header/header_logo.tsx @@ -49,7 +49,7 @@ function onClick( return; } - const navLink = navLinks.find(item => item.href === anchor.href); + const navLink = navLinks.find((item) => item.href === anchor.href); if (navLink && navLink.isDisabled) { event.preventDefault(); return; @@ -95,7 +95,7 @@ export function HeaderLogo({ href, forceNavigation, navLinks, navigateToApp }: P onClick(e, forceNavigation, navLinks, navigateToApp)} + onClick={(e) => onClick(e, forceNavigation, navLinks, navigateToApp)} href={href} aria-label={i18n.translate('core.ui.chrome.headerGlobalNav.goHomePageIconAriaLabel', { defaultMessage: 'Go to home page', diff --git a/src/core/public/chrome/ui/header/nav_link.tsx b/src/core/public/chrome/ui/header/nav_link.tsx index 8003c22b99a36..c979bb8271e1b 100644 --- a/src/core/public/chrome/ui/header/nav_link.tsx +++ b/src/core/public/chrome/ui/header/nav_link.tsx @@ -161,7 +161,7 @@ export function createRecentNavLink( ) { const { link, label } = recentLink; const href = relativeToAbsolute(basePath.prepend(link)); - const navLink = navLinks.find(nl => href.startsWith(nl.baseUrl ?? nl.subUrlBase)); + const navLink = navLinks.find((nl) => href.startsWith(nl.baseUrl ?? nl.subUrlBase)); let titleAndAriaLabel = label; if (navLink) { diff --git a/src/core/public/chrome/ui/loading_indicator.tsx b/src/core/public/chrome/ui/loading_indicator.tsx index 7729302b6b612..0209612eae08c 100644 --- a/src/core/public/chrome/ui/loading_indicator.tsx +++ b/src/core/public/chrome/ui/loading_indicator.tsx @@ -35,7 +35,7 @@ export class LoadingIndicator extends React.Component { + this.loadingCountSubscription = this.props.loadingCount$.subscribe((count) => { this.setState({ visible: count > 0, }); diff --git a/src/core/public/entry_point.ts b/src/core/public/entry_point.ts index 9461acccf30b9..1594a25dcd500 100644 --- a/src/core/public/entry_point.ts +++ b/src/core/public/entry_point.ts @@ -42,8 +42,8 @@ if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && process.env.ELASTIC_APM_AC i18n .load(injectedMetadata.i18n.translationsUrl) - .catch(e => e) - .then(async i18nError => { + .catch((e) => e) + .then(async (i18nError) => { const coreSystem = new CoreSystem({ injectedMetadata, rootDomElement: document.body, diff --git a/src/core/public/fatal_errors/fatal_errors_screen.tsx b/src/core/public/fatal_errors/fatal_errors_screen.tsx index f7184b01a0a78..98eb9f0ef21d5 100644 --- a/src/core/public/fatal_errors/fatal_errors_screen.tsx +++ b/src/core/public/fatal_errors/fatal_errors_screen.tsx @@ -63,8 +63,8 @@ export class FatalErrorsScreen extends React.Component { // consume error notifications and set them to the component state this.props.errorInfo$.pipe( - tap(error => { - this.setState(state => ({ + tap((error) => { + this.setState((state) => ({ ...state, errors: [...state.errors, error], })); diff --git a/src/core/public/fatal_errors/fatal_errors_service.test.ts b/src/core/public/fatal_errors/fatal_errors_service.test.ts index 373b0efddc2cf..a39f31d2c559c 100644 --- a/src/core/public/fatal_errors/fatal_errors_service.test.ts +++ b/src/core/public/fatal_errors/fatal_errors_service.test.ts @@ -20,7 +20,7 @@ import * as Rx from 'rxjs'; expect.addSnapshotSerializer({ - test: val => val instanceof Rx.Observable, + test: (val) => val instanceof Rx.Observable, print: () => `Rx.Observable`, }); diff --git a/src/core/public/fatal_errors/fatal_errors_service.tsx b/src/core/public/fatal_errors/fatal_errors_service.tsx index 309f07859ef26..403f8925b99c7 100644 --- a/src/core/public/fatal_errors/fatal_errors_service.tsx +++ b/src/core/public/fatal_errors/fatal_errors_service.tsx @@ -85,7 +85,7 @@ export class FatalErrorsService { }) ) .subscribe({ - error: error => { + error: (error) => { // eslint-disable-next-line no-console console.error('Uncaught error in fatal error service internals', error); }, @@ -145,7 +145,7 @@ export class FatalErrorsService { private setupGlobalErrorHandlers(fatalErrorsSetup: FatalErrorsSetup) { if (window.addEventListener) { - window.addEventListener('unhandledrejection', function(e) { + window.addEventListener('unhandledrejection', function (e) { console.log(`Detected an unhandled Promise rejection.\n${e.reason}`); // eslint-disable-line no-console }); } diff --git a/src/core/public/http/base_path.ts b/src/core/public/http/base_path.ts index 67464a6196b02..ac85d71c793fe 100644 --- a/src/core/public/http/base_path.ts +++ b/src/core/public/http/base_path.ts @@ -49,7 +49,7 @@ export class BasePath { public prepend = (path: string): string => { if (!this.basePath) return path; - return modifyUrl(path, parts => { + return modifyUrl(path, (parts) => { if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) { parts.pathname = `${this.basePath}${parts.pathname}`; } diff --git a/src/core/public/http/fetch.test.ts b/src/core/public/http/fetch.test.ts index f223956075e97..d889fae335ece 100644 --- a/src/core/public/http/fetch.test.ts +++ b/src/core/public/http/fetch.test.ts @@ -28,7 +28,7 @@ import { BasePath } from './base_path'; import { HttpResponse, HttpFetchOptionsWithPath } from './types'; function delay(duration: number) { - return new Promise(r => setTimeout(r, duration)); + return new Promise((r) => setTimeout(r, duration)); } const BASE_PATH = 'http://localhost/myBase'; @@ -44,11 +44,7 @@ describe('Fetch', () => { }); describe('getRequestCount$', () => { - const getCurrentRequestCount = () => - fetchInstance - .getRequestCount$() - .pipe(first()) - .toPromise(); + const getCurrentRequestCount = () => fetchInstance.getRequestCount$().pipe(first()).toPromise(); it('should increase and decrease when request receives success response', async () => { fetchMock.get('*', 200); @@ -88,7 +84,7 @@ describe('Fetch', () => { const requestCounts: number[] = []; const subscription = fetchInstance .getRequestCount$() - .subscribe(count => requestCounts.push(count)); + .subscribe((count) => requestCounts.push(count)); const success1 = fetchInstance.fetch('/success'); const success2 = fetchInstance.fetch('/success'); @@ -371,7 +367,7 @@ describe('Fetch', () => { fetchMock.get('*', Promise.reject(abortError)); - await fetchInstance.fetch('/my/path').catch(e => { + await fetchInstance.fetch('/my/path').catch((e) => { expect(e.name).toEqual('AbortError'); }); }); diff --git a/src/core/public/http/fetch.ts b/src/core/public/http/fetch.ts index d88dc2e3a9037..bf9b4235e9444 100644 --- a/src/core/public/http/fetch.ts +++ b/src/core/public/http/fetch.ts @@ -212,7 +212,7 @@ const validateFetchArguments = ( ); } - const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter(headerName => + const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter((headerName) => headerName.startsWith('kbn-') ); if (invalidHeaders.length) { diff --git a/src/core/public/http/intercept.ts b/src/core/public/http/intercept.ts index bacc8748d2680..be02ebbf94fae 100644 --- a/src/core/public/http/intercept.ts +++ b/src/core/public/http/intercept.ts @@ -31,7 +31,7 @@ export async function interceptRequest( return [...interceptors].reduceRight( (promise, interceptor) => promise.then( - async fetchOptions => { + async (fetchOptions) => { current = fetchOptions; checkHalt(controller); @@ -45,7 +45,7 @@ export async function interceptRequest( ...overrides, }; }, - async error => { + async (error) => { checkHalt(controller, error); if (!interceptor.requestError) { @@ -83,7 +83,7 @@ export async function interceptResponse( return await [...interceptors].reduce( (promise, interceptor) => promise.then( - async httpResponse => { + async (httpResponse) => { current = httpResponse; checkHalt(controller); @@ -98,7 +98,7 @@ export async function interceptResponse( ...interceptorOverrides, }; }, - async error => { + async (error) => { const request = error.request || (current && current.request); checkHalt(controller, error); diff --git a/src/core/public/http/loading_count_service.test.ts b/src/core/public/http/loading_count_service.test.ts index 3ba4d315178cc..706d62b4283ba 100644 --- a/src/core/public/http/loading_count_service.test.ts +++ b/src/core/public/http/loading_count_service.test.ts @@ -89,10 +89,7 @@ describe('LoadingCountService', () => { const countA$ = new Subject(); const countB$ = new Subject(); const countC$ = new Subject(); - const promise = loadingCount - .getLoadingCount$() - .pipe(toArray()) - .toPromise(); + const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise(); loadingCount.addLoadingCountSource(countA$); loadingCount.addLoadingCountSource(countB$); @@ -125,10 +122,7 @@ describe('LoadingCountService', () => { const { service, loadingCount } = setup(); const count$ = new Subject(); - const promise = loadingCount - .getLoadingCount$() - .pipe(toArray()) - .toPromise(); + const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise(); loadingCount.addLoadingCountSource(count$); count$.next(0); diff --git a/src/core/public/http/loading_count_service.ts b/src/core/public/http/loading_count_service.ts index 14b945e0801ca..e4a248daca8f2 100644 --- a/src/core/public/http/loading_count_service.ts +++ b/src/core/public/http/loading_count_service.ts @@ -56,7 +56,7 @@ export class LoadingCountService implements CoreService { + tap((count) => { if (count < 0) { throw new Error( 'Observables passed to loadingCount.add() must only emit positive numbers' @@ -73,10 +73,10 @@ export class LoadingCountService implements CoreService next - prev) ) .subscribe({ - next: delta => { + next: (delta) => { this.loadingCount$.next(this.loadingCount$.getValue() + delta); }, - error: error => fatalErrors.add(error), + error: (error) => fatalErrors.add(error), }); }, }; diff --git a/src/core/public/integrations/moment/moment_service.test.mocks.ts b/src/core/public/integrations/moment/moment_service.test.mocks.ts index bb13232157b78..4c0c584679b2c 100644 --- a/src/core/public/integrations/moment/moment_service.test.mocks.ts +++ b/src/core/public/integrations/moment/moment_service.test.mocks.ts @@ -22,7 +22,7 @@ export const momentMock = { tz: { setDefault: jest.fn(), zone: jest.fn( - z => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find(f => z === f.name) || null + (z) => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find((f) => z === f.name) || null ), }, weekdays: jest.fn(() => ['dow1', 'dow2', 'dow3']), diff --git a/src/core/public/integrations/moment/moment_service.test.ts b/src/core/public/integrations/moment/moment_service.test.ts index bc48ba2a85f63..5179ff468f84d 100644 --- a/src/core/public/integrations/moment/moment_service.test.ts +++ b/src/core/public/integrations/moment/moment_service.test.ts @@ -32,7 +32,7 @@ describe('MomentService', () => { }); afterEach(() => service.stop()); - const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100)); + const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100)); test('sets initial moment config', async () => { const tz$ = new BehaviorSubject('tz1'); diff --git a/src/core/public/integrations/styles/styles_service.test.ts b/src/core/public/integrations/styles/styles_service.test.ts index e413e9cc2f4d7..fc75c6b3e3d06 100644 --- a/src/core/public/integrations/styles/styles_service.test.ts +++ b/src/core/public/integrations/styles/styles_service.test.ts @@ -25,7 +25,7 @@ import { StylesService } from './styles_service'; import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.mock'; describe('StylesService', () => { - const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100)); + const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100)); const getDisableAnimationsTag = () => document.querySelector('style#disableAnimationsCss')!; afterEach(() => getDisableAnimationsTag().remove()); diff --git a/src/core/public/legacy/legacy_service.ts b/src/core/public/legacy/legacy_service.ts index 01837ba6f5940..6213e5e641406 100644 --- a/src/core/public/legacy/legacy_service.ts +++ b/src/core/public/legacy/legacy_service.ts @@ -115,8 +115,8 @@ export class LegacyPlatformService { // Initialize legacy sub urls core.chrome.navLinks .getAll() - .filter(link => link.legacy) - .forEach(navLink => { + .filter((link) => link.legacy) + .forEach((navLink) => { const lastSubUrl = lastSubUrlStorage.getItem(`lastSubUrl:${navLink.baseUrl}`); core.chrome.navLinks.update(navLink.id, { url: lastSubUrl || navLink.url || navLink.baseUrl, diff --git a/src/core/public/notifications/toasts/global_toast_list.test.tsx b/src/core/public/notifications/toasts/global_toast_list.test.tsx index dc2a9dabe791e..1d5d5b86836fd 100644 --- a/src/core/public/notifications/toasts/global_toast_list.test.tsx +++ b/src/core/public/notifications/toasts/global_toast_list.test.tsx @@ -34,7 +34,7 @@ it('renders matching snapshot', () => { it('subscribes to toasts$ on mount and unsubscribes on unmount', () => { const unsubscribeSpy = jest.fn(); - const subscribeSpy = jest.fn(observer => { + const subscribeSpy = jest.fn((observer) => { observer.next([]); return unsubscribeSpy; }); diff --git a/src/core/public/notifications/toasts/global_toast_list.tsx b/src/core/public/notifications/toasts/global_toast_list.tsx index f96a0a6f362bf..cb2d90ff265bf 100644 --- a/src/core/public/notifications/toasts/global_toast_list.tsx +++ b/src/core/public/notifications/toasts/global_toast_list.tsx @@ -47,7 +47,7 @@ export class GlobalToastList extends React.Component { private subscription?: Rx.Subscription; public componentDidMount() { - this.subscription = this.props.toasts$.subscribe(toasts => { + this.subscription = this.props.toasts$.subscribe((toasts) => { this.setState({ toasts }); }); } diff --git a/src/core/public/notifications/toasts/toasts_api.test.ts b/src/core/public/notifications/toasts/toasts_api.test.ts index 7c0ef5576256a..08e1d9711322c 100644 --- a/src/core/public/notifications/toasts/toasts_api.test.ts +++ b/src/core/public/notifications/toasts/toasts_api.test.ts @@ -25,10 +25,7 @@ import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.moc import { i18nServiceMock } from '../../i18n/i18n_service.mock'; async function getCurrentToasts(toasts: ToastsApi) { - return await toasts - .get$() - .pipe(take(1)) - .toPromise(); + return await toasts.get$().pipe(take(1)).toPromise(); } function uiSettingsMock() { diff --git a/src/core/public/notifications/toasts/toasts_api.tsx b/src/core/public/notifications/toasts/toasts_api.tsx index 53717b9c2e174..db65ed76d1cb1 100644 --- a/src/core/public/notifications/toasts/toasts_api.tsx +++ b/src/core/public/notifications/toasts/toasts_api.tsx @@ -150,7 +150,7 @@ export class ToastsApi implements IToasts { public remove(toastOrId: Toast | string) { const toRemove = typeof toastOrId === 'string' ? toastOrId : toastOrId.id; const list = this.toasts$.getValue(); - const listWithoutToast = list.filter(t => t.id !== toRemove); + const listWithoutToast = list.filter((t) => t.id !== toRemove); if (listWithoutToast.length !== list.length) { this.toasts$.next(listWithoutToast); } diff --git a/src/core/public/overlays/banners/banners_list.tsx b/src/core/public/overlays/banners/banners_list.tsx index ee7aa73dc34a6..6503af985f9c8 100644 --- a/src/core/public/overlays/banners/banners_list.tsx +++ b/src/core/public/overlays/banners/banners_list.tsx @@ -47,7 +47,7 @@ export const BannersList: React.FunctionComponent = ({ banners$ }) => { return (
- {banners.map(banner => ( + {banners.map((banner) => ( ))}
diff --git a/src/core/public/overlays/banners/banners_service.test.ts b/src/core/public/overlays/banners/banners_service.test.ts index f11a5d6b88bc2..8e76a18178ff0 100644 --- a/src/core/public/overlays/banners/banners_service.test.ts +++ b/src/core/public/overlays/banners/banners_service.test.ts @@ -31,11 +31,7 @@ describe('OverlayBannersService', () => { }); }); - const currentBanners = () => - service - .get$() - .pipe(take(1)) - .toPromise(); + const currentBanners = () => service.get$().pipe(take(1)).toPromise(); describe('adding banners', () => { test('adds a single banner', async () => { diff --git a/src/core/public/overlays/banners/banners_service.tsx b/src/core/public/overlays/banners/banners_service.tsx index ed59ed819b1c2..c0f76a6deaac7 100644 --- a/src/core/public/overlays/banners/banners_service.tsx +++ b/src/core/public/overlays/banners/banners_service.tsx @@ -112,7 +112,7 @@ export class OverlayBannersService { }, get$() { - return banners$.pipe(map(bannerMap => [...bannerMap.values()])); + return banners$.pipe(map((bannerMap) => [...bannerMap.values()])); }, getComponent() { diff --git a/src/core/public/overlays/banners/user_banner_service.tsx b/src/core/public/overlays/banners/user_banner_service.tsx index e3f4d9dee5b78..643d95a1e3bb4 100644 --- a/src/core/public/overlays/banners/user_banner_service.tsx +++ b/src/core/public/overlays/banners/user_banner_service.tsx @@ -63,7 +63,7 @@ export class UserBannerService { id = banners.replace( id, - el => { + (el) => { ReactDOM.render( { describe('openModal()', () => { it('renders a modal to the DOM', () => { expect(mockReactDomRender).not.toHaveBeenCalled(); - modals.open(container => { + modals.open((container) => { const content = document.createElement('span'); content.textContent = 'Modal content'; container.append(content); @@ -104,7 +104,7 @@ describe('ModalService', () => { describe('openConfirm()', () => { it('renders a mountpoint confirm message', () => { expect(mockReactDomRender).not.toHaveBeenCalled(); - modals.openConfirm(container => { + modals.openConfirm((container) => { const content = document.createElement('span'); content.textContent = 'Modal content'; container.append(content); diff --git a/src/core/public/overlays/overlay.test.mocks.ts b/src/core/public/overlays/overlay.test.mocks.ts index 563f414a0ae99..f382511d445ea 100644 --- a/src/core/public/overlays/overlay.test.mocks.ts +++ b/src/core/public/overlays/overlay.test.mocks.ts @@ -19,7 +19,7 @@ export const mockReactDomRender = jest.fn(); export const mockReactDomUnmount = jest.fn(); -export const mockReactDomCreatePortal = jest.fn().mockImplementation(component => component); +export const mockReactDomCreatePortal = jest.fn().mockImplementation((component) => component); jest.doMock('react-dom', () => ({ render: mockReactDomRender, createPortal: mockReactDomCreatePortal, diff --git a/src/core/public/plugins/plugin.test.ts b/src/core/public/plugins/plugin.test.ts index 8fe745db9554d..3f77161f8c34d 100644 --- a/src/core/public/plugins/plugin.test.ts +++ b/src/core/public/plugins/plugin.test.ts @@ -101,7 +101,7 @@ describe('PluginWrapper', () => { setup: jest.fn(), start: jest.fn(async () => { // Add small delay to ensure startDependencies is not resolved until after the plugin instance's start resolves. - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }), @@ -113,7 +113,7 @@ describe('PluginWrapper', () => { const deps = { otherDep: 'value' }; // Add promise callback prior to calling `start` to ensure calls in `setup` will not resolve before `start` is // called. - const startDependenciesCheck = plugin.startDependencies.then(res => { + const startDependenciesCheck = plugin.startDependencies.then((res) => { startDependenciesResolved = true; expect(res).toEqual([context, deps, pluginStartContract]); }); diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts index c4b3c929415ee..0ac63199498f0 100644 --- a/src/core/public/plugins/plugin_context.ts +++ b/src/core/public/plugins/plugin_context.ts @@ -95,8 +95,8 @@ export function createPluginSetupContext< ): CoreSetup { return { application: { - register: app => deps.application.register(plugin.opaqueId, app), - registerAppUpdater: statusUpdater$ => deps.application.registerAppUpdater(statusUpdater$), + register: (app) => deps.application.register(plugin.opaqueId, app), + registerAppUpdater: (statusUpdater$) => deps.application.registerAppUpdater(statusUpdater$), registerMountContext: (contextName, provider) => deps.application.registerMountContext(plugin.opaqueId, contextName, provider), }, diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts index 6c5ab5fcedcfd..05127e73d0c7a 100644 --- a/src/core/public/plugins/plugins_service.test.ts +++ b/src/core/public/plugins/plugins_service.test.ts @@ -50,7 +50,7 @@ import { contextServiceMock } from '../context/context_service.mock'; export let mockPluginInitializers: Map; mockPluginInitializerProvider.mockImplementation( - pluginName => mockPluginInitializers.get(pluginName)! + (pluginName) => mockPluginInitializers.get(pluginName)! ); let plugins: InjectedPluginMetadata[]; @@ -251,7 +251,7 @@ describe('PluginsService', () => { }); describe('timeout', () => { - const flushPromises = () => new Promise(resolve => setImmediate(resolve)); + const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); beforeAll(() => { jest.useFakeTimers(); }); @@ -263,7 +263,7 @@ describe('PluginsService', () => { mockPluginInitializers.set( 'pluginA', jest.fn(() => ({ - setup: jest.fn(() => new Promise(i => i)), + setup: jest.fn(() => new Promise((i) => i)), start: jest.fn(() => ({ value: 1 })), stop: jest.fn(), })) @@ -344,7 +344,7 @@ describe('PluginsService', () => { 'pluginA', jest.fn(() => ({ setup: jest.fn(() => ({ value: 1 })), - start: jest.fn(() => new Promise(i => i)), + start: jest.fn(() => new Promise((i) => i)), stop: jest.fn(), })) ); diff --git a/src/core/public/plugins/plugins_service.ts b/src/core/public/plugins/plugins_service.ts index 862aa5043ad4b..f9bc40ca52601 100644 --- a/src/core/public/plugins/plugins_service.ts +++ b/src/core/public/plugins/plugins_service.ts @@ -60,14 +60,14 @@ export class PluginsService implements CoreService(plugins.map(p => [p.id, Symbol(p.id)])); + const opaqueIds = new Map(plugins.map((p) => [p.id, Symbol(p.id)])); // Setup dependency map and plugin wrappers plugins.forEach(({ id, plugin, config = {} }) => { // Setup map of dependencies this.pluginDependencies.set(id, [ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(optPlugin => opaqueIds.has(optPlugin)), + ...plugin.optionalPlugins.filter((optPlugin) => opaqueIds.has(optPlugin)), ]); // Construct plugin wrappers, depending on the topological order set by the server. @@ -87,7 +87,7 @@ export class PluginsService implements CoreService [ this.plugins.get(id)!.opaqueId, - deps.map(depId => this.plugins.get(depId)!.opaqueId), + deps.map((depId) => this.plugins.get(depId)!.opaqueId), ]) ); } diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 7958a4f8134d3..cdc113871c447 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -156,8 +156,8 @@ export class SavedObjectsClient { this.bulkGet(queue) .then(({ savedObjects }) => { - queue.forEach(queueItem => { - const foundObject = savedObjects.find(savedObject => { + queue.forEach((queueItem) => { + const foundObject = savedObjects.find((savedObject) => { return savedObject.id === queueItem.id && savedObject.type === queueItem.type; }); @@ -168,8 +168,8 @@ export class SavedObjectsClient { queueItem.resolve(foundObject); }); }) - .catch(err => { - queue.forEach(queueItem => { + .catch((err) => { + queue.forEach((queueItem) => { queueItem.reject(err); }); }); @@ -216,7 +216,7 @@ export class SavedObjectsClient { }), }); - return createRequest.then(resp => this.createSavedObject(resp)); + return createRequest.then((resp) => this.createSavedObject(resp)); }; /** @@ -239,8 +239,8 @@ export class SavedObjectsClient { query, body: JSON.stringify(objects), }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsBatchResponse @@ -301,8 +301,8 @@ export class SavedObjectsClient { method: 'GET', query, }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsFindResponsePublic @@ -350,14 +350,14 @@ export class SavedObjectsClient { */ public bulkGet = (objects: Array<{ id: string; type: string }> = []) => { const path = this.getPath(['_bulk_get']); - const filteredObjects = objects.map(obj => pick(obj, ['id', 'type'])); + const filteredObjects = objects.map((obj) => pick(obj, ['id', 'type'])); const request: ReturnType = this.savedObjectsFetch(path, { method: 'POST', body: JSON.stringify(filteredObjects), }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsBatchResponse @@ -414,7 +414,7 @@ export class SavedObjectsClient { return this.savedObjectsFetch(path, { method: 'PUT', body: JSON.stringify(objects), - }).then(resp => { + }).then((resp) => { resp.saved_objects = resp.saved_objects.map((d: SavedObject) => this.createSavedObject(d)); return renameKeys< PromiseType>, diff --git a/src/core/public/ui_settings/ui_settings_api.test.ts b/src/core/public/ui_settings/ui_settings_api.test.ts index 9a462e0541347..bab7081509d53 100644 --- a/src/core/public/ui_settings/ui_settings_api.test.ts +++ b/src/core/public/ui_settings/ui_settings_api.test.ts @@ -26,7 +26,7 @@ import { setup as httpSetup } from '../../../test_utils/public/http_test_setup'; import { UiSettingsApi } from './ui_settings_api'; function setup() { - const { http } = httpSetup(injectedMetadata => { + const { http } = httpSetup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue('/foo/bar'); }); @@ -181,10 +181,7 @@ describe('#getLoadingCount$()', () => { const { uiSettingsApi } = setup(); const done$ = new Rx.Subject(); - const promise = uiSettingsApi - .getLoadingCount$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise(); await uiSettingsApi.batchSet('foo', 'bar'); done$.next(); @@ -209,10 +206,7 @@ describe('#getLoadingCount$()', () => { const { uiSettingsApi } = setup(); const done$ = new Rx.Subject(); - const promise = uiSettingsApi - .getLoadingCount$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise(); await uiSettingsApi.batchSet('foo', 'bar'); await expect(uiSettingsApi.batchSet('foo', 'bar')).rejects.toThrowError(); @@ -230,14 +224,8 @@ describe('#stop', () => { const { uiSettingsApi } = setup(); const promise = Promise.all([ - uiSettingsApi - .getLoadingCount$() - .pipe(toArray()) - .toPromise(), - uiSettingsApi - .getLoadingCount$() - .pipe(toArray()) - .toPromise(), + uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(), + uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(), ]); const batchSetPromise = uiSettingsApi.batchSet('foo', 'bar'); diff --git a/src/core/public/ui_settings/ui_settings_client.test.ts b/src/core/public/ui_settings/ui_settings_client.test.ts index f394036e3e046..3b67efb740e7d 100644 --- a/src/core/public/ui_settings/ui_settings_client.test.ts +++ b/src/core/public/ui_settings/ui_settings_client.test.ts @@ -88,20 +88,14 @@ describe('#get', () => { describe('#get$', () => { it('emits the current value when called', async () => { const { client } = setup(); - const values = await client - .get$('dateFormat') - .pipe(take(1), toArray()) - .toPromise(); + const values = await client.get$('dateFormat').pipe(take(1), toArray()).toPromise(); expect(values).toEqual(['Browser']); }); it('emits an error notification if the key is unknown', async () => { const { client } = setup(); - const values = await client - .get$('unknown key') - .pipe(materialize()) - .toPromise(); + const values = await client.get$('unknown key').pipe(materialize()).toPromise(); expect(values).toMatchInlineSnapshot(` Notification { @@ -124,10 +118,7 @@ You can use \`IUiSettingsClient.get("unknown key", defaultValue)\`, which will j client.set('dateFormat', 'new format'); }, 10); - const values = await client - .get$('dateFormat') - .pipe(take(2), toArray()) - .toPromise(); + const values = await client.get$('dateFormat').pipe(take(2), toArray()).toPromise(); expect(values).toEqual(['Browser', 'new format']); }); diff --git a/src/core/public/ui_settings/ui_settings_client.ts b/src/core/public/ui_settings/ui_settings_client.ts index f5596b1bc34fc..2a7c3c2fab2f3 100644 --- a/src/core/public/ui_settings/ui_settings_client.ts +++ b/src/core/public/ui_settings/ui_settings_client.ts @@ -97,7 +97,7 @@ You can use \`IUiSettingsClient.get("${key}", defaultValue)\`, which will just r return concat( defer(() => of(this.get(key, defaultOverride))), this.update$.pipe( - filter(update => update.key === key), + filter((update) => update.key === key), map(() => this.get(key, defaultOverride)) ) ); diff --git a/src/core/public/ui_settings/ui_settings_service.test.ts b/src/core/public/ui_settings/ui_settings_service.test.ts index 2747a78d93fa6..4c688d5b7b2c1 100644 --- a/src/core/public/ui_settings/ui_settings_service.test.ts +++ b/src/core/public/ui_settings/ui_settings_service.test.ts @@ -38,7 +38,7 @@ describe('#stop', () => { it('stops the uiSettingsClient and uiSettingsApi', async () => { const service = new UiSettingsService(); let loadingCount$: Rx.Observable; - defaultDeps.http.addLoadingCountSource.mockImplementation(obs$ => (loadingCount$ = obs$)); + defaultDeps.http.addLoadingCountSource.mockImplementation((obs$) => (loadingCount$ = obs$)); const client = service.setup(defaultDeps); service.stop(); diff --git a/src/core/public/utils/share_weak_replay.test.ts b/src/core/public/utils/share_weak_replay.test.ts index 6eaa140e5afad..beac851aa689c 100644 --- a/src/core/public/utils/share_weak_replay.test.ts +++ b/src/core/public/utils/share_weak_replay.test.ts @@ -38,7 +38,7 @@ function counter({ async = true }: { async?: boolean } = {}) { completedCounts += 1; } - return new Rx.Observable(subscriber => { + return new Rx.Observable((subscriber) => { if (!async) { sendCount(subscriber); return; @@ -53,7 +53,7 @@ async function record(observable: Rx.Observable) { return observable .pipe( materialize(), - map(n => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')), + map((n) => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')), toArray() ) .toPromise(); diff --git a/src/core/public/utils/share_weak_replay.ts b/src/core/public/utils/share_weak_replay.ts index 74ea6cc536888..5ed6f76c5a05a 100644 --- a/src/core/public/utils/share_weak_replay.ts +++ b/src/core/public/utils/share_weak_replay.ts @@ -39,7 +39,7 @@ export function shareWeakReplay(bufferSize?: number): Rx.MonoTypeOperatorFunc let subject: Rx.ReplaySubject | undefined; const stop$ = new Rx.Subject(); - return new Rx.Observable(observer => { + return new Rx.Observable((observer) => { if (!subject) { subject = new Rx.ReplaySubject(bufferSize); } diff --git a/src/core/server/bootstrap.ts b/src/core/server/bootstrap.ts index dff0c00a4625e..5dbe5a0b4f955 100644 --- a/src/core/server/bootstrap.ts +++ b/src/core/server/bootstrap.ts @@ -71,7 +71,7 @@ export async function bootstrap({ // This is only used by the LogRotator service // in order to be able to reload the log configuration // under the cluster mode - process.on('message', msg => { + process.on('message', (msg) => { if (!msg || msg.reloadLoggingConfig !== true) { return; } diff --git a/src/core/server/capabilities/capabilities_service.ts b/src/core/server/capabilities/capabilities_service.ts index d3d6b507da523..f0be9743d4d60 100644 --- a/src/core/server/capabilities/capabilities_service.ts +++ b/src/core/server/capabilities/capabilities_service.ts @@ -127,7 +127,7 @@ export class CapabilitiesService { () => mergeCapabilities( defaultCapabilities, - ...this.capabilitiesProviders.map(provider => provider()) + ...this.capabilitiesProviders.map((provider) => provider()) ), () => this.capabilitiesSwitchers ); @@ -150,7 +150,7 @@ export class CapabilitiesService { public start(): CapabilitiesStart { return { - resolveCapabilities: request => this.resolveCapabilities(request, []), + resolveCapabilities: (request) => this.resolveCapabilities(request, []), }; } } diff --git a/src/core/server/capabilities/resolve_capabilities.ts b/src/core/server/capabilities/resolve_capabilities.ts index dcb93bdca5f16..1be504d4bc314 100644 --- a/src/core/server/capabilities/resolve_capabilities.ts +++ b/src/core/server/capabilities/resolve_capabilities.ts @@ -64,7 +64,7 @@ function recursiveApplyChanges< TSource extends Record >(destination: TDestination, source: TSource): TDestination { return Object.keys(destination) - .map(key => { + .map((key) => { const orig = destination[key]; const changed = source[key]; if (changed == null) { diff --git a/src/core/server/config/config.ts b/src/core/server/config/config.ts index b1a6a8cc525bf..a4026b1d88ac3 100644 --- a/src/core/server/config/config.ts +++ b/src/core/server/config/config.ts @@ -34,7 +34,7 @@ export function isConfigPath(value: unknown): value is ConfigPath { return true; } - return Array.isArray(value) && value.every(segment => typeof segment === 'string'); + return Array.isArray(value) && value.every((segment) => typeof segment === 'string'); } /** diff --git a/src/core/server/config/config_service.test.ts b/src/core/server/config/config_service.test.ts index 773a444dea948..5f28fca1371b0 100644 --- a/src/core/server/config/config_service.test.ts +++ b/src/core/server/config/config_service.test.ts @@ -62,10 +62,10 @@ test('throws if config at path does not match schema', async () => { .atPath('key') .pipe(take(1)) .subscribe( - value => { + (value) => { valuesReceived.push(value); }, - error => { + (error) => { valuesReceived.push(error); } ); @@ -86,10 +86,10 @@ test('re-validate config when updated', async () => { const valuesReceived: any[] = []; await configService.atPath('key').subscribe( - value => { + (value) => { valuesReceived.push(value); }, - error => { + (error) => { valuesReceived.push(error); } ); @@ -133,7 +133,7 @@ test("does not push new configs when reloading if config at path hasn't changed" await configService.setSchema('key', schema.string()); const valuesReceived: any[] = []; - configService.atPath('key').subscribe(value => { + configService.atPath('key').subscribe((value) => { valuesReceived.push(value); }); @@ -150,7 +150,7 @@ test('pushes new config when reloading and config at path has changed', async () await configService.setSchema('key', schema.string()); const valuesReceived: any[] = []; - configService.atPath('key').subscribe(value => { + configService.atPath('key').subscribe((value) => { valuesReceived.push(value); }); diff --git a/src/core/server/config/config_service.ts b/src/core/server/config/config_service.ts index 61630f43bffb5..bceba420bb6ce 100644 --- a/src/core/server/config/config_service.ts +++ b/src/core/server/config/config_service.ts @@ -89,7 +89,7 @@ export class ConfigService { const flatPath = pathToString(path); this.deprecations.next([ ...this.deprecations.value, - ...provider(configDeprecationFactory).map(deprecation => ({ + ...provider(configDeprecationFactory).map((deprecation) => ({ deprecation, path: flatPath, })), @@ -104,9 +104,7 @@ export class ConfigService { public async validate() { const namespaces = [...this.schemas.keys()]; for (let i = 0; i < namespaces.length; i++) { - await this.validateConfigAtPath(namespaces[i]) - .pipe(first()) - .toPromise(); + await this.validateConfigAtPath(namespaces[i]).pipe(first()).toPromise(); } await this.logDeprecation(); @@ -138,7 +136,7 @@ export class ConfigService { */ public optionalAtPath(path: ConfigPath) { return this.getDistinctConfig(path).pipe( - map(config => { + map((config) => { if (config === undefined) return undefined; return this.validateAtPath(path, config) as TSchema; }) @@ -149,9 +147,7 @@ export class ConfigService { const namespace = pathToString(path); const validatedConfig = this.schemas.has(namespace) - ? await this.atPath<{ enabled?: boolean }>(path) - .pipe(first()) - .toPromise() + ? await this.atPath<{ enabled?: boolean }>(path).pipe(first()).toPromise() : undefined; const enabledPath = createPluginEnabledPath(path); @@ -186,26 +182,23 @@ export class ConfigService { const config = await this.config$.pipe(first()).toPromise(); const handledPaths = this.handledPaths.map(pathToString); - return config.getFlattenedPaths().filter(path => !isPathHandled(path, handledPaths)); + return config.getFlattenedPaths().filter((path) => !isPathHandled(path, handledPaths)); } public async getUsedPaths() { const config = await this.config$.pipe(first()).toPromise(); const handledPaths = this.handledPaths.map(pathToString); - return config.getFlattenedPaths().filter(path => isPathHandled(path, handledPaths)); + return config.getFlattenedPaths().filter((path) => isPathHandled(path, handledPaths)); } private async logDeprecation() { - const rawConfig = await this.rawConfigProvider - .getConfig$() - .pipe(take(1)) - .toPromise(); + const rawConfig = await this.rawConfigProvider.getConfig$().pipe(take(1)).toPromise(); const deprecations = await this.deprecations.pipe(take(1)).toPromise(); const deprecationMessages: string[] = []; const logger = (msg: string) => deprecationMessages.push(msg); applyDeprecations(rawConfig, deprecations, logger); - deprecationMessages.forEach(msg => { + deprecationMessages.forEach((msg) => { this.deprecationLog.warn(msg); }); } @@ -228,14 +221,14 @@ export class ConfigService { } private validateConfigAtPath(path: ConfigPath) { - return this.getDistinctConfig(path).pipe(map(config => this.validateAtPath(path, config))); + return this.getDistinctConfig(path).pipe(map((config) => this.validateAtPath(path, config))); } private getDistinctConfig(path: ConfigPath) { this.markAsHandled(path); return this.config$.pipe( - map(config => config.get(path)), + map((config) => config.get(path)), distinctUntilChanged(isEqual) ); } @@ -260,4 +253,4 @@ const pathToString = (path: ConfigPath) => (Array.isArray(path) ? path.join('.') * handled paths. */ const isPathHandled = (path: string, handledPaths: string[]) => - handledPaths.some(handledPath => hasConfigPathIntersection(path, handledPath)); + handledPaths.some((handledPath) => hasConfigPathIntersection(path, handledPath)); diff --git a/src/core/server/config/deprecation/apply_deprecations.test.ts b/src/core/server/config/deprecation/apply_deprecations.test.ts index 25cae80d8b5cb..d7cc85add4e76 100644 --- a/src/core/server/config/deprecation/apply_deprecations.test.ts +++ b/src/core/server/config/deprecation/apply_deprecations.test.ts @@ -36,7 +36,7 @@ describe('applyDeprecations', () => { const handlerC = jest.fn(); applyDeprecations( {}, - [handlerA, handlerB, handlerC].map(h => wrapHandler(h)) + [handlerA, handlerB, handlerC].map((h) => wrapHandler(h)) ); expect(handlerA).toHaveBeenCalledTimes(1); expect(handlerB).toHaveBeenCalledTimes(1); @@ -49,7 +49,7 @@ describe('applyDeprecations', () => { const alteredConfig = { foo: 'bar' }; const handlerA = jest.fn().mockReturnValue(alteredConfig); - const handlerB = jest.fn().mockImplementation(conf => conf); + const handlerB = jest.fn().mockImplementation((conf) => conf); applyDeprecations( initialConfig, diff --git a/src/core/server/config/deprecation/core_deprecations.test.ts b/src/core/server/config/deprecation/core_deprecations.test.ts index a91e128f62d2d..ebdb6f1c88b16 100644 --- a/src/core/server/config/deprecation/core_deprecations.test.ts +++ b/src/core/server/config/deprecation/core_deprecations.test.ts @@ -28,11 +28,11 @@ const applyCoreDeprecations = (settings: Record = {}) => { const deprecationMessages: string[] = []; const migrated = applyDeprecations( settings, - deprecations.map(deprecation => ({ + deprecations.map((deprecation) => ({ deprecation, path: '', })), - msg => deprecationMessages.push(msg) + (msg) => deprecationMessages.push(msg) ); return { messages: deprecationMessages, diff --git a/src/core/server/config/deprecation/core_deprecations.ts b/src/core/server/config/deprecation/core_deprecations.ts index 9e098c06ba155..483534e0c145b 100644 --- a/src/core/server/config/deprecation/core_deprecations.ts +++ b/src/core/server/config/deprecation/core_deprecations.ts @@ -72,26 +72,26 @@ const cspRulesDeprecation: ConfigDeprecation = (settings, fromPath, log) => { const rules: string[] = get(settings, 'csp.rules'); if (rules) { const parsed = new Map( - rules.map(ruleStr => { + rules.map((ruleStr) => { const parts = ruleStr.split(/\s+/); return [parts[0], parts.slice(1)]; }) ); settings.csp.rules = [...parsed].map(([policy, sourceList]) => { - if (sourceList.find(source => source.includes(NONCE_STRING))) { + if (sourceList.find((source) => source.includes(NONCE_STRING))) { log(`csp.rules no longer supports the {nonce} syntax. Replacing with 'self' in ${policy}`); - sourceList = sourceList.filter(source => !source.includes(NONCE_STRING)); + sourceList = sourceList.filter((source) => !source.includes(NONCE_STRING)); // Add 'self' if not present - if (!sourceList.find(source => source.includes(SELF_STRING))) { + if (!sourceList.find((source) => source.includes(SELF_STRING))) { sourceList.push(SELF_STRING); } } if ( SELF_POLICIES.includes(policy) && - !sourceList.find(source => source.includes(SELF_STRING)) + !sourceList.find((source) => source.includes(SELF_STRING)) ) { log(`csp.rules must contain the 'self' source. Automatically adding to ${policy}.`); sourceList.push(SELF_STRING); diff --git a/src/core/server/config/deprecation/deprecation_factory.test.ts b/src/core/server/config/deprecation/deprecation_factory.test.ts index 2595fdd923dd5..3910ee3235caf 100644 --- a/src/core/server/config/deprecation/deprecation_factory.test.ts +++ b/src/core/server/config/deprecation/deprecation_factory.test.ts @@ -24,7 +24,7 @@ describe('DeprecationFactory', () => { const { rename, unused, renameFromRoot, unusedFromRoot } = configDeprecationFactory; let deprecationMessages: string[]; - const logger: ConfigDeprecationLogger = msg => deprecationMessages.push(msg); + const logger: ConfigDeprecationLogger = (msg) => deprecationMessages.push(msg); beforeEach(() => { deprecationMessages = []; diff --git a/src/core/server/config/ensure_deep_object.ts b/src/core/server/config/ensure_deep_object.ts index 58865d13c1afa..6eaaef983355c 100644 --- a/src/core/server/config/ensure_deep_object.ts +++ b/src/core/server/config/ensure_deep_object.ts @@ -31,7 +31,7 @@ export function ensureDeepObject(obj: any): any { } if (Array.isArray(obj)) { - return obj.map(item => ensureDeepObject(item)); + return obj.map((item) => ensureDeepObject(item)); } return Object.keys(obj).reduce((fullObject, propertyKey) => { diff --git a/src/core/server/config/integration_tests/config_deprecation.test.ts b/src/core/server/config/integration_tests/config_deprecation.test.ts index 5bc3887f05f93..3523b074ea5b4 100644 --- a/src/core/server/config/integration_tests/config_deprecation.test.ts +++ b/src/core/server/config/integration_tests/config_deprecation.test.ts @@ -36,7 +36,7 @@ describe('configuration deprecations', () => { await root.setup(); const logs = loggingServiceMock.collect(mockLoggingService); - const warnings = logs.warn.flatMap(i => i); + const warnings = logs.warn.flatMap((i) => i); expect(warnings).not.toContain( '"optimize.lazy" is deprecated and has been replaced by "optimize.watch"' ); @@ -56,7 +56,7 @@ describe('configuration deprecations', () => { await root.setup(); const logs = loggingServiceMock.collect(mockLoggingService); - const warnings = logs.warn.flatMap(i => i); + const warnings = logs.warn.flatMap((i) => i); expect(warnings).toContain( '"optimize.lazy" is deprecated and has been replaced by "optimize.watch"' ); diff --git a/src/core/server/config/raw_config_service.test.ts b/src/core/server/config/raw_config_service.test.ts index f02c31d4659ca..8846ea3847f79 100644 --- a/src/core/server/config/raw_config_service.test.ts +++ b/src/core/server/config/raw_config_service.test.ts @@ -83,10 +83,7 @@ test('returns config at path as observable', async () => { configService.loadConfig(); - const exampleConfig = await configService - .getConfig$() - .pipe(first()) - .toPromise(); + const exampleConfig = await configService.getConfig$().pipe(first()).toPromise(); expect(exampleConfig.key).toEqual('value'); expect(Object.keys(exampleConfig)).toEqual(['key']); @@ -100,7 +97,7 @@ test("pushes new configs when reloading even if config at path hasn't changed", configService.loadConfig(); const valuesReceived: any[] = []; - configService.getConfig$().subscribe(config => { + configService.getConfig$().subscribe((config) => { valuesReceived.push(config); }); @@ -129,7 +126,7 @@ test('pushes new config when reloading and config at path has changed', async () configService.loadConfig(); const valuesReceived: any[] = []; - configService.getConfig$().subscribe(config => { + configService.getConfig$().subscribe((config) => { valuesReceived.push(config); }); @@ -145,7 +142,7 @@ test('pushes new config when reloading and config at path has changed', async () expect(Object.keys(valuesReceived[1])).toEqual(['key']); }); -test('completes config observables when stopped', done => { +test('completes config observables when stopped', (done) => { expect.assertions(0); mockGetConfigFromFiles.mockImplementation(() => ({ key: 'value' })); diff --git a/src/core/server/config/raw_config_service.ts b/src/core/server/config/raw_config_service.ts index 728d793f494a9..257ec612f3249 100644 --- a/src/core/server/config/raw_config_service.ts +++ b/src/core/server/config/raw_config_service.ts @@ -41,10 +41,10 @@ export class RawConfigService { constructor( public readonly configFiles: readonly string[], - configAdapter: RawConfigAdapter = rawConfig => rawConfig + configAdapter: RawConfigAdapter = (rawConfig) => rawConfig ) { this.config$ = this.rawConfigFromFile$.pipe( - map(rawConfig => { + map((rawConfig) => { if (isPlainObject(rawConfig)) { // TODO Make config consistent, e.g. handle dots in keys return configAdapter(cloneDeep(rawConfig)); diff --git a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts index 2c7efe075152b..3284be5ba4750 100644 --- a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts +++ b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts @@ -44,7 +44,7 @@ describe('default route provider', () => { await root.shutdown(); }); - it('redirects to the configured default route respecting basePath', async function() { + it('redirects to the configured default route respecting basePath', async function () { const { status, header } = await kbnTestServer.request.get(root, '/'); expect(status).toEqual(302); @@ -53,7 +53,7 @@ describe('default route provider', () => { }); }); - it('ignores invalid values', async function() { + it('ignores invalid values', async function () { const invalidRoutes = [ 'http://not-your-kibana.com', '///example.com', @@ -75,7 +75,7 @@ describe('default route provider', () => { }); }); - it('consumes valid values', async function() { + it('consumes valid values', async function () { await kbnTestServer.request .post(root, '/api/kibana/settings/defaultRoute') .send({ value: '/valid' }) diff --git a/src/core/server/core_app/integration_tests/static_assets.test.ts b/src/core/server/core_app/integration_tests/static_assets.test.ts index aad2510ef8c0e..23125cb3a6704 100644 --- a/src/core/server/core_app/integration_tests/static_assets.test.ts +++ b/src/core/server/core_app/integration_tests/static_assets.test.ts @@ -19,17 +19,17 @@ import * as kbnTestServer from '../../../../test_utils/kbn_server'; import { Root } from '../../root'; -describe('Platform assets', function() { +describe('Platform assets', function () { let root: Root; - beforeAll(async function() { + beforeAll(async function () { root = kbnTestServer.createRoot(); await root.setup(); await root.start(); }); - afterAll(async function() { + afterAll(async function () { await root.shutdown(); }); @@ -37,15 +37,15 @@ describe('Platform assets', function() { await kbnTestServer.request.get(root, '/ui/favicons/favicon.ico').expect(200); }); - it('returns 404 if not found', async function() { + it('returns 404 if not found', async function () { await kbnTestServer.request.get(root, '/ui/favicons/not-a-favicon.ico').expect(404); }); - it('does not expose folder content', async function() { + it('does not expose folder content', async function () { await kbnTestServer.request.get(root, '/ui/favicons/').expect(403); }); - it('does not allow file tree traversing', async function() { + it('does not allow file tree traversing', async function () { await kbnTestServer.request.get(root, '/ui/../../../../../README.md').expect(404); }); }); diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.ts b/src/core/server/elasticsearch/elasticsearch_config.test.ts index cb4501a51e849..ccd5fd0c7a571 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.test.ts @@ -35,11 +35,11 @@ const applyElasticsearchDeprecations = (settings: Record = {}) => { _config[CONFIG_PATH] = settings; const migrated = applyDeprecations( _config, - deprecations.map(deprecation => ({ + deprecations.map((deprecation) => ({ deprecation, path: CONFIG_PATH, })), - msg => deprecationMessages.push(msg) + (msg) => deprecationMessages.push(msg) ); return { messages: deprecationMessages, diff --git a/src/core/server/elasticsearch/elasticsearch_config.ts b/src/core/server/elasticsearch/elasticsearch_config.ts index c87c94bcd0b6a..cac8c75a04486 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.ts @@ -51,7 +51,7 @@ export const configSchema = schema.object({ schema.contextRef('dist'), false, schema.string({ - validate: rawConfig => { + validate: (rawConfig) => { if (rawConfig === 'elastic') { return ( 'value of "elastic" is forbidden. This is a superuser account that can obfuscate ' + @@ -96,7 +96,7 @@ export const configSchema = schema.object({ alwaysPresentCertificate: schema.boolean({ defaultValue: false }), }, { - validate: rawConfig => { + validate: (rawConfig) => { if (rawConfig.key && rawConfig.keystore.path) { return 'cannot use [key] when [keystore.path] is specified'; } @@ -112,7 +112,7 @@ export const configSchema = schema.object({ schema.contextRef('dev'), false, schema.boolean({ - validate: rawValue => { + validate: (rawValue) => { if (rawValue === true) { return '"ignoreVersionMismatch" can only be set to true in development mode'; } diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 2667859f303d4..26144eaaa4afa 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -34,7 +34,7 @@ import { elasticsearchServiceMock } from './elasticsearch_service.mock'; import { duration } from 'moment'; const delay = async (durationMs: number) => - await new Promise(resolve => setTimeout(resolve, durationMs)); + await new Promise((resolve) => setTimeout(resolve, durationMs)); let elasticsearchService: ElasticsearchService; const configService = configServiceMock.create(); @@ -217,7 +217,7 @@ describe('#setup', () => { }); }); - it('esNodeVersionCompatibility$ only starts polling when subscribed to', async done => { + it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient(); MockClusterClient.mockImplementationOnce( @@ -236,7 +236,7 @@ describe('#setup', () => { }); }); - it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async done => { + it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient(); MockClusterClient.mockImplementationOnce( @@ -272,7 +272,7 @@ describe('#stop', () => { expect(mockDataClusterClientInstance.close).toHaveBeenCalledTimes(1); }); - it('stops pollEsNodeVersions even if there are active subscriptions', async done => { + it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => { expect.assertions(2); const mockAdminClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 18725f04a05b5..ab9c9e11fedc8 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -77,7 +77,7 @@ export class ElasticsearchService this.log = coreContext.logger.get('elasticsearch-service'); this.config$ = coreContext.configService .atPath('elasticsearch') - .pipe(map(rawConfig => new ElasticsearchConfig(rawConfig))); + .pipe(map((rawConfig) => new ElasticsearchConfig(rawConfig))); } public async setup(deps: SetupDeps): Promise { @@ -93,8 +93,8 @@ export class ElasticsearchService return true; }), switchMap( - config => - new Observable(subscriber => { + (config) => + new Observable((subscriber) => { this.log.debug(`Creating elasticsearch clients`); const coreClients = { @@ -120,8 +120,8 @@ export class ElasticsearchService const config = await this.config$.pipe(first()).toPromise(); - const adminClient$ = clients$.pipe(map(clients => clients.adminClient)); - const dataClient$ = clients$.pipe(map(clients => clients.dataClient)); + const adminClient$ = clients$.pipe(map((clients) => clients.adminClient)); + const dataClient$ = clients$.pipe(map((clients) => clients.dataClient)); this.adminClient = { async callAsInternalUser( @@ -189,7 +189,7 @@ export class ElasticsearchService }; return { - legacy: { config$: clients$.pipe(map(clients => clients.config)) }, + legacy: { config$: clients$.pipe(map((clients) => clients.config)) }, esNodesCompatibility$, adminClient: this.adminClient, dataClient, diff --git a/src/core/server/elasticsearch/retry_call_cluster.test.ts b/src/core/server/elasticsearch/retry_call_cluster.test.ts index 4f391f0aba34b..8be138e6752d2 100644 --- a/src/core/server/elasticsearch/retry_call_cluster.test.ts +++ b/src/core/server/elasticsearch/retry_call_cluster.test.ts @@ -75,7 +75,7 @@ describe('migrationsRetryCallCluster', () => { loggingServiceMock.clear(mockLogger); }); - errors.forEach(errorName => { + errors.forEach((errorName) => { it('retries ES API calls that rejects with ' + errorName, () => { expect.assertions(1); const callEsApi = jest.fn(); diff --git a/src/core/server/elasticsearch/retry_call_cluster.ts b/src/core/server/elasticsearch/retry_call_cluster.ts index 901b801159cb6..aa3e39d948593 100644 --- a/src/core/server/elasticsearch/retry_call_cluster.ts +++ b/src/core/server/elasticsearch/retry_call_cluster.ts @@ -47,7 +47,7 @@ export function migrationsRetryCallCluster( return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => { return defer(() => apiCaller(endpoint, clientParams, options)) .pipe( - retryWhen(error$ => + retryWhen((error$) => error$.pipe( concatMap((error, i) => { if (!previousErrors.includes(error.message)) { @@ -90,7 +90,7 @@ export function retryCallCluster(apiCaller: APICaller) { return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => { return defer(() => apiCaller(endpoint, clientParams, options)) .pipe( - retryWhen(errors => + retryWhen((errors) => errors.pipe( concatMap((error, i) => iif( diff --git a/src/core/server/elasticsearch/scoped_cluster_client.ts b/src/core/server/elasticsearch/scoped_cluster_client.ts index 920d236935261..4b64bfba15190 100644 --- a/src/core/server/elasticsearch/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/scoped_cluster_client.ts @@ -89,7 +89,7 @@ export class ScopedClusterClient implements IScopedClusterClient { const customHeaders: any = clientParams.headers; if (isObject(customHeaders)) { const duplicates = intersection(Object.keys(defaultHeaders), Object.keys(customHeaders)); - duplicates.forEach(duplicate => { + duplicates.forEach((duplicate) => { if (defaultHeaders[duplicate] !== (customHeaders as any)[duplicate]) { throw Error(`Cannot override default header ${duplicate}.`); } diff --git a/src/core/server/elasticsearch/status.test.ts b/src/core/server/elasticsearch/status.test.ts index dd5fb04bfd1c6..ef7ca7cd04608 100644 --- a/src/core/server/elasticsearch/status.test.ts +++ b/src/core/server/elasticsearch/status.test.ts @@ -38,11 +38,7 @@ const nodeInfo = { describe('calculateStatus', () => { it('starts in unavailable', async () => { - expect( - await calculateStatus$(new Subject()) - .pipe(take(1)) - .toPromise() - ).toEqual({ + expect(await calculateStatus$(new Subject()).pipe(take(1)).toPromise()).toEqual({ level: ServiceStatusLevels.unavailable, summary: 'Waiting for Elasticsearch', meta: { @@ -123,7 +119,7 @@ describe('calculateStatus', () => { const nodeCompat$ = new Subject(); const statusUpdates: ServiceStatus[] = []; - const subscription = calculateStatus$(nodeCompat$).subscribe(status => + const subscription = calculateStatus$(nodeCompat$).subscribe((status) => statusUpdates.push(status) ); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts index 4989c4a31295c..a4cf0ffd58088 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts @@ -30,7 +30,7 @@ const KIBANA_VERSION = '5.1.0'; function createNodes(...versions: string[]): NodesInfo { const nodes = {} as any; versions - .map(version => { + .map((version) => { return { version, http: { @@ -121,7 +121,7 @@ describe('pollEsNodesVersion', () => { callWithInternalUser.mockClear(); }); - it('returns iscCompatible=false and keeps polling when a poll request throws', done => { + it('returns iscCompatible=false and keeps polling when a poll request throws', (done) => { expect.assertions(3); const expectedCompatibilityResults = [false, false, true]; jest.clearAllMocks(); @@ -137,7 +137,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(3)) .subscribe({ - next: result => { + next: (result) => { expect(result.isCompatible).toBe(expectedCompatibilityResults.shift()); }, complete: done, @@ -145,7 +145,7 @@ describe('pollEsNodesVersion', () => { }); }); - it('returns compatibility results', done => { + it('returns compatibility results', (done) => { expect.assertions(1); const nodes = createNodes('5.1.0', '5.2.0', '5.0.0'); callWithInternalUser.mockResolvedValueOnce(nodes); @@ -158,7 +158,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(1)) .subscribe({ - next: result => { + next: (result) => { expect(result).toEqual(mapNodesVersionCompatibility(nodes, KIBANA_VERSION, false)); }, complete: done, @@ -166,7 +166,7 @@ describe('pollEsNodesVersion', () => { }); }); - it('only emits if the node versions changed since the previous poll', done => { + it('only emits if the node versions changed since the previous poll', (done) => { expect.assertions(4); callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering @@ -184,7 +184,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(4)) .subscribe({ - next: result => expect(result).toBeDefined(), + next: (result) => expect(result).toBeDefined(), complete: done, error: done, }); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 7bd6331978d1d..776298e5869a0 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -83,32 +83,32 @@ export function mapNodesVersionCompatibility( } const nodes = Object.keys(nodesInfo.nodes) .sort() // Sorting ensures a stable node ordering for comparison - .map(key => nodesInfo.nodes[key]) - .map(node => Object.assign({}, node, { name: getHumanizedNodeName(node) })); + .map((key) => nodesInfo.nodes[key]) + .map((node) => Object.assign({}, node, { name: getHumanizedNodeName(node) })); // Aggregate incompatible ES nodes. const incompatibleNodes = nodes.filter( - node => !esVersionCompatibleWithKibana(node.version, kibanaVersion) + (node) => !esVersionCompatibleWithKibana(node.version, kibanaVersion) ); // Aggregate ES nodes which should prompt a Kibana upgrade. It's acceptable // if ES and Kibana versions are not the same as long as they are not // incompatible, but we should warn about it. // Ignore version qualifiers https://github.com/elastic/elasticsearch/issues/36859 - const warningNodes = nodes.filter(node => !esVersionEqualsKibana(node.version, kibanaVersion)); + const warningNodes = nodes.filter((node) => !esVersionEqualsKibana(node.version, kibanaVersion)); // Note: If incompatible and warning nodes are present `message` only contains // an incompatibility notice. let message; if (incompatibleNodes.length > 0) { - const incompatibleNodeNames = incompatibleNodes.map(node => node.name).join(', '); + const incompatibleNodeNames = incompatibleNodes.map((node) => node.name).join(', '); if (ignoreVersionMismatch) { message = `Ignoring version incompatibility between Kibana v${kibanaVersion} and the following Elasticsearch nodes: ${incompatibleNodeNames}`; } else { message = `This version of Kibana (v${kibanaVersion}) is incompatible with the following Elasticsearch nodes in your cluster: ${incompatibleNodeNames}`; } } else if (warningNodes.length > 0) { - const warningNodeNames = warningNodes.map(node => node.name).join(', '); + const warningNodeNames = warningNodes.map((node) => node.name).join(', '); message = `You're running Kibana ${kibanaVersion} with some different versions of ` + 'Elasticsearch. Update Kibana or Elasticsearch to the same ' + @@ -151,7 +151,7 @@ export const pollEsNodesVersion = ({ filterPath: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], }) ).pipe( - catchError(_err => { + catchError((_err) => { return of({ nodes: {} }); }) ); diff --git a/src/core/server/http/auth_headers_storage.ts b/src/core/server/http/auth_headers_storage.ts index 469e194a61fed..f532afc8b4bc7 100644 --- a/src/core/server/http/auth_headers_storage.ts +++ b/src/core/server/http/auth_headers_storage.ts @@ -33,7 +33,7 @@ export class AuthHeadersStorage { public set = (request: KibanaRequest | LegacyRequest, headers: AuthHeaders) => { this.authHeadersCache.set(ensureRawRequest(request), headers); }; - public get: GetAuthHeaders = request => { + public get: GetAuthHeaders = (request) => { return this.authHeadersCache.get(ensureRawRequest(request)); }; } diff --git a/src/core/server/http/auth_state_storage.ts b/src/core/server/http/auth_state_storage.ts index 10c8ccca32401..1172f06d06ab3 100644 --- a/src/core/server/http/auth_state_storage.ts +++ b/src/core/server/http/auth_state_storage.ts @@ -71,7 +71,7 @@ export class AuthStateStorage { return { status, state }; }; - public isAuthenticated: IsAuthenticated = request => { + public isAuthenticated: IsAuthenticated = (request) => { return this.get(request).status === AuthStatus.authenticated; }; } diff --git a/src/core/server/http/base_path_proxy_server.ts b/src/core/server/http/base_path_proxy_server.ts index acefbd00ae2be..ffbdabadd03f7 100644 --- a/src/core/server/http/base_path_proxy_server.ts +++ b/src/core/server/http/base_path_proxy_server.ts @@ -180,9 +180,7 @@ export class BasePathProxyServer { // condition is met (e.g. until target listener is ready). async (request, responseToolkit) => { apm.setTransactionName(`${request.method.toUpperCase()} /{basePath}/{kbnPath*}`); - await delayUntil() - .pipe(take(1)) - .toPromise(); + await delayUntil().pipe(take(1)).toPromise(); return responseToolkit.continue; }, ], @@ -216,9 +214,7 @@ export class BasePathProxyServer { // Before we proxy request to a target port we may want to wait until some // condition is met (e.g. until target listener is ready). async (request, responseToolkit) => { - await delayUntil() - .pipe(take(1)) - .toPromise(); + await delayUntil().pipe(take(1)).toPromise(); return responseToolkit.continue; }, ], diff --git a/src/core/server/http/base_path_service.ts b/src/core/server/http/base_path_service.ts index 5b5901b0ad6fb..093d73b2da3bf 100644 --- a/src/core/server/http/base_path_service.ts +++ b/src/core/server/http/base_path_service.ts @@ -69,7 +69,7 @@ export class BasePath { */ public prepend = (path: string): string => { if (this.serverBasePath === '') return path; - return modifyUrl(path, parts => { + return modifyUrl(path, (parts) => { if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) { parts.pathname = `${this.serverBasePath}${parts.pathname}`; } diff --git a/src/core/server/http/cookie_session_storage.test.ts b/src/core/server/http/cookie_session_storage.test.ts index 0ca87eae6e235..a5612675c37de 100644 --- a/src/core/server/http/cookie_session_storage.test.ts +++ b/src/core/server/http/cookie_session_storage.test.ts @@ -101,7 +101,7 @@ const userData = { id: '42' }; const sessionDurationMs = 1000; const path = '/'; const sessVal = () => ({ value: userData, expires: Date.now() + sessionDurationMs, path }); -const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); +const delay = (ms: number) => new Promise((res) => setTimeout(res, ms)); const cookieOptions = { name: 'sid', encryptionKey: 'something_at_least_32_characters', @@ -135,9 +135,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); expect(cookies).toBeDefined(); @@ -174,9 +172,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); expect(cookies).toBeDefined(); @@ -207,9 +203,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200, { value: null }); + const response = await supertest(innerServer.listener).get('/').expect(200, { value: null }); const cookies = response.get('set-cookie'); expect(cookies).not.toBeDefined(); @@ -414,9 +408,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); const sessionCookie = retrieveSessionCookie(cookies[0]); diff --git a/src/core/server/http/http_config.ts b/src/core/server/http/http_config.ts index 7c72e3270743e..289b6539fd762 100644 --- a/src/core/server/http/http_config.ts +++ b/src/core/server/http/http_config.ts @@ -103,7 +103,7 @@ export const config = { }), }, { - validate: rawConfig => { + validate: (rawConfig) => { if (!rawConfig.basePath && rawConfig.rewriteBasePath) { return 'cannot use [rewriteBasePath] when [basePath] is not specified'; } @@ -157,7 +157,7 @@ export class HttpConfig { (headers, [key, value]) => { return { ...headers, - [key]: Array.isArray(value) ? value.map(e => convertHeader(e)) : convertHeader(value), + [key]: Array.isArray(value) ? value.map((e) => convertHeader(e)) : convertHeader(value), }; }, {} diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts index 4fb433b5c77ba..1798c3a921da4 100644 --- a/src/core/server/http/http_server.test.ts +++ b/src/core/server/http/http_server.test.ts @@ -163,7 +163,7 @@ test('valid params', async () => { await supertest(innerServer.listener) .get('/foo/some-string') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('some-string'); }); }); @@ -193,7 +193,7 @@ test('invalid params', async () => { await supertest(innerServer.listener) .get('/foo/some-string') .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -228,7 +228,7 @@ test('valid query', async () => { await supertest(innerServer.listener) .get('/foo/?bar=test&quux=123') .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', quux: 123 }); }); }); @@ -258,7 +258,7 @@ test('invalid query', async () => { await supertest(innerServer.listener) .get('/foo/?bar=test') .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -297,7 +297,7 @@ test('valid body', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -335,7 +335,7 @@ test('valid body with validate function', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -378,7 +378,7 @@ test('not inline validation - specifying params', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -421,7 +421,7 @@ test('not inline validation - specifying validation handler', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -471,7 +471,7 @@ test('not inline handler - KibanaRequest', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'TEST', baz: '123' }); }); }); @@ -520,7 +520,7 @@ test('not inline handler - RequestHandler', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'TEST', baz: '123' }); }); }); @@ -551,7 +551,7 @@ test('invalid body', async () => { .post('/foo/') .send({ bar: 'test' }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -586,7 +586,7 @@ test('handles putting', async () => { .put('/foo/') .send({ key: 'new value' }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ key: 'new value' }); }); }); @@ -616,7 +616,7 @@ test('handles deleting', async () => { await supertest(innerServer.listener) .delete('/foo/3') .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ key: 3 }); }); }); @@ -646,28 +646,22 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => { }); test('/bar => 404', async () => { - await supertest(innerServerListener) - .get('/bar') - .expect(404); + await supertest(innerServerListener).get('/bar').expect(404); }); test('/bar/ => 404', async () => { - await supertest(innerServerListener) - .get('/bar/') - .expect(404); + await supertest(innerServerListener).get('/bar/').expect(404); }); test('/bar/foo => 404', async () => { - await supertest(innerServerListener) - .get('/bar/foo') - .expect(404); + await supertest(innerServerListener).get('/bar/foo').expect(404); }); test('/ => /', async () => { await supertest(innerServerListener) .get('/') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -676,7 +670,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => { await supertest(innerServerListener) .get('/foo') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/foo'); }); }); @@ -710,7 +704,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -719,7 +713,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar/') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -728,21 +722,17 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar/foo') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/foo'); }); }); test('/ => 404', async () => { - await supertest(innerServerListener) - .get('/') - .expect(404); + await supertest(innerServerListener).get('/').expect(404); }); test('/foo => 404', async () => { - await supertest(innerServerListener) - .get('/foo') - .expect(404); + await supertest(innerServerListener).get('/foo').expect(404); }); }); @@ -787,13 +777,9 @@ test('allows attaching metadata to attach meta-data tag strings to a route', asy registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .get('/with-tags') - .expect(200, { tags }); + await supertest(innerServer.listener).get('/with-tags').expect(200, { tags }); - await supertest(innerServer.listener) - .get('/without-tags') - .expect(200, { tags: [] }); + await supertest(innerServer.listener).get('/without-tags').expect(200, { tags: [] }); }); test('exposes route details of incoming request to a route handler', async () => { @@ -835,9 +821,7 @@ describe('conditional compression', () => { test('with `compression.enabled: true`', async () => { const listener = await setupServer(config); - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).toHaveProperty('content-encoding', 'gzip'); }); @@ -848,9 +832,7 @@ describe('conditional compression', () => { compression: { enabled: false }, }); - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).not.toHaveProperty('content-encoding'); }); @@ -865,9 +847,7 @@ describe('conditional compression', () => { }); test('enables compression for no referer', async () => { - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).toHaveProperty('content-encoding', 'gzip'); }); @@ -952,14 +932,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(415, { - statusCode: 415, - error: 'Unsupported Media Type', - message: 'Unsupported Media Type', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(415, { + statusCode: 415, + error: 'Unsupported Media Type', + message: 'Unsupported Media Type', + }); }); test('should reject the request because the payload is too large', async () => { @@ -977,14 +954,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(413, { - statusCode: 413, - error: 'Request Entity Too Large', - message: 'Payload content length greater than maximum allowed: 1', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(413, { + statusCode: 413, + error: 'Request Entity Too Large', + message: 'Payload content length greater than maximum allowed: 1', + }); }); test('should not parse the content in the request', async () => { @@ -1010,14 +984,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(200, { - parse: false, - maxBytes: 1024, // hapi populates the default - output: 'data', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(200, { + parse: false, + maxBytes: 1024, // hapi populates the default + output: 'data', + }); }); }); @@ -1043,14 +1014,11 @@ test('should return a stream in the body', async () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .put('/') - .send({ test: 1 }) - .expect(200, { - parse: true, - maxBytes: 1024, // hapi populates the default - output: 'stream', - }); + await supertest(innerServer.listener).put('/').send({ test: 1 }).expect(200, { + parse: true, + maxBytes: 1024, // hapi populates the default + output: 'stream', + }); }); describe('setup contract', () => { diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts index 92ac5220735a1..8089ee901fa65 100644 --- a/src/core/server/http/http_server.ts +++ b/src/core/server/http/http_server.ts @@ -176,7 +176,7 @@ export class HttpServer { // validation applied in ./http_tools#getServerOptions // (All NP routes are already required to specify their own validation in order to access the payload) validate, - payload: [allow, maxBytes, output, parse].some(v => typeof v !== 'undefined') + payload: [allow, maxBytes, output, parse].some((v) => typeof v !== 'undefined') ? { allow, maxBytes, output, parse } : undefined, }, diff --git a/src/core/server/http/http_tools.test.ts b/src/core/server/http/http_tools.test.ts index bdaab4f2999ed..79a1e32d1b51e 100644 --- a/src/core/server/http/http_tools.test.ts +++ b/src/core/server/http/http_tools.test.ts @@ -81,7 +81,7 @@ describe('timeouts', () => { test('closes sockets on timeout', async () => { const router = new Router('', logger.get(), enhanceWithContext); router.get({ path: '/a', validate: false }, async (context, req, res) => { - await new Promise(resolve => setTimeout(resolve, 2000)); + await new Promise((resolve) => setTimeout(resolve, 2000)); return res.ok({}); }); router.get({ path: '/b', validate: false }, (context, req, res) => res.ok({})); @@ -98,9 +98,7 @@ describe('timeouts', () => { expect(supertest(innerServer.listener).get('/a')).rejects.toThrow('socket hang up'); - await supertest(innerServer.listener) - .get('/b') - .expect(200); + await supertest(innerServer.listener).get('/b').expect(200); }); afterAll(async () => { diff --git a/src/core/server/http/http_tools.ts b/src/core/server/http/http_tools.ts index 6e785ae9f8f00..4e47cf492e287 100644 --- a/src/core/server/http/http_tools.ts +++ b/src/core/server/http/http_tools.ts @@ -53,7 +53,7 @@ export function getServerOptions(config: HttpConfig, { configureTLS = true } = { // This is a default payload validation which applies to all LP routes which do not specify their own // `validate.payload` handler, in order to reduce the likelyhood of prototype pollution vulnerabilities. // (All NP routes are already required to specify their own validation in order to access the payload) - payload: value => Promise.resolve(validateObject(value)), + payload: (value) => Promise.resolve(validateObject(value)), }, }, state: { @@ -104,7 +104,7 @@ export function createServer(serverOptions: ServerOptions, listenerOptions: List server.listener.keepAliveTimeout = listenerOptions.keepaliveTimeout; server.listener.setTimeout(listenerOptions.socketTimeout); - server.listener.on('timeout', socket => { + server.listener.on('timeout', (socket) => { socket.destroy(); }); server.listener.on('clientError', (err, socket) => { @@ -155,7 +155,7 @@ export function defaultValidationErrorHandler( const validationError: HapiValidationError = err as HapiValidationError; const validationKeys: string[] = []; - validationError.details.forEach(detail => { + validationError.details.forEach((detail) => { if (detail.path.length > 0) { validationKeys.push(Hoek.escapeHtml(detail.path.join('.'))); } else { diff --git a/src/core/server/http/https_redirect_server.test.ts b/src/core/server/http/https_redirect_server.test.ts index e7cd653bb9eec..a7d3cbe41aa3d 100644 --- a/src/core/server/http/https_redirect_server.test.ts +++ b/src/core/server/http/https_redirect_server.test.ts @@ -100,7 +100,7 @@ test('forwards http requests to https', async () => { await supertest(getServerListener(server)) .get('/') .expect(302) - .then(res => { + .then((res) => { expect(res.header.location).toEqual(`https://${config.host}:${config.port}/`); }); }); diff --git a/src/core/server/http/integration_tests/core_service.test.mocks.ts b/src/core/server/http/integration_tests/core_service.test.mocks.ts index b3adda8dd22d1..8e782970e2a8e 100644 --- a/src/core/server/http/integration_tests/core_service.test.mocks.ts +++ b/src/core/server/http/integration_tests/core_service.test.mocks.ts @@ -20,7 +20,7 @@ import { elasticsearchServiceMock } from '../../elasticsearch/elasticsearch_serv export const clusterClientMock = jest.fn(); jest.doMock('../../elasticsearch/scoped_cluster_client', () => ({ - ScopedClusterClient: clusterClientMock.mockImplementation(function() { + ScopedClusterClient: clusterClientMock.mockImplementation(function () { return elasticsearchServiceMock.createScopedClusterClient(); }), })); @@ -30,7 +30,7 @@ jest.doMock('elasticsearch', () => { return { ...realES, // eslint-disable-next-line object-shorthand - Client: function() { + Client: function () { return elasticsearchServiceMock.createElasticsearchClient(); }, }; diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts index 0f0d54e88daca..73ed4e5de4b04 100644 --- a/src/core/server/http/integration_tests/lifecycle.test.ts +++ b/src/core/server/http/integration_tests/lifecycle.test.ts @@ -75,9 +75,7 @@ describe('OnPreAuth', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -108,9 +106,7 @@ describe('OnPreAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/initial') - .expect(200, 'redirected'); + await supertest(innerServer.listener).get('/initial').expect(200, 'redirected'); expect(urlBeforeForwarding).toBe('/initial'); expect(urlAfterForwarding).toBe('/redirectUrl'); @@ -132,9 +128,7 @@ describe('OnPreAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -154,9 +148,7 @@ describe('OnPreAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -172,9 +164,7 @@ describe('OnPreAuth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -195,9 +185,7 @@ describe('OnPreAuth', () => { registerOnPreAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -232,9 +220,7 @@ describe('OnPreAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -257,9 +243,7 @@ describe('OnPostAuth', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -280,9 +264,7 @@ describe('OnPostAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -301,9 +283,7 @@ describe('OnPostAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -318,9 +298,7 @@ describe('OnPostAuth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -340,9 +318,7 @@ describe('OnPostAuth', () => { registerOnPostAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -378,9 +354,7 @@ describe('OnPostAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -410,9 +384,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.authenticated()); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { content: 'ok' }); + await supertest(innerServer.listener).get('/').expect(200, { content: 'ok' }); }); it('blocks access to a resource if credentials are not provided', async () => { @@ -425,9 +397,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.notHandled()); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -443,9 +413,7 @@ describe('Auth', () => { registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: true }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: true }); expect(authenticate).toHaveBeenCalledTimes(1); }); @@ -463,9 +431,7 @@ describe('Auth', () => { registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: false }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: false }); expect(authenticate).toHaveBeenCalledTimes(0); }); @@ -483,9 +449,7 @@ describe('Auth', () => { await registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: true }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: true }); expect(authenticate).toHaveBeenCalledTimes(1); }); @@ -498,9 +462,7 @@ describe('Auth', () => { registerAuth((req, res) => res.unauthorized()); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('supports redirecting', async () => { @@ -516,9 +478,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(302); + const response = await supertest(innerServer.listener).get('/').expect(302); expect(response.header.location).toBe(redirectTo); }); @@ -530,9 +490,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.redirected({} as any)); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); }); it(`doesn't expose internal error details`, async () => { @@ -545,9 +503,7 @@ describe('Auth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -582,9 +538,7 @@ describe('Auth', () => { await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['set-cookie']).toBeDefined(); const cookies = response.header['set-cookie']; @@ -628,9 +582,7 @@ describe('Auth', () => { }); await server.start(); - const responseToSetCookie = await supertest(innerServer.listener) - .get('/') - .expect(200); + const responseToSetCookie = await supertest(innerServer.listener).get('/').expect(200); expect(responseToSetCookie.header['set-cookie']).toBeDefined(); @@ -680,10 +632,7 @@ describe('Auth', () => { await server.start(); const token = 'Basic: user:password'; - await supertest(innerServer.listener) - .get('/') - .set('Authorization', token) - .expect(200); + await supertest(innerServer.listener).get('/').set('Authorization', token).expect(200); expect(fromRegisterOnPreAuth).toEqual({}); expect(fromRegisterAuth).toEqual({ authorization: token }); @@ -705,9 +654,7 @@ describe('Auth', () => { router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']); }); @@ -726,9 +673,7 @@ describe('Auth', () => { router.get({ path: '/', validate: false }, (context, req, res) => res.badRequest()); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(400); + const response = await supertest(innerServer.listener).get('/').expect(400); expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']); }); @@ -755,9 +700,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['www-authenticate']).toBe('from auth interceptor'); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` @@ -790,9 +733,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(400); + const response = await supertest(innerServer.listener).get('/').expect(400); expect(response.header['www-authenticate']).toBe('from auth interceptor'); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` @@ -819,9 +760,7 @@ describe('Auth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -841,9 +780,7 @@ describe('Auth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -858,9 +795,7 @@ describe('Auth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -880,9 +815,7 @@ describe('Auth', () => { registerOnPostAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -917,9 +850,7 @@ describe('Auth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -944,9 +875,7 @@ describe('OnPreResponse', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -974,9 +903,7 @@ describe('OnPreResponse', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header['x-kibana-header']).toBe('value'); expect(result.header['x-my-header']).toBe('foo'); @@ -1000,9 +927,7 @@ describe('OnPreResponse', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` Array [ @@ -1025,9 +950,7 @@ describe('OnPreResponse', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1049,9 +972,7 @@ describe('OnPreResponse', () => { registerOnPreResponse((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1078,8 +999,6 @@ describe('OnPreResponse', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); }); }); diff --git a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts index b5364c616f17c..2120fb5b881de 100644 --- a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts +++ b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts @@ -94,9 +94,7 @@ describe('core lifecycle handlers', () => { }); it('accepts requests that do not include a version header', async () => { - await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); }); it('rejects requests with an incorrect version passed in the version header', async () => { @@ -122,9 +120,7 @@ describe('core lifecycle handlers', () => { }); it('adds the kbn-name header', async () => { - const result = await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); const headers = result.header as Record; expect(headers).toEqual( expect.objectContaining({ @@ -134,9 +130,7 @@ describe('core lifecycle handlers', () => { }); it('adds the kbn-name header in case of error', async () => { - const result = await supertest(innerServer.listener) - .get(testErrorRoute) - .expect(400); + const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400); const headers = result.header as Record; expect(headers).toEqual( expect.objectContaining({ @@ -146,17 +140,13 @@ describe('core lifecycle handlers', () => { }); it('adds the custom headers', async () => { - const result = await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); const headers = result.header as Record; expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' })); }); it('adds the custom headers in case of error', async () => { - const result = await supertest(innerServer.listener) - .get(testErrorRoute) - .expect(400); + const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400); const headers = result.header as Record; expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' })); }); @@ -176,7 +166,7 @@ describe('core lifecycle handlers', () => { return res.ok({ body: 'ok' }); }); - destructiveMethods.forEach(method => { + destructiveMethods.forEach((method) => { ((router as any)[method.toLowerCase()] as RouteRegistrar)( { path: testPath, validate: false }, (context, req, res) => { @@ -200,7 +190,7 @@ describe('core lifecycle handlers', () => { await server.start(); }); - nonDestructiveMethods.forEach(method => { + nonDestructiveMethods.forEach((method) => { describe(`When using non-destructive ${method} method`, () => { it('accepts requests without a token', async () => { await getSupertest(method.toLowerCase(), testPath).expect( @@ -217,7 +207,7 @@ describe('core lifecycle handlers', () => { }); }); - destructiveMethods.forEach(method => { + destructiveMethods.forEach((method) => { describe(`When using destructive ${method} method`, () => { it('accepts requests with the xsrf header', async () => { await getSupertest(method.toLowerCase(), testPath) diff --git a/src/core/server/http/integration_tests/request.test.ts b/src/core/server/http/integration_tests/request.test.ts index 85270174fbc04..d33757273042b 100644 --- a/src/core/server/http/integration_tests/request.test.ts +++ b/src/core/server/http/integration_tests/request.test.ts @@ -43,7 +43,7 @@ afterEach(async () => { await server.stop(); }); -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); describe('KibanaRequest', () => { describe('auth', () => { describe('isAuthenticated', () => { @@ -56,11 +56,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns false if not authenticated on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -72,11 +70,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns false if redirected on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -88,11 +84,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns true if authenticated on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -104,11 +98,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: true, + }); }); it('returns true if authenticated', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -120,17 +112,15 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: true, + }); }); }); }); describe('events', () => { describe('aborted$', () => { - it('emits once and completes when request aborted', async done => { + it('emits once and completes when request aborted', async (done) => { expect.assertions(1); const { server: innerServer, createRouter } = await server.setup(setupDeps); const router = createRouter('/'); diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts index af05229f86f20..8f3799b12eccb 100644 --- a/src/core/server/http/integration_tests/router.test.ts +++ b/src/core/server/http/integration_tests/router.test.ts @@ -65,12 +65,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('Authenticated user has access to a route', async () => { @@ -94,12 +92,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: true, - requestIsAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: true, + requestIsAuthenticated: true, + }); }); it('User with no credentials can access a route', async () => { @@ -122,12 +118,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('User with invalid credentials cannot access a route', async () => { @@ -142,9 +136,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('does not redirect user and allows access to a resource', async () => { @@ -171,12 +163,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); }); @@ -197,12 +187,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('Authenticated user has access to a route', async () => { @@ -226,12 +214,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: true, - requestIsAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: true, + requestIsAuthenticated: true, + }); }); it('User with no credentials cannot access a route', async () => { @@ -245,9 +231,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('User with invalid credentials cannot access a route', async () => { @@ -262,9 +246,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('allows redirecting an user', async () => { @@ -284,9 +266,7 @@ describe('Options', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(302); + const result = await supertest(innerServer.listener).get('/').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -313,12 +293,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); expect(authHook).toHaveBeenCalledTimes(0); }); @@ -352,9 +330,7 @@ describe('Cache-Control', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect('Cache-Control', 'public, max-age=1200'); + await supertest(innerServer.listener).get('/').expect('Cache-Control', 'public, max-age=1200'); }); }); @@ -368,9 +344,7 @@ describe('Handler', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -391,9 +365,7 @@ describe('Handler', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -412,9 +384,7 @@ describe('Handler', () => { router.get({ path: '/', validate: false }, (context, req, res) => 'ok' as any); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -501,11 +471,7 @@ describe('Handler', () => { ); await server.start(); - await supertest(innerServer.listener) - .post('/') - .type('json') - .send('12') - .expect(200); + await supertest(innerServer.listener).post('/').type('json').send('12').expect(200); expect(body).toEqual(12); }); @@ -524,9 +490,7 @@ describe('handleLegacyErrors', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('Not Found'); }); @@ -546,9 +510,7 @@ describe('handleLegacyErrors', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -570,9 +532,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.body).toEqual({ key: 'value' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -588,9 +548,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('result'); expect(result.header['content-type']).toBe('text/html; charset=utf-8'); @@ -606,9 +564,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); }); it('supports answering with Stream', async () => { @@ -630,9 +586,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('abc'); expect(result.header['content-type']).toBe(undefined); @@ -646,7 +600,7 @@ describe('Response factory', () => { const stream = new Stream.PassThrough(); stream.write('a'); stream.write('b'); - setTimeout(function() { + setTimeout(function () { stream.write('c'); stream.end(); }, 100); @@ -656,9 +610,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('abc'); expect(result.header['transfer-encoding']).toBe('chunked'); @@ -681,10 +633,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200) - .buffer(true); + const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true); expect(result.header['content-encoding']).toBe('binary'); expect(result.header['content-length']).toBe('1028'); @@ -708,10 +657,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200) - .buffer(true); + const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true); expect(result.text).toBe('abc'); expect(result.header['content-length']).toBe('3'); @@ -733,9 +679,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toEqual('value'); expect(result.header.etag).toBe('1234'); @@ -757,9 +701,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toEqual('value'); expect(result.header.etag).toBe('1234'); @@ -781,9 +723,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header.etag).toBe('1234'); }); @@ -803,9 +743,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header['set-cookie']).toEqual(['foo', 'bar']); }); @@ -822,9 +760,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); // error happens within hapi when route handler already finished execution. expect(loggingServiceMock.collect(logger).error).toHaveLength(0); @@ -840,9 +776,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.body).toEqual({ key: 'value' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -858,9 +792,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(202); + const result = await supertest(innerServer.listener).get('/').expect(202); expect(result.body).toEqual({ location: 'somewhere' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -876,9 +808,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(204); + const result = await supertest(innerServer.listener).get('/').expect(204); expect(result.noContent).toBe(true); }); @@ -901,9 +831,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(302); + const result = await supertest(innerServer.listener).get('/').expect(302); expect(result.text).toBe('The document has moved'); expect(result.header.location).toBe('/new-url'); @@ -924,9 +852,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -951,9 +877,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -972,9 +896,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -995,9 +917,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -1040,7 +960,7 @@ describe('Response factory', () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1051,7 +971,7 @@ describe('Response factory', () => { baz: '123', }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', message: '[request body.body]: Wrong payload', @@ -1088,7 +1008,7 @@ describe('Response factory', () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1099,7 +1019,7 @@ describe('Response factory', () => { baz: '123', // Automatic casting happens }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1110,7 +1030,7 @@ describe('Response factory', () => { baz: 'test', // Can't cast it into number }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', message: '[request body.baz]: expected value of type [number] but got [string]', @@ -1135,9 +1055,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('no access'); expect(result.header['www-authenticate']).toBe('challenge'); @@ -1153,9 +1071,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -1171,9 +1087,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(403); + const result = await supertest(innerServer.listener).get('/').expect(403); expect(result.body.message).toBe('reason'); }); @@ -1188,9 +1102,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(403); + const result = await supertest(innerServer.listener).get('/').expect(403); expect(result.body.message).toBe('Forbidden'); }); @@ -1206,9 +1118,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('file is not found'); }); @@ -1223,9 +1133,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('Not Found'); }); @@ -1241,9 +1149,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(409); + const result = await supertest(innerServer.listener).get('/').expect(409); expect(result.body.message).toBe('stale version'); }); @@ -1258,9 +1164,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(409); + const result = await supertest(innerServer.listener).get('/').expect(409); expect(result.body.message).toBe('Conflict'); }); @@ -1279,9 +1183,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(418); + const result = await supertest(innerServer.listener).get('/').expect(418); expect(result.body).toEqual({ error: "I'm a teapot", @@ -1305,9 +1207,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1331,9 +1231,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1356,9 +1254,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1392,9 +1288,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(201); + const result = await supertest(innerServer.listener).get('/').expect(201); expect(result.header.location).toBe('somewhere'); }); @@ -1415,9 +1309,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(301); + const result = await supertest(innerServer.listener).get('/').expect(301); expect(result.header.location).toBe('/new-url'); }); @@ -1436,9 +1328,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` Array [ @@ -1463,9 +1353,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('unauthorized'); }); @@ -1486,9 +1374,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body).toEqual({ error: 'Unauthorized', @@ -1514,9 +1400,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body).toEqual({ error: 'Unauthorized', @@ -1540,9 +1424,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -1560,9 +1442,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('reason'); expect(loggingServiceMock.collect(logger).error).toHaveLength(0); @@ -1581,9 +1461,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1607,9 +1485,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1632,9 +1508,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1657,9 +1531,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` diff --git a/src/core/server/http/lifecycle/on_pre_response.ts b/src/core/server/http/lifecycle/on_pre_response.ts index 050881472bc80..9c8c6fba690d1 100644 --- a/src/core/server/http/lifecycle/on_pre_response.ts +++ b/src/core/server/http/lifecycle/on_pre_response.ts @@ -147,7 +147,7 @@ function findHeadersIntersection( headers: ResponseHeaders, log: Logger ) { - Object.keys(headers).forEach(headerName => { + Object.keys(headers).forEach((headerName) => { if (Reflect.has(responseHeaders, headerName)) { log.warn(`onPreResponseHandler rewrote a response header [${headerName}].`); } diff --git a/src/core/server/http/prototype_pollution/validate_object.test.ts b/src/core/server/http/prototype_pollution/validate_object.test.ts index 9e23d6cec6444..23d6c4ae3b49f 100644 --- a/src/core/server/http/prototype_pollution/validate_object.test.ts +++ b/src/core/server/http/prototype_pollution/validate_object.test.ts @@ -51,8 +51,8 @@ test(`fails on circular references`, () => { }, { constructor: { foo: { prototype: null } } }, { prototype: { foo: { constructor: null } } }, -].forEach(value => { - ['headers', 'payload', 'query', 'params'].forEach(property => { +].forEach((value) => { + ['headers', 'payload', 'query', 'params'].forEach((property) => { const obj = { [property]: value, }; @@ -72,7 +72,7 @@ test(`fails on circular references`, () => { JSON.parse(`{ "constructor": { "prototype" : null } }`), JSON.parse(`{ "foo": { "constructor": { "prototype" : null } } }`), JSON.parse(`{ "foo": { "bar": { "constructor": { "prototype" : null } } } }`), -].forEach(value => { +].forEach((value) => { test(`can't submit ${JSON.stringify(value)}`, () => { expect(() => validateObject(value)).toThrowErrorMatchingSnapshot(); }); diff --git a/src/core/server/http/router/error_wrapper.ts b/src/core/server/http/router/error_wrapper.ts index af99812eff4b3..75d0e0d630296 100644 --- a/src/core/server/http/router/error_wrapper.ts +++ b/src/core/server/http/router/error_wrapper.ts @@ -20,7 +20,7 @@ import Boom from 'boom'; import { RequestHandlerWrapper } from './router'; -export const wrapErrors: RequestHandlerWrapper = handler => { +export const wrapErrors: RequestHandlerWrapper = (handler) => { return async (context, request, response) => { try { return await handler(context, request, response); diff --git a/src/core/server/http/router/headers.ts b/src/core/server/http/router/headers.ts index b79cc0d325f1e..f27f5e937b2c0 100644 --- a/src/core/server/http/router/headers.ts +++ b/src/core/server/http/router/headers.ts @@ -71,7 +71,7 @@ export function filterHeaders( // Normalize list of headers we want to allow in upstream request const fieldsToKeepNormalized = fieldsToKeep .map(normalizeHeaderField) - .filter(name => !fieldsToExcludeNormalized.includes(name)); + .filter((name) => !fieldsToExcludeNormalized.includes(name)); return pick(headers, fieldsToKeepNormalized); } diff --git a/src/core/server/http/router/router.mock.ts b/src/core/server/http/router/router.mock.ts index b43db0ca7ed5a..651d1712100ee 100644 --- a/src/core/server/http/router/router.mock.ts +++ b/src/core/server/http/router/router.mock.ts @@ -30,7 +30,7 @@ function create({ routerPath = '' }: { routerPath?: string } = {}): RouterMock { put: jest.fn(), patch: jest.fn(), getRoutes: jest.fn(), - handleLegacyErrors: jest.fn().mockImplementation(handler => handler), + handleLegacyErrors: jest.fn().mockImplementation((handler) => handler), }; } diff --git a/src/core/server/http/router/validator/validator.test.ts b/src/core/server/http/router/validator/validator.test.ts index e972e2075e705..30f66f5d41fbe 100644 --- a/src/core/server/http/router/validator/validator.test.ts +++ b/src/core/server/http/router/validator/validator.test.ts @@ -46,7 +46,7 @@ describe('Router validator', () => { it('should validate and infer the type from a function that does not use the resolver', () => { const validator = RouteValidator.from({ - params: data => { + params: (data) => { if (typeof data.foo === 'string') { return { value: { foo: data.foo as string } }; } @@ -112,7 +112,7 @@ describe('Router validator', () => { it('should catch the errors thrown by the validate function', () => { const validator = RouteValidator.from({ - params: data => { + params: (data) => { throw new Error('Something went terribly wrong'); }, }); diff --git a/src/core/server/http/ssl_config.ts b/src/core/server/http/ssl_config.ts index 4eb0c50e72362..75dc05d1a801b 100644 --- a/src/core/server/http/ssl_config.ts +++ b/src/core/server/http/ssl_config.ts @@ -65,7 +65,7 @@ export const sslSchema = schema.object( ), }, { - validate: ssl => { + validate: (ssl) => { if (ssl.key && ssl.keystore.path) { return 'cannot use [key] when [keystore.path] is specified'; } diff --git a/src/core/server/legacy/config/ensure_valid_configuration.ts b/src/core/server/legacy/config/ensure_valid_configuration.ts index a68d3df577a89..5cd1603ea65fb 100644 --- a/src/core/server/legacy/config/ensure_valid_configuration.ts +++ b/src/core/server/legacy/config/ensure_valid_configuration.ts @@ -36,7 +36,7 @@ export async function ensureValidConfiguration( if (unusedConfigKeys.length > 0) { const message = `Unknown configuration key(s): ${unusedConfigKeys - .map(key => `"${key}"`) + .map((key) => `"${key}"`) .join(', ')}. Check for spelling errors and ensure that expected plugins are installed.`; throw new InvalidConfigurationError(message); } diff --git a/src/core/server/legacy/config/get_unused_config_keys.ts b/src/core/server/legacy/config/get_unused_config_keys.ts index 20c9776f63c58..6cd193d896109 100644 --- a/src/core/server/legacy/config/get_unused_config_keys.ts +++ b/src/core/server/legacy/config/get_unused_config_keys.ts @@ -72,8 +72,8 @@ export async function getUnusedConfigKeys({ // Filter out keys that are marked as used in the core (e.g. by new core plugins). return difference(inputKeys, appliedKeys).filter( - unusedConfigKey => - !coreHandledConfigPaths.some(usedInCoreConfigKey => + (unusedConfigKey) => + !coreHandledConfigPaths.some((usedInCoreConfigKey) => hasConfigPathIntersection(unusedConfigKey, usedInCoreConfigKey) ) ); diff --git a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts index 8651d05064492..b09f9d00b3bed 100644 --- a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts +++ b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts @@ -27,7 +27,7 @@ jest.spyOn(configDeprecationFactory, 'unusedFromRoot'); jest.spyOn(configDeprecationFactory, 'renameFromRoot'); const executeHandlers = (handlers: ConfigDeprecation[]) => { - handlers.forEach(handler => { + handlers.forEach((handler) => { handler({}, '', () => null); }); }; @@ -99,7 +99,7 @@ describe('convertLegacyDeprecationProvider', () => { const migrated = applyDeprecations( rawConfig, - handlers.map(handler => ({ deprecation: handler, path: '' })) + handlers.map((handler) => ({ deprecation: handler, path: '' })) ); expect(migrated).toEqual({ new: 'oldvalue', goodValue: 'good' }); }); diff --git a/src/core/server/legacy/legacy_internals.test.ts b/src/core/server/legacy/legacy_internals.test.ts index dcab62627442b..2ae5e3a3fd1e8 100644 --- a/src/core/server/legacy/legacy_internals.test.ts +++ b/src/core/server/legacy/legacy_internals.test.ts @@ -84,7 +84,7 @@ describe('LegacyInternals', () => { jest.fn().mockResolvedValue({ is: 'merged-core' }), ]; - injectors.forEach(injector => legacyInternals.injectUiAppVars('core', injector)); + injectors.forEach((injector) => legacyInternals.injectUiAppVars('core', injector)); await expect(legacyInternals.getInjectedUiAppVars('core')).resolves.toMatchInlineSnapshot(` Object { @@ -136,10 +136,10 @@ describe('LegacyInternals', () => { it('gets: no default injectors, with injected vars replacers, with ui app injectors, no inject arg', async () => { uiExports.injectedVarsReplacers = [ - jest.fn(async vars => ({ ...vars, added: 'key' })), - jest.fn(vars => vars), - jest.fn(vars => ({ replaced: 'all' })), - jest.fn(async vars => ({ ...vars, added: 'last-key' })), + jest.fn(async (vars) => ({ ...vars, added: 'key' })), + jest.fn((vars) => vars), + jest.fn((vars) => ({ replaced: 'all' })), + jest.fn(async (vars) => ({ ...vars, added: 'last-key' })), ]; const request = httpServerMock.createRawRequest(); @@ -186,7 +186,7 @@ describe('LegacyInternals', () => { varsProvider({ gamma: 'gamma' }), varsProvider({ alpha: 'beta' }), ]; - uiExports.injectedVarsReplacers = [jest.fn(async vars => ({ ...vars, gamma: 'delta' }))]; + uiExports.injectedVarsReplacers = [jest.fn(async (vars) => ({ ...vars, gamma: 'delta' }))]; legacyInternals.injectUiAppVars('core', async () => ({ is: 'core' })); legacyInternals.injectUiAppVars('core', () => ({ sync: 'injector' })); diff --git a/src/core/server/legacy/legacy_service.test.ts b/src/core/server/legacy/legacy_service.test.ts index a75f7dda302c2..d9a0ac5e4ecff 100644 --- a/src/core/server/legacy/legacy_service.test.ts +++ b/src/core/server/legacy/legacy_service.test.ts @@ -353,7 +353,7 @@ describe('once LegacyService is set up without connection info', () => { describe('once LegacyService is set up in `devClusterMaster` mode', () => { beforeEach(() => { - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { return new BehaviorSubject( path === 'dev' ? { basePathProxyTargetPort: 100500 } : { basePath: '/abc' } ); @@ -447,7 +447,7 @@ describe('#discoverPlugins()', () => { it(`register legacy plugin's deprecation providers`, async () => { findLegacyPluginSpecsMock.mockImplementation( - settings => + (settings) => Promise.resolve({ pluginSpecs: [ { @@ -486,7 +486,7 @@ describe('#discoverPlugins()', () => { { getId: () => 'pluginB', getDeprecationsProvider: () => undefined }, ]; findLegacyPluginSpecsMock.mockImplementation( - settings => + (settings) => Promise.resolve({ pluginSpecs, pluginExtendedConfig: settings, diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index b95362e1ea26e..df1ed3e100923 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -91,7 +91,7 @@ export class LegacyService implements CoreService { this.log = logger.get('legacy-service'); this.devConfig$ = configService .atPath(devConfig.path) - .pipe(map(rawConfig => new DevConfig(rawConfig))); + .pipe(map((rawConfig) => new DevConfig(rawConfig))); this.httpConfig$ = combineLatest( configService.atPath(httpConfig.path), configService.atPath(cspConfig.path) @@ -108,7 +108,7 @@ export class LegacyService implements CoreService { this.kbnServer.applyLoggingConfiguration(getLegacyRawConfig(config, pathConfig)); } }), - tap({ error: err => this.log.error(err) }), + tap({ error: (err) => this.log.error(err) }), publishReplay(1) ) as ConnectableObservable<[Config, PathConfigType]>; @@ -146,14 +146,14 @@ export class LegacyService implements CoreService { }; const deprecationProviders = await pluginSpecs - .map(spec => spec.getDeprecationsProvider()) + .map((spec) => spec.getDeprecationsProvider()) .reduce(async (providers, current) => { if (current) { return [...(await providers), await convertLegacyDeprecationProvider(current)]; } return providers; }, Promise.resolve([] as ConfigDeprecationProvider[])); - deprecationProviders.forEach(provider => + deprecationProviders.forEach((provider) => this.coreContext.configService.addDeprecationProvider('', provider) ); diff --git a/src/core/server/legacy/merge_vars.ts b/src/core/server/legacy/merge_vars.ts index a1d43af2f861d..5d1820988e57a 100644 --- a/src/core/server/legacy/merge_vars.ts +++ b/src/core/server/legacy/merge_vars.ts @@ -25,9 +25,9 @@ export function mergeVars(...sources: LegacyVars[]): LegacyVars { return Object.assign( {}, ...sources, - ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap(key => - sources.some(source => key in source) - ? [{ [key]: Object.assign({}, ...sources.map(source => source[key] || {})) }] + ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap((key) => + sources.some((source) => key in source) + ? [{ [key]: Object.assign({}, ...sources.map((source) => source[key] || {})) }] : [] ) ); diff --git a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts index 44f02f0c90d4e..5039b3a55cc58 100644 --- a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts +++ b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts @@ -63,14 +63,14 @@ export async function findLegacyPluginSpecs( const log$ = merge( pack$.pipe( - tap(definition => { + tap((definition) => { const path = definition.getPath(); logger.debug(`Found plugin at ${path}`, { path }); }) ), invalidDirectoryError$.pipe( - tap(error => { + tap((error) => { logger.warn(`Unable to scan directory for plugins "${error.path}"`, { err: error, dir: error.path, @@ -79,7 +79,7 @@ export async function findLegacyPluginSpecs( ), invalidPackError$.pipe( - tap(error => { + tap((error) => { logger.warn(`Skipping non-plugin directory at ${error.path}`, { path: error.path, }); @@ -87,21 +87,21 @@ export async function findLegacyPluginSpecs( ), otherError$.pipe( - tap(error => { + tap((error) => { // rethrow unhandled errors, which will fail the server throw error; }) ), invalidVersionSpec$.pipe( - map(spec => { + map((spec) => { const name = spec.getId(); const pluginVersion = spec.getExpectedKibanaVersion(); const kibanaVersion = packageInfo.version; return `Plugin "${name}" was disabled because it expected Kibana version "${pluginVersion}", and found "${kibanaVersion}".`; }), distinct(), - tap(message => { + tap((message) => { logger.warn(message); }) ), diff --git a/src/core/server/legacy/plugins/get_nav_links.test.ts b/src/core/server/legacy/plugins/get_nav_links.test.ts index 5e84f27acabd5..af10706d0ea08 100644 --- a/src/core/server/legacy/plugins/get_nav_links.test.ts +++ b/src/core/server/legacy/plugins/get_nav_links.test.ts @@ -40,7 +40,7 @@ const createLegacyExports = ({ const createPluginSpecs = (...ids: string[]): LegacyPluginSpec[] => ids.map( - id => + (id) => ({ getId: () => id, } as LegacyPluginSpec) diff --git a/src/core/server/legacy/plugins/get_nav_links.ts b/src/core/server/legacy/plugins/get_nav_links.ts index 067fb204ca7f3..b1d22df41e345 100644 --- a/src/core/server/legacy/plugins/get_nav_links.ts +++ b/src/core/server/legacy/plugins/get_nav_links.ts @@ -66,11 +66,11 @@ function isHidden(app: LegacyAppSpec) { export function getNavLinks(uiExports: LegacyUiExports, pluginSpecs: LegacyPluginSpec[]) { const navLinkSpecs = uiExports.navLinkSpecs || []; const appSpecs = (uiExports.uiAppSpecs || []).filter( - app => app !== undefined && !isHidden(app) + (app) => app !== undefined && !isHidden(app) ) as LegacyAppSpec[]; - const pluginIds = (pluginSpecs || []).map(spec => spec.getId()); - appSpecs.forEach(spec => { + const pluginIds = (pluginSpecs || []).map((spec) => spec.getId()); + appSpecs.forEach((spec) => { if (spec.pluginId && !pluginIds.includes(spec.pluginId)) { throw new Error(`Unknown plugin id "${spec.pluginId}"`); } diff --git a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts index df86f5a2b4031..4a4a1b1b0e60b 100644 --- a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts +++ b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts @@ -36,7 +36,7 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({ }) => { const thirdPartySpecs = specs.filter(isThirdPartyPluginSpec); if (thirdPartySpecs.length > 0) { - const pluginIds = thirdPartySpecs.map(spec => spec.getId()); + const pluginIds = thirdPartySpecs.map((spec) => spec.getId()); log.warn( `Some installed third party plugin(s) [${pluginIds.join( ', ' @@ -49,5 +49,5 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({ const isThirdPartyPluginSpec = (spec: LegacyPluginSpec): boolean => { const pluginPath = spec.getPack().getPath(); - return !internalPaths.some(internalPath => pluginPath.indexOf(internalPath) > -1); + return !internalPaths.some((internalPath) => pluginPath.indexOf(internalPath) > -1); }; diff --git a/src/core/server/logging/appenders/file/file_appender.test.ts b/src/core/server/logging/appenders/file/file_appender.test.ts index 0483a06b199b6..bff60029faf11 100644 --- a/src/core/server/logging/appenders/file/file_appender.test.ts +++ b/src/core/server/logging/appenders/file/file_appender.test.ts @@ -23,7 +23,7 @@ import { LogLevel } from '../../log_level'; import { LogRecord } from '../../log_record'; import { FileAppender } from './file_appender'; -const tickMs = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const tickMs = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); beforeEach(() => { mockCreateWriteStream.mockReset(); diff --git a/src/core/server/logging/appenders/file/file_appender.ts b/src/core/server/logging/appenders/file/file_appender.ts index 3aca59fb3f42c..728e82ebcec9a 100644 --- a/src/core/server/logging/appenders/file/file_appender.ts +++ b/src/core/server/logging/appenders/file/file_appender.ts @@ -66,7 +66,7 @@ export class FileAppender implements DisposableAppender { * Disposes `FileAppender`. Waits for the underlying file stream to be completely flushed and closed. */ public async dispose() { - await new Promise(resolve => { + await new Promise((resolve) => { if (this.outputStream === undefined) { return resolve(); } diff --git a/src/core/server/logging/integration_tests/utils.ts b/src/core/server/logging/integration_tests/utils.ts index 81a76ce76ad73..e4c2c8866cb92 100644 --- a/src/core/server/logging/integration_tests/utils.ts +++ b/src/core/server/logging/integration_tests/utils.ts @@ -55,7 +55,7 @@ export async function getPlatformLogsFromFile(path: string) { const fileContent = await readFile(path, 'utf-8'); return fileContent .split('\n') - .map(s => normalizePlatformLogging(s)) + .map((s) => normalizePlatformLogging(s)) .join('\n'); } @@ -63,6 +63,6 @@ export async function getLegacyPlatformLogsFromFile(path: string) { const fileContent = await readFile(path, 'utf-8'); return fileContent .split('\n') - .map(s => normalizeLegacyPlatformLogging(s)) + .map((s) => normalizeLegacyPlatformLogging(s)) .join('\n'); } diff --git a/src/core/server/logging/layouts/pattern_layout.ts b/src/core/server/logging/layouts/pattern_layout.ts index 9490db149cc0f..7839345a3703b 100644 --- a/src/core/server/logging/layouts/pattern_layout.ts +++ b/src/core/server/logging/layouts/pattern_layout.ts @@ -37,7 +37,7 @@ import { const DEFAULT_PATTERN = `[%date][%level][%logger]%meta %message`; export const patternSchema = schema.string({ - validate: string => { + validate: (string) => { DateConversion.validate!(string); }, }); diff --git a/src/core/server/logging/logging_config.ts b/src/core/server/logging/logging_config.ts index 8f80be7d79cb1..772909ce584e5 100644 --- a/src/core/server/logging/logging_config.ts +++ b/src/core/server/logging/logging_config.ts @@ -167,13 +167,13 @@ export class LoggingConfig { ]; const loggerConfigByContext = new Map( - loggers.map(loggerConfig => toTuple(loggerConfig.context, loggerConfig)) + loggers.map((loggerConfig) => toTuple(loggerConfig.context, loggerConfig)) ); for (const [loggerContext, loggerConfig] of loggerConfigByContext) { // Ensure logger config only contains valid appenders. const unsupportedAppenderKey = loggerConfig.appenders.find( - appenderKey => !this.appenders.has(appenderKey) + (appenderKey) => !this.appenders.has(appenderKey) ); if (unsupportedAppenderKey) { diff --git a/src/core/server/logging/logging_service.ts b/src/core/server/logging/logging_service.ts index f9535e6c8283e..2e6f895724122 100644 --- a/src/core/server/logging/logging_service.ts +++ b/src/core/server/logging/logging_service.ts @@ -108,7 +108,7 @@ export class LoggingService implements LoggerFactory { const { level, appenders } = this.getLoggerConfigByContext(config, context); const loggerLevel = LogLevel.fromId(level); - const loggerAppenders = appenders.map(appenderKey => this.appenders.get(appenderKey)!); + const loggerAppenders = appenders.map((appenderKey) => this.appenders.get(appenderKey)!); return new BaseLogger(context, loggerLevel, loggerAppenders, this.asLoggerFactory()); } diff --git a/src/core/server/metrics/collectors/process.ts b/src/core/server/metrics/collectors/process.ts index a3b59a7cc8b7c..b020eebcbbd0b 100644 --- a/src/core/server/metrics/collectors/process.ts +++ b/src/core/server/metrics/collectors/process.ts @@ -46,7 +46,7 @@ export class ProcessMetricsCollector implements MetricsCollector => { const bench = new Bench(); - return new Promise(resolve => { + return new Promise((resolve) => { setImmediate(() => { return resolve(bench.elapsed()); }); diff --git a/src/core/server/metrics/collectors/server.ts b/src/core/server/metrics/collectors/server.ts index 84204d0466ff3..036332c24c34f 100644 --- a/src/core/server/metrics/collectors/server.ts +++ b/src/core/server/metrics/collectors/server.ts @@ -45,7 +45,7 @@ export class ServerMetricsCollector implements MetricsCollector { + this.server.events.on('response', (request) => { const statusCode = (request.response as ResponseObject)?.statusCode; if (statusCode) { if (!this.requests.statusCodes[statusCode]) { @@ -62,7 +62,7 @@ export class ServerMetricsCollector implements MetricsCollector { - const connections = await new Promise(resolve => { + const connections = await new Promise((resolve) => { this.server.listener.getConnections((_, count) => { resolve(count); }); diff --git a/src/core/server/metrics/integration_tests/server_collector.test.ts b/src/core/server/metrics/integration_tests/server_collector.test.ts index 3b982a06cf06c..4476b3c26a2e1 100644 --- a/src/core/server/metrics/integration_tests/server_collector.test.ts +++ b/src/core/server/metrics/integration_tests/server_collector.test.ts @@ -34,7 +34,7 @@ describe('ServerMetricsCollector', () => { let hapiServer: HapiServer; let router: IRouter; - const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const sendGet = (path: string) => supertest(hapiServer.listener).get(path); beforeEach(async () => { @@ -81,7 +81,7 @@ describe('ServerMetricsCollector', () => { }); it('collect disconnects requests infos', async () => { - const never = new Promise(resolve => undefined); + const never = new Promise((resolve) => undefined); const hitSubject = new BehaviorSubject(0); router.get({ path: '/', validate: false }, async (ctx, req, res) => { @@ -100,7 +100,7 @@ describe('ServerMetricsCollector', () => { await hitSubject .pipe( - filter(count => count >= 2), + filter((count) => count >= 2), take(1) ) .toPromise(); @@ -177,7 +177,7 @@ describe('ServerMetricsCollector', () => { const waitForHits = (hits: number) => hitSubject .pipe( - filter(count => count >= hits), + filter((count) => count >= hits), take(1) ) .toPromise(); @@ -189,12 +189,12 @@ describe('ServerMetricsCollector', () => { // however in this test we need to send the request now and await for it later in the code. // also using `.end` is not possible as it would execute the request twice. // so the only option is this noop `.then`. - const res1 = sendGet('/').then(res => res); + const res1 = sendGet('/').then((res) => res); await waitForHits(1); metrics = await collector.collect(); expect(metrics.concurrent_connections).toEqual(1); - const res2 = sendGet('/').then(res => res); + const res2 = sendGet('/').then((res) => res); await waitForHits(2); metrics = await collector.collect(); expect(metrics.concurrent_connections).toEqual(2); diff --git a/src/core/server/metrics/metrics_service.test.ts b/src/core/server/metrics/metrics_service.test.ts index f6334cc5d3c0f..01a7429745cda 100644 --- a/src/core/server/metrics/metrics_service.test.ts +++ b/src/core/server/metrics/metrics_service.test.ts @@ -82,10 +82,7 @@ describe('MetricsService', () => { // however the `reset` call is executed after the async call to `collect` // meaning that we are going to miss the call if we don't wait for the // actual observable emission that is performed after - const waitForNextEmission = () => - getOpsMetrics$() - .pipe(take(1)) - .toPromise(); + const waitForNextEmission = () => getOpsMetrics$().pipe(take(1)).toPromise(); expect(mockOpsCollector.collect).toHaveBeenCalledTimes(1); expect(mockOpsCollector.reset).toHaveBeenCalledTimes(1); diff --git a/src/core/server/path/index.ts b/src/core/server/path/index.ts index ef8a3caeefa2c..d482a32b32ae4 100644 --- a/src/core/server/path/index.ts +++ b/src/core/server/path/index.ts @@ -38,7 +38,7 @@ const DATA_PATHS = [ ].filter(isString); function findFile(paths: string[]) { - const availablePath = paths.find(configPath => { + const availablePath = paths.find((configPath) => { try { accessSync(configPath, constants.R_OK); return true; diff --git a/src/core/server/plugins/discovery/plugin_manifest_parser.ts b/src/core/server/plugins/discovery/plugin_manifest_parser.ts index 573109c9db35a..27c3ca5a71e16 100644 --- a/src/core/server/plugins/discovery/plugin_manifest_parser.ts +++ b/src/core/server/plugins/discovery/plugin_manifest_parser.ts @@ -154,7 +154,9 @@ export async function parseManifest(pluginPath: string, packageInfo: PackageInfo ); } - const unknownManifestKeys = Object.keys(manifest).filter(key => !KNOWN_MANIFEST_FIELDS.has(key)); + const unknownManifestKeys = Object.keys(manifest).filter( + (key) => !KNOWN_MANIFEST_FIELDS.has(key) + ); if (unknownManifestKeys.length > 0) { throw PluginDiscoveryError.invalidManifest( manifestPath, diff --git a/src/core/server/plugins/discovery/plugins_discovery.test.ts b/src/core/server/plugins/discovery/plugins_discovery.test.ts index 2902aafdbf146..73f274957cbc4 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.test.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.test.ts @@ -143,7 +143,7 @@ test('properly iterates through plugin search locations', async () => { resolve(TEST_PLUGIN_SEARCH_PATHS.nonEmptySrcPlugins, '6'), TEST_EXTRA_PLUGIN_PATH, ]) { - const discoveredPlugin = plugins.find(plugin => plugin.path === path)!; + const discoveredPlugin = plugins.find((plugin) => plugin.path === path)!; expect(discoveredPlugin).toBeInstanceOf(PluginWrapper); expect(discoveredPlugin.configPath).toEqual(['core', 'config']); expect(discoveredPlugin.requiredPlugins).toEqual(['a', 'b']); @@ -153,7 +153,7 @@ test('properly iterates through plugin search locations', async () => { await expect( error$ .pipe( - map(error => error.toString()), + map((error) => error.toString()), toArray() ) .toPromise() diff --git a/src/core/server/plugins/discovery/plugins_discovery.ts b/src/core/server/plugins/discovery/plugins_discovery.ts index e7f82c9dc15ad..1910483211e34 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.ts @@ -56,7 +56,7 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) { from(config.additionalPluginPaths), processPluginSearchPaths$(config.pluginSearchPaths, log) ).pipe( - mergeMap(pluginPathOrError => { + mergeMap((pluginPathOrError) => { return typeof pluginPathOrError === 'string' ? createPlugin$(pluginPathOrError, log, coreContext) : [pluginPathOrError]; @@ -83,21 +83,21 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) { */ function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) { return from(pluginDirs).pipe( - mergeMap(dir => { + mergeMap((dir) => { log.debug(`Scanning "${dir}" for plugin sub-directories...`); return fsReadDir$(dir).pipe( - mergeMap((subDirs: string[]) => subDirs.map(subDir => resolve(dir, subDir))), - mergeMap(path => + mergeMap((subDirs: string[]) => subDirs.map((subDir) => resolve(dir, subDir))), + mergeMap((path) => fsStat$(path).pipe( // Filter out non-directory entries from target directories, it's expected that // these directories may contain files (e.g. `README.md` or `package.json`). // We shouldn't silently ignore the entries we couldn't get stat for though. - mergeMap(pathStat => (pathStat.isDirectory() ? [path] : [])), - catchError(err => [PluginDiscoveryError.invalidPluginPath(path, err)]) + mergeMap((pathStat) => (pathStat.isDirectory() ? [path] : [])), + catchError((err) => [PluginDiscoveryError.invalidPluginPath(path, err)]) ) ), - catchError(err => [PluginDiscoveryError.invalidSearchPath(dir, err)]) + catchError((err) => [PluginDiscoveryError.invalidSearchPath(dir, err)]) ); }) ); @@ -113,7 +113,7 @@ function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) { */ function createPlugin$(path: string, log: Logger, coreContext: CoreContext) { return from(parseManifest(path, coreContext.env.packageInfo, log)).pipe( - map(manifest => { + map((manifest) => { log.debug(`Successfully discovered plugin "${manifest.id}" at "${path}"`); const opaqueId = Symbol(manifest.id); return new PluginWrapper({ @@ -123,6 +123,6 @@ function createPlugin$(path: string, log: Logger, coreContext: CoreContext) { initializerContext: createPluginInitializerContext(coreContext, opaqueId, manifest), }); }), - catchError(err => [err]) + catchError((err) => [err]) ); } diff --git a/src/core/server/plugins/integration_tests/plugins_service.test.ts b/src/core/server/plugins/integration_tests/plugins_service.test.ts index 1521fc332bcdb..04f570cca489b 100644 --- a/src/core/server/plugins/integration_tests/plugins_service.test.ts +++ b/src/core/server/plugins/integration_tests/plugins_service.test.ts @@ -139,7 +139,7 @@ describe('PluginsService', () => { }, start: async (core, plugins) => { contextFromStart = { core, plugins }; - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }, diff --git a/src/core/server/plugins/plugin.test.ts b/src/core/server/plugins/plugin.test.ts index 1e4d94dd00d0d..8d82d96f949c7 100644 --- a/src/core/server/plugins/plugin.test.ts +++ b/src/core/server/plugins/plugin.test.ts @@ -260,7 +260,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async setup: jest.fn(), start: async () => { // delay to ensure startDependencies is not resolved until after the plugin instance's start resolves. - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }, @@ -269,7 +269,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async await plugin.setup({} as any, {} as any); - const startDependenciesCheck = plugin.startDependencies.then(resolvedStartDeps => { + const startDependenciesCheck = plugin.startDependencies.then((resolvedStartDeps) => { startDependenciesResolved = true; expect(resolvedStartDeps).toEqual([startContext, pluginDeps, pluginStartContract]); }); diff --git a/src/core/server/plugins/plugins_service.test.ts b/src/core/server/plugins/plugins_service.test.ts index 38fda12bd290f..6f8d15838641f 100644 --- a/src/core/server/plugins/plugins_service.test.ts +++ b/src/core/server/plugins/plugins_service.test.ts @@ -51,7 +51,7 @@ const logger = loggingServiceMock.create(); expect.addSnapshotSerializer(createAbsolutePathSerializer()); -['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach(path => { +['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach((path) => { jest.doMock(join(path, 'server'), () => ({}), { virtual: true, }); @@ -200,7 +200,7 @@ describe('PluginsService', () => { it('properly detects plugins that should be disabled.', async () => { jest .spyOn(configService, 'isEnabledAtPath') - .mockImplementation(path => Promise.resolve(!path.includes('disabled'))); + .mockImplementation((path) => Promise.resolve(!path.includes('disabled'))); mockPluginSystem.setupPlugins.mockResolvedValue(new Map()); diff --git a/src/core/server/plugins/plugins_service.ts b/src/core/server/plugins/plugins_service.ts index d7a348affe94f..7441e753efa6a 100644 --- a/src/core/server/plugins/plugins_service.ts +++ b/src/core/server/plugins/plugins_service.ts @@ -87,7 +87,7 @@ export class PluginsService implements CoreService('plugins') - .pipe(map(rawConfig => new PluginsConfig(rawConfig, coreContext.env))); + .pipe(map((rawConfig) => new PluginsConfig(rawConfig, coreContext.env))); } public async discover() { @@ -153,7 +153,7 @@ export class PluginsService implements CoreService exposed) + Object.values(configDescriptor?.exposeToBrowser).some((exposed) => exposed) ); }) .map(([pluginId, plugin]) => { @@ -186,14 +186,14 @@ export class PluginsService implements CoreService errorTypesToReport.includes(error.type)), - tap(pluginError => this.log.error(pluginError)), + filter((error) => errorTypesToReport.includes(error.type)), + tap((pluginError) => this.log.error(pluginError)), toArray() ) .toPromise(); if (errors.length > 0) { throw new Error( - `Failed to initialize plugins:${errors.map(err => `\n\t${err.message}`).join('')}` + `Failed to initialize plugins:${errors.map((err) => `\n\t${err.message}`).join('')}` ); } } @@ -205,7 +205,7 @@ export class PluginsService implements CoreService(); await plugin$ .pipe( - mergeMap(async plugin => { + mergeMap(async (plugin) => { const configDescriptor = plugin.getConfigDescriptor(); if (configDescriptor) { this.pluginConfigDescriptors.set(plugin.name, configDescriptor); @@ -263,8 +263,8 @@ export class PluginsService implements CoreService !parents.includes(dep)) - .every(dependencyName => + .filter((dep) => !parents.includes(dep)) + .every((dependencyName) => this.shouldEnablePlugin(dependencyName, pluginEnableStatuses, [...parents, pluginName]) ) ); diff --git a/src/core/server/plugins/plugins_system.test.ts b/src/core/server/plugins/plugins_system.test.ts index 22dfbeecbaedd..8b318ad1b735e 100644 --- a/src/core/server/plugins/plugins_system.test.ts +++ b/src/core/server/plugins/plugins_system.test.ts @@ -342,7 +342,7 @@ test('`uiPlugins` returns ordered Maps of all plugin manifests', async () => { ], ] as Array<[PluginWrapper, Record]>); - [...plugins.keys()].forEach(plugin => { + [...plugins.keys()].forEach((plugin) => { pluginsSystem.addPlugin(plugin); }); @@ -371,7 +371,7 @@ test('`uiPlugins` returns only ui plugin dependencies', async () => { createPlugin('opt-no-ui', { ui: false, server: true }), ]; - plugins.forEach(plugin => { + plugins.forEach((plugin) => { pluginsSystem.addPlugin(plugin); }); @@ -424,7 +424,7 @@ describe('setup', () => { }); it('throws timeout error if "setup" was not completed in 30 sec.', async () => { const plugin: PluginWrapper = createPlugin('timeout-setup'); - jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise(i => i)); + jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise((i) => i)); pluginsSystem.addPlugin(plugin); mockCreatePluginSetupContext.mockImplementation(() => ({})); @@ -447,7 +447,7 @@ describe('start', () => { it('throws timeout error if "start" was not completed in 30 sec.', async () => { const plugin: PluginWrapper = createPlugin('timeout-start'); jest.spyOn(plugin, 'setup').mockResolvedValue({}); - jest.spyOn(plugin, 'start').mockImplementation(() => new Promise(i => i)); + jest.spyOn(plugin, 'start').mockImplementation(() => new Promise((i) => i)); pluginsSystem.addPlugin(plugin); mockCreatePluginSetupContext.mockImplementation(() => ({})); diff --git a/src/core/server/plugins/plugins_system.ts b/src/core/server/plugins/plugins_system.ts index dd2df7c8e01d1..e0401006ffac9 100644 --- a/src/core/server/plugins/plugins_system.ts +++ b/src/core/server/plugins/plugins_system.ts @@ -53,9 +53,9 @@ export class PluginsSystem { [ ...new Set([ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(optPlugin => this.plugins.has(optPlugin)), + ...plugin.optionalPlugins.filter((optPlugin) => this.plugins.has(optPlugin)), ]), - ].map(depId => this.plugins.get(depId)!.opaqueId), + ].map((depId) => this.plugins.get(depId)!.opaqueId), ]) ); } @@ -161,18 +161,22 @@ export class PluginsSystem { */ public uiPlugins() { const uiPluginNames = [...this.getTopologicallySortedPluginNames().keys()].filter( - pluginName => this.plugins.get(pluginName)!.includesUiPlugin + (pluginName) => this.plugins.get(pluginName)!.includesUiPlugin ); const publicPlugins = new Map( - uiPluginNames.map(pluginName => { + uiPluginNames.map((pluginName) => { const plugin = this.plugins.get(pluginName)!; return [ pluginName, { id: pluginName, configPath: plugin.manifest.configPath, - requiredPlugins: plugin.manifest.requiredPlugins.filter(p => uiPluginNames.includes(p)), - optionalPlugins: plugin.manifest.optionalPlugins.filter(p => uiPluginNames.includes(p)), + requiredPlugins: plugin.manifest.requiredPlugins.filter((p) => + uiPluginNames.includes(p) + ), + optionalPlugins: plugin.manifest.optionalPlugins.filter((p) => + uiPluginNames.includes(p) + ), }, ]; }) @@ -200,7 +204,7 @@ export class PluginsSystem { pluginName, new Set([ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(dependency => this.plugins.has(dependency)), + ...plugin.optionalPlugins.filter((dependency) => this.plugins.has(dependency)), ]), ] as [PluginName, Set]; }) @@ -209,7 +213,7 @@ export class PluginsSystem { // First, find a list of "start nodes" which have no outgoing edges. At least // one such node must exist in a non-empty acyclic graph. const pluginsWithAllDependenciesSorted = [...pluginsDependenciesGraph.keys()].filter( - pluginName => pluginsDependenciesGraph.get(pluginName)!.size === 0 + (pluginName) => pluginsDependenciesGraph.get(pluginName)!.size === 0 ); const sortedPluginNames = new Set(); diff --git a/src/core/server/rendering/views/fonts.tsx b/src/core/server/rendering/views/fonts.tsx index e87179920202a..8e460a150439d 100644 --- a/src/core/server/rendering/views/fonts.tsx +++ b/src/core/server/rendering/views/fonts.tsx @@ -249,7 +249,7 @@ export const Fonts: FunctionComponent = ({ url }) => { .flatMap(({ family, variants }) => variants.map(({ style, weight, format, sources, unicodeRange }) => { const src = sources - .map(source => + .map((source) => source.startsWith(url) ? `url('${source}') format('${format || source.split('.').pop()}')` : `local('${source}')` diff --git a/src/core/server/root/index.test.ts b/src/core/server/root/index.test.ts index 3b187aac022c3..5b853903ea4be 100644 --- a/src/core/server/root/index.test.ts +++ b/src/core/server/root/index.test.ts @@ -183,7 +183,7 @@ test('stops services if consequent logger upgrade fails', async () => { // Wait for shutdown to be called. await onShutdown .pipe( - filter(e => e !== null), + filter((e) => e !== null), first() ) .toPromise(); diff --git a/src/core/server/root/index.ts b/src/core/server/root/index.ts index eecc6399366dc..d6d0c641e00b0 100644 --- a/src/core/server/root/index.ts +++ b/src/core/server/root/index.ts @@ -99,10 +99,10 @@ export class Root { const update$ = configService.getConfig$().pipe( // always read the logging config when the underlying config object is re-read switchMap(() => configService.atPath('logging')), - map(config => this.loggingService.upgrade(config)), + map((config) => this.loggingService.upgrade(config)), // This specifically console.logs because we were not able to configure the logger. // eslint-disable-next-line no-console - tap({ error: err => console.error('Configuring logger failed:', err) }), + tap({ error: (err) => console.error('Configuring logger failed:', err) }), publishReplay(1) ) as ConnectableObservable; @@ -112,7 +112,7 @@ export class Root { // Send subsequent update failures to this.shutdown(), stopped via loggingConfigSubscription. this.loggingConfigSubscription = update$.subscribe({ - error: err => this.shutdown(err), + error: (err) => this.shutdown(err), }); // Add subscription we got from `connect` so that we can dispose both of them diff --git a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts index a703c9f9fbd96..cafaa5a3147db 100644 --- a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts +++ b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts @@ -95,7 +95,7 @@ async function fetchObjectsToExport({ throw Boom.badRequest(`Can't specify both "search" and "objects" properties when exporting`); } const bulkGetResult = await savedObjectsClient.bulkGet(objects, { namespace }); - const erroredObjects = bulkGetResult.saved_objects.filter(obj => !!obj.error); + const erroredObjects = bulkGetResult.saved_objects.filter((obj) => !!obj.error); if (erroredObjects.length) { const err = Boom.badRequest(); err.output.payload.attributes = { diff --git a/src/core/server/saved_objects/export/inject_nested_depdendencies.ts b/src/core/server/saved_objects/export/inject_nested_depdendencies.ts index d00650926e57a..1f8c645340dbf 100644 --- a/src/core/server/saved_objects/export/inject_nested_depdendencies.ts +++ b/src/core/server/saved_objects/export/inject_nested_depdendencies.ts @@ -51,8 +51,10 @@ export async function fetchNestedDependencies( } const allObjects = [...savedObjectsMap.values()]; return { - objects: allObjects.filter(obj => !obj.error), - missingRefs: allObjects.filter(obj => !!obj.error).map(obj => ({ type: obj.type, id: obj.id })), + objects: allObjects.filter((obj) => !obj.error), + missingRefs: allObjects + .filter((obj) => !!obj.error) + .map((obj) => ({ type: obj.type, id: obj.id })), }; } diff --git a/src/core/server/saved_objects/export/sort_objects.ts b/src/core/server/saved_objects/export/sort_objects.ts index 522146737d9cf..64bab9f43bf14 100644 --- a/src/core/server/saved_objects/export/sort_objects.ts +++ b/src/core/server/saved_objects/export/sort_objects.ts @@ -24,7 +24,7 @@ export function sortObjects(savedObjects: SavedObject[]): SavedObject[] { const path = new Set(); const sorted = new Set(); const objectsByTypeId = new Map( - savedObjects.map(object => [`${object.type}:${object.id}`, object] as [string, SavedObject]) + savedObjects.map((object) => [`${object.type}:${object.id}`, object] as [string, SavedObject]) ); function includeObjects(objects: SavedObject[]) { @@ -32,13 +32,13 @@ export function sortObjects(savedObjects: SavedObject[]): SavedObject[] { if (path.has(object)) { throw Boom.badRequest( `circular reference: ${[...path, object] - .map(obj => `[${obj.type}:${obj.id}]`) + .map((obj) => `[${obj.type}:${obj.id}]`) .join(' ref-> ')}` ); } const refdObjects = object.references - .map(ref => objectsByTypeId.get(`${ref.type}:${ref.id}`)) + .map((ref) => objectsByTypeId.get(`${ref.type}:${ref.id}`)) .filter((ref): ref is SavedObject => !!ref); if (refdObjects.length) { diff --git a/src/core/server/saved_objects/import/collect_saved_objects.ts b/src/core/server/saved_objects/import/collect_saved_objects.ts index 1a8ede41d0b2c..1b787c7d9dc10 100644 --- a/src/core/server/saved_objects/import/collect_saved_objects.ts +++ b/src/core/server/saved_objects/import/collect_saved_objects.ts @@ -45,7 +45,7 @@ export async function collectSavedObjects({ const collectedObjects: Array> = await createPromiseFromStreams([ readStream, createLimitStream(objectLimit), - createFilterStream>(obj => { + createFilterStream>((obj) => { if (supportedTypes.includes(obj.type)) { return true; } @@ -59,7 +59,7 @@ export async function collectSavedObjects({ }); return false; }), - createFilterStream(obj => (filter ? filter(obj) : true)), + createFilterStream((obj) => (filter ? filter(obj) : true)), createMapStream((obj: SavedObject) => { // Ensure migrations execute on every saved object return Object.assign({ migrationVersion: {} }, obj); diff --git a/src/core/server/saved_objects/import/create_objects_filter.ts b/src/core/server/saved_objects/import/create_objects_filter.ts index c48cded00f1ec..55b8ab128d753 100644 --- a/src/core/server/saved_objects/import/create_objects_filter.ts +++ b/src/core/server/saved_objects/import/create_objects_filter.ts @@ -21,7 +21,7 @@ import { SavedObject } from '../types'; import { SavedObjectsImportRetry } from './types'; export function createObjectsFilter(retries: SavedObjectsImportRetry[]) { - const retryKeys = new Set(retries.map(retry => `${retry.type}:${retry.id}`)); + const retryKeys = new Set(retries.map((retry) => `${retry.type}:${retry.id}`)); return (obj: SavedObject) => { return retryKeys.has(`${obj.type}:${obj.id}`); }; diff --git a/src/core/server/saved_objects/import/import_saved_objects.test.ts b/src/core/server/saved_objects/import/import_saved_objects.test.ts index b43e5063c13e1..e204cd7bddfc7 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.test.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.test.ts @@ -95,7 +95,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -178,7 +178,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -262,7 +262,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -345,13 +345,13 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.find.mockResolvedValueOnce(emptyResponse); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ type: savedObject.type, id: savedObject.id, error: { @@ -527,7 +527,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push({ id: '1', type: 'wigwags', attributes: { title: 'my title' }, references: [] }); this.push(null); }, diff --git a/src/core/server/saved_objects/import/import_saved_objects.ts b/src/core/server/saved_objects/import/import_saved_objects.ts index cb1d70e5c8dc4..6065e03fb1628 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.ts @@ -78,7 +78,7 @@ export async function importSavedObjectsFromStream({ return { success: errorAccumulator.length === 0, - successCount: bulkCreateResult.saved_objects.filter(obj => !obj.error).length, + successCount: bulkCreateResult.saved_objects.filter((obj) => !obj.error).length, ...(errorAccumulator.length ? { errors: errorAccumulator } : {}), }; } diff --git a/src/core/server/saved_objects/import/resolve_import_errors.test.ts b/src/core/server/saved_objects/import/resolve_import_errors.test.ts index 2c6d89e0a0a47..54ebecc7dca70 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.test.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.test.ts @@ -73,7 +73,7 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -100,12 +100,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValueOnce({ - saved_objects: savedObjects.filter(obj => obj.type === 'visualization' && obj.id === '3'), + saved_objects: savedObjects.filter((obj) => obj.type === 'visualization' && obj.id === '3'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -161,12 +161,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'index-pattern' && obj.id === '1'), + saved_objects: savedObjects.filter((obj) => obj.type === 'index-pattern' && obj.id === '1'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -223,12 +223,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'dashboard' && obj.id === '4'), + saved_objects: savedObjects.filter((obj) => obj.type === 'dashboard' && obj.id === '4'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -296,12 +296,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ type: savedObject.type, id: savedObject.id, error: { @@ -315,7 +315,7 @@ describe('resolveImportErrors()', () => { const result = await resolveSavedObjectsImportErrors({ readStream, objectLimit: 4, - retries: savedObjects.map(obj => ({ + retries: savedObjects.map((obj) => ({ type: obj.type, id: obj.id, overwrite: false, @@ -495,7 +495,7 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push({ id: '1', type: 'wigwags', attributes: { title: 'my title' }, references: [] }); this.push(null); }, @@ -540,12 +540,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'index-pattern' && obj.id === '1'), + saved_objects: savedObjects.filter((obj) => obj.type === 'index-pattern' && obj.id === '1'), }); const result = await resolveSavedObjectsImportErrors({ readStream, diff --git a/src/core/server/saved_objects/import/resolve_import_errors.ts b/src/core/server/saved_objects/import/resolve_import_errors.ts index d9ac567882573..a5175aa080598 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.ts @@ -99,7 +99,7 @@ export async function resolveSavedObjectsImportErrors({ ...errorAccumulator, ...extractErrors(bulkCreateResult.saved_objects, objectsToOverwrite), ]; - successCount += bulkCreateResult.saved_objects.filter(obj => !obj.error).length; + successCount += bulkCreateResult.saved_objects.filter((obj) => !obj.error).length; } if (objectsToNotOverwrite.length) { const bulkCreateResult = await savedObjectsClient.bulkCreate(objectsToNotOverwrite, { @@ -109,7 +109,7 @@ export async function resolveSavedObjectsImportErrors({ ...errorAccumulator, ...extractErrors(bulkCreateResult.saved_objects, objectsToNotOverwrite), ]; - successCount += bulkCreateResult.saved_objects.filter(obj => !obj.error).length; + successCount += bulkCreateResult.saved_objects.filter((obj) => !obj.error).length; } return { diff --git a/src/core/server/saved_objects/import/split_overwrites.ts b/src/core/server/saved_objects/import/split_overwrites.ts index 192d43e9edb24..be55e049a2bfc 100644 --- a/src/core/server/saved_objects/import/split_overwrites.ts +++ b/src/core/server/saved_objects/import/split_overwrites.ts @@ -24,8 +24,8 @@ export function splitOverwrites(savedObjects: SavedObject[], retries: SavedObjec const objectsToOverwrite: SavedObject[] = []; const objectsToNotOverwrite: SavedObject[] = []; const overwrites = retries - .filter(retry => retry.overwrite) - .map(retry => `${retry.type}:${retry.id}`); + .filter((retry) => retry.overwrite) + .map((retry) => `${retry.type}:${retry.id}`); for (const savedObject of savedObjects) { if (overwrites.includes(`${savedObject.type}:${savedObject.id}`)) { diff --git a/src/core/server/saved_objects/import/validate_references.ts b/src/core/server/saved_objects/import/validate_references.ts index f0c033c1d00b4..2a30dcc96c08a 100644 --- a/src/core/server/saved_objects/import/validate_references.ts +++ b/src/core/server/saved_objects/import/validate_references.ts @@ -50,12 +50,12 @@ export async function getNonExistingReferenceAsKeys( } // Fetch references to see if they exist - const bulkGetOpts = Array.from(collector.values()).map(obj => ({ ...obj, fields: ['id'] })); + const bulkGetOpts = Array.from(collector.values()).map((obj) => ({ ...obj, fields: ['id'] })); const bulkGetResponse = await savedObjectsClient.bulkGet(bulkGetOpts, { namespace }); // Error handling const erroredObjects = bulkGetResponse.saved_objects.filter( - obj => obj.error && obj.error.statusCode !== 404 + (obj) => obj.error && obj.error.statusCode !== 404 ); if (erroredObjects.length) { const err = Boom.badRequest(); @@ -89,7 +89,7 @@ export async function validateReferences( ); // Filter out objects with missing references, add to error object - let filteredObjects = savedObjects.filter(savedObject => { + let filteredObjects = savedObjects.filter((savedObject) => { const missingReferences = []; const enforcedTypeReferences = (savedObject.references || []).filter( filterReferencesToValidate @@ -117,7 +117,7 @@ export async function validateReferences( // Filter out objects that reference objects within the import but are missing_references // For example: visualization referencing a search that is missing an index pattern needs to be filtered out - filteredObjects = filteredObjects.filter(savedObject => { + filteredObjects = filteredObjects.filter((savedObject) => { let isBlocked = false; for (const reference of savedObject.references || []) { const referencedObjectError = errorMap[`${reference.type}:${reference.id}`]; diff --git a/src/core/server/saved_objects/mappings/lib/get_types.ts b/src/core/server/saved_objects/mappings/lib/get_types.ts index d77d48f410ae0..66d54aede365b 100644 --- a/src/core/server/saved_objects/mappings/lib/get_types.ts +++ b/src/core/server/saved_objects/mappings/lib/get_types.ts @@ -23,5 +23,5 @@ import { IndexMapping } from '../types'; * Get the names of the types defined in the EsMappingsDsl */ export function getTypes(mappings: IndexMapping) { - return Object.keys(mappings).filter(type => type !== '_default_'); + return Object.keys(mappings).filter((type) => type !== '_default_'); } diff --git a/src/core/server/saved_objects/migrations/core/build_active_mappings.ts b/src/core/server/saved_objects/migrations/core/build_active_mappings.ts index 418ed95f14e05..c2a7b11e057cd 100644 --- a/src/core/server/saved_objects/migrations/core/build_active_mappings.ts +++ b/src/core/server/saved_objects/migrations/core/build_active_mappings.ts @@ -76,10 +76,7 @@ export function diffMappings(actual: IndexMapping, expected: IndexMapping) { // Convert an object to an md5 hash string, using a stable serialization (canonicalStringify) function md5Object(obj: any) { - return crypto - .createHash('md5') - .update(canonicalStringify(obj)) - .digest('hex'); + return crypto.createHash('md5').update(canonicalStringify(obj)).digest('hex'); } // JSON.stringify is non-canonical, meaning the same object may produce slightly @@ -106,7 +103,7 @@ function canonicalStringify(obj: any): string { const sortedObj = keys .sort((a, b) => a.localeCompare(b)) - .map(k => `${k}: ${canonicalStringify(obj[k])}`); + .map((k) => `${k}: ${canonicalStringify(obj[k])}`); return `{${sortedObj}}`; } @@ -120,7 +117,7 @@ function md5Values(obj: any) { // care, as it could be a disabled plugin, etc, and keeping stale stuff // around is better than migrating unecessesarily. function findChangedProp(actual: any, expected: any) { - return Object.keys(expected).find(k => actual[k] !== expected[k]); + return Object.keys(expected).find((k) => actual[k] !== expected[k]); } /** @@ -170,7 +167,7 @@ function validateAndMerge( dest: SavedObjectsMappingProperties, source: SavedObjectsTypeMappingDefinitions | SavedObjectsMappingProperties ) { - Object.keys(source).forEach(k => { + Object.keys(source).forEach((k) => { if (k.startsWith('_')) { throw new Error(`Invalid mapping "${k}". Mappings cannot start with _.`); } diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts index 2c710d4eaa079..031d63a565e88 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts @@ -23,7 +23,7 @@ import { SavedObjectsType } from '../../types'; const createRegistry = (...types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', namespaceType: 'single', diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.ts b/src/core/server/saved_objects/migrations/core/build_index_map.ts index 8f7fe2f8eac5b..0848fcf56d9fb 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.ts @@ -38,7 +38,7 @@ export interface IndexMap { */ export function createIndexMap({ kibanaIndexName, registry, indexMap }: CreateIndexMapOptions) { const map: IndexMap = {}; - Object.keys(indexMap).forEach(type => { + Object.keys(indexMap).forEach((type) => { const typeDef = registry.getType(type); const script = typeDef?.convertToAliasScript; // Defaults to kibanaIndexName if indexPattern isn't defined diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts index bd10520ca1c57..a364710322524 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts @@ -29,7 +29,7 @@ const mockLogger = mockLoggerFactory.get('mock logger'); const createRegistry = (...types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', namespaceType: 'single', @@ -73,7 +73,7 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'foo', migrations: { - bar: doc => doc, + bar: (doc) => doc, }, }), validateDoc: _.noop, @@ -131,7 +131,7 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'user', migrations: { - '1.2.3': doc => { + '1.2.3': (doc) => { _.set(doc, 'attributes.name', 'Mike'); return doc; }, @@ -639,10 +639,10 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'aaa', migrations: { - '2.3.4': d => _.set(d, 'attributes.counter', 42), + '2.3.4': (d) => _.set(d, 'attributes.counter', 42), }, }), - validateDoc: d => { + validateDoc: (d) => { if ((d.attributes as any).counter === 42) { throw new Error('Meaningful!'); } diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.ts b/src/core/server/saved_objects/migrations/core/document_migrator.ts index 07c1da5586107..376f823267ebe 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.ts @@ -183,7 +183,7 @@ function validateMigrationDefinition(registry: ISavedObjectTypeRegistry) { } } - registry.getAllTypes().forEach(type => { + registry.getAllTypes().forEach((type) => { if (type.migrations) { assertObject( type.migrations, @@ -209,7 +209,7 @@ function buildActiveMigrations( ): ActiveMigrations { return typeRegistry .getAllTypes() - .filter(type => type.migrations && Object.keys(type.migrations).length > 0) + .filter((type) => type.migrations && Object.keys(type.migrations).length > 0) .reduce((migrations, type) => { const transforms = Object.entries(type.migrations!) .map(([version, transform]) => ({ @@ -334,7 +334,7 @@ function wrapWithTry( * Finds the first unmigrated property in the specified document. */ function nextUnmigratedProp(doc: SavedObjectUnsanitizedDoc, migrations: ActiveMigrations) { - return props(doc).find(p => { + return props(doc).find((p) => { const latestVersion = propVersion(migrations, p); const docVersion = propVersion(doc, p); @@ -431,7 +431,7 @@ function assertNoDowngrades( } const downgrade = Object.keys(migrationVersion).find( - k => !docVersion.hasOwnProperty(k) || Semver.lt(docVersion[k], migrationVersion[k]) + (k) => !docVersion.hasOwnProperty(k) || Semver.lt(docVersion[k], migrationVersion[k]) ); if (downgrade) { diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index e7621d88f78ee..e87c3e3ff0d64 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -194,7 +194,7 @@ export async function migrationsUpToDate( throw e; } - await new Promise(r => setTimeout(r, 1000)); + await new Promise((r) => setTimeout(r, 1000)); return await migrationsUpToDate(callCluster, index, migrationVersion, retryCount - 1); } @@ -259,7 +259,7 @@ export async function claimAlias( ) { const result = await callCluster('indices.getAlias', { ignore: [404], name: alias }); const aliasInfo = (result as NotFound).status === 404 ? {} : result; - const removeActions = Object.keys(aliasInfo).map(key => ({ remove: { index: key, alias } })); + const removeActions = Object.keys(aliasInfo).map((key) => ({ remove: { index: key, alias } })); await callCluster('indices.updateAliases', { body: { @@ -347,11 +347,11 @@ async function reindex( let completed = false; while (!completed) { - await new Promise(r => setTimeout(r, pollInterval)); + await new Promise((r) => setTimeout(r, pollInterval)); completed = await callCluster('tasks.get', { taskId: task, - }).then(result => { + }).then((result) => { if (result.error) { const e = result.error; throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts index 19208e6c83596..392089c69f5a0 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts @@ -341,7 +341,7 @@ function withIndex(callCluster: jest.Mock, opts: any = {}) { let scrollCallCounter = 1; - callCluster.mockImplementation(method => { + callCluster.mockImplementation((method) => { if (method === 'indices.get') { return Promise.resolve(index); } else if (method === 'indices.getAlias') { diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.ts b/src/core/server/saved_objects/migrations/core/index_migrator.ts index ef2a8870d78d0..b2ffe2ad04a88 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.ts @@ -153,11 +153,11 @@ async function deleteIndexTemplates({ callCluster, log, obsoleteIndexTemplatePat return; } - const templateNames = templates.map(t => t.name); + const templateNames = templates.map((t) => t.name); log.info(`Removing index templates: ${templateNames}`); - return Promise.all(templateNames.map(name => callCluster('indices.deleteTemplate', { name }))); + return Promise.all(templateNames.map((name) => callCluster('indices.deleteTemplate', { name }))); } /** @@ -190,7 +190,7 @@ async function migrateSourceToDest(context: Context) { return; } - log.debug(`Migrating saved objects ${docs.map(d => d._id).join(', ')}`); + log.debug(`Migrating saved objects ${docs.map((d) => d._id).join(', ')}`); await Index.write( callCluster, diff --git a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts index 49acea82e1c8a..a2b72ea76c1a2 100644 --- a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts +++ b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts @@ -39,7 +39,7 @@ export function migrateRawDocs( rawDocs: SavedObjectsRawDoc[], log: SavedObjectsMigrationLogger ): SavedObjectsRawDoc[] { - return rawDocs.map(raw => { + return rawDocs.map((raw) => { if (serializer.isRawSavedObject(raw)) { const savedObject = serializer.rawToSavedObject(raw); savedObject.migrationVersion = savedObject.migrationVersion || {}; diff --git a/src/core/server/saved_objects/migrations/core/migration_coordinator.ts b/src/core/server/saved_objects/migrations/core/migration_coordinator.ts index 5ba2d0afc692e..2e32763f4e637 100644 --- a/src/core/server/saved_objects/migrations/core/migration_coordinator.ts +++ b/src/core/server/saved_objects/migrations/core/migration_coordinator.ts @@ -123,5 +123,5 @@ async function waitForMigration( } function sleep(ms: number) { - return new Promise(r => setTimeout(r, ms)); + return new Promise((r) => setTimeout(r, ms)); } diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts index 3f5c0c3876615..fae33bc050dee 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts @@ -65,7 +65,7 @@ const createMigrator = ( }; mockMigrator.getActiveMappings.mockReturnValue(buildActiveMappings(mergeTypes(types))); - mockMigrator.migrateDocument.mockImplementation(doc => doc); + mockMigrator.migrateDocument.mockImplementation((doc) => doc); return mockMigrator; }; diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts index cda0e86f15bdf..7a5c044924d0e 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts @@ -25,7 +25,7 @@ import { SavedObjectsType } from '../../types'; const createRegistry = (types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', hidden: false, @@ -77,7 +77,7 @@ describe('KibanaMigrator', () => { // and should only be done once const callClusterCommands = clusterStub.mock.calls .map(([callClusterPath]) => callClusterPath) - .filter(callClusterPath => callClusterPath === 'cat.templates'); + .filter((callClusterPath) => callClusterPath === 'cat.templates'); expect(callClusterCommands.length).toBe(1); }); @@ -87,10 +87,7 @@ describe('KibanaMigrator', () => { options.callCluster = clusterStub; const migrator = new KibanaMigrator(options); - const migratorStatus = migrator - .getStatus$() - .pipe(take(3)) - .toPromise(); + const migratorStatus = migrator.getStatus$().pipe(take(3)).toPromise(); await migrator.runMigrations(); const { status, result } = await migratorStatus; expect(status).toEqual('completed'); diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts index 7d9ff9bed6d72..4f69d45c192e9 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts @@ -125,7 +125,7 @@ export class KibanaMigrator { > { if (this.migrationResult === undefined || rerun) { this.status$.next({ status: 'running' }); - this.migrationResult = this.runMigrationsInternal().then(result => { + this.migrationResult = this.runMigrationsInternal().then((result) => { this.status$.next({ status: 'completed', result }); return result; }); @@ -146,7 +146,7 @@ export class KibanaMigrator { registry: this.typeRegistry, }); - const migrators = Object.keys(indexMap).map(index => { + const migrators = Object.keys(indexMap).map((index) => { return new IndexMigrator({ batchSize: this.savedObjectsConfig.batchSize, callCluster: this.callCluster, @@ -164,7 +164,7 @@ export class KibanaMigrator { }); }); - return Promise.all(migrators.map(migrator => migrator.migrate())); + return Promise.all(migrators.map((migrator) => migrator.migrate())); } /** diff --git a/src/core/server/saved_objects/migrations/mocks.ts b/src/core/server/saved_objects/migrations/mocks.ts index 50a7191393472..1c4e55566b61b 100644 --- a/src/core/server/saved_objects/migrations/mocks.ts +++ b/src/core/server/saved_objects/migrations/mocks.ts @@ -20,7 +20,9 @@ import { SavedObjectMigrationContext } from './types'; import { SavedObjectsMigrationLogger } from './core'; -export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked => { +export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked< + SavedObjectsMigrationLogger +> => { const mock = { debug: jest.fn(), info: jest.fn(), diff --git a/src/core/server/saved_objects/routes/export.ts b/src/core/server/saved_objects/routes/export.ts index 7205699ddc702..9445c144ecda4 100644 --- a/src/core/server/saved_objects/routes/export.ts +++ b/src/core/server/saved_objects/routes/export.ts @@ -61,7 +61,7 @@ export const registerExportRoute = (router: IRouter, config: SavedObjectConfig) // need to access the registry for type validation, can't use the schema for this const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(t => t.name); + .map((t) => t.name); if (types) { const validationError = validateTypes(types, supportedTypes); if (validationError) { diff --git a/src/core/server/saved_objects/routes/import.ts b/src/core/server/saved_objects/routes/import.ts index 0731d4159356d..8fce6f49fb850 100644 --- a/src/core/server/saved_objects/routes/import.ts +++ b/src/core/server/saved_objects/routes/import.ts @@ -63,7 +63,7 @@ export const registerImportRoute = (router: IRouter, config: SavedObjectConfig) const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(type => type.name); + .map((type) => type.name); const result = await importSavedObjectsFromStream({ supportedTypes, diff --git a/src/core/server/saved_objects/routes/integration_tests/export.test.ts b/src/core/server/saved_objects/routes/integration_tests/export.test.ts index 858d34d5a93bf..bdb2e23f0826d 100644 --- a/src/core/server/saved_objects/routes/integration_tests/export.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/export.test.ts @@ -98,7 +98,7 @@ describe('POST /api/saved_objects/_export', () => { }) ); - const objects = (result.text as string).split('\n').map(row => JSON.parse(row)); + const objects = (result.text as string).split('\n').map((row) => JSON.parse(row)); expect(objects).toEqual(sortedObjects); expect(exportSavedObjectsToStream.mock.calls[0][0]).toEqual( expect.objectContaining({ diff --git a/src/core/server/saved_objects/routes/integration_tests/find.test.ts b/src/core/server/saved_objects/routes/integration_tests/find.test.ts index 907bf44c7748f..7916100e46831 100644 --- a/src/core/server/saved_objects/routes/integration_tests/find.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/find.test.ts @@ -129,9 +129,7 @@ describe('GET /api/saved_objects/_find', () => { }); it('accepts the optional query parameter has_reference', async () => { - await supertest(httpSetup.server.listener) - .get('/api/saved_objects/_find?type=foo') - .expect(200); + await supertest(httpSetup.server.listener).get('/api/saved_objects/_find?type=foo').expect(200); expect(savedObjectsClient.find).toHaveBeenCalledTimes(1); diff --git a/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts b/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts index 928d17e7e5be2..5bc7d126ace03 100644 --- a/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts @@ -35,27 +35,18 @@ describe('SavedObjects /_migrate endpoint', () => { }); it('calls runMigrations on the migrator with rerun=true when accessed', async () => { - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledWith({ rerun: true }); }); it('calls runMigrations multiple time when multiple access', async () => { - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(2); }); diff --git a/src/core/server/saved_objects/routes/resolve_import_errors.ts b/src/core/server/saved_objects/routes/resolve_import_errors.ts index 05bff871b3520..3458e601e0fe6 100644 --- a/src/core/server/saved_objects/routes/resolve_import_errors.ts +++ b/src/core/server/saved_objects/routes/resolve_import_errors.ts @@ -74,7 +74,7 @@ export const registerResolveImportErrorsRoute = (router: IRouter, config: SavedO const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(type => type.name); + .map((type) => type.name); const result = await resolveSavedObjectsImportErrors({ supportedTypes, diff --git a/src/core/server/saved_objects/routes/utils.ts b/src/core/server/saved_objects/routes/utils.ts index 5f0db3c4d548c..3963833a9c718 100644 --- a/src/core/server/saved_objects/routes/utils.ts +++ b/src/core/server/saved_objects/routes/utils.ts @@ -37,13 +37,13 @@ export function createSavedObjectsStreamFromNdJson(ndJsonStream: Readable) { ) .pipe( createFilterStream( - obj => !!obj && !(obj as SavedObjectsExportResultDetails).exportedCount + (obj) => !!obj && !(obj as SavedObjectsExportResultDetails).exportedCount ) ); } export function validateTypes(types: string[], supportedTypes: string[]): string | undefined { - const invalidTypes = types.filter(t => !supportedTypes.includes(t)); + const invalidTypes = types.filter((t) => !supportedTypes.includes(t)); if (invalidTypes.length) { return `Trying to export non-exportable type(s): ${invalidTypes.join(', ')}`; } @@ -53,10 +53,10 @@ export function validateObjects( objects: Array<{ id: string; type: string }>, supportedTypes: string[] ): string | undefined { - const invalidObjects = objects.filter(obj => !supportedTypes.includes(obj.type)); + const invalidObjects = objects.filter((obj) => !supportedTypes.includes(obj.type)); if (invalidObjects.length) { return `Trying to export object(s) with non-exportable types: ${invalidObjects - .map(obj => `${obj.type}:${obj.id}`) + .map((obj) => `${obj.type}:${obj.id}`) .join(', ')}`; } } diff --git a/src/core/server/saved_objects/saved_objects_service.test.ts b/src/core/server/saved_objects/saved_objects_service.test.ts index 7dea7a017a47d..bff392e8761eb 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -46,7 +46,7 @@ describe('SavedObjectsService', () => { env, }: { skipMigration?: boolean; env?: Env } = {}) => { const configService = configServiceMock.create({ atPath: { skip: true } }); - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { if (path === 'migrations') { return new BehaviorSubject({ skip: skipMigration }); } @@ -192,7 +192,7 @@ describe('SavedObjectsService', () => { expect(migratorInstanceMock.runMigrations).not.toHaveBeenCalled(); }); - it('waits for all es nodes to be compatible before running migrations', async done => { + it('waits for all es nodes to be compatible before running migrations', async (done) => { expect.assertions(2); const coreContext = createCoreContext({ skipMigration: false }); const soService = new SavedObjectsService(coreContext); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index 373b8bd1d2bc6..a822a92acb91a 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -310,7 +310,7 @@ export class SavedObjectsService setupDeps.legacyPlugins.uiExports, setupDeps.legacyPlugins.pluginExtendedConfig ); - legacyTypes.forEach(type => this.typeRegistry.registerType(type)); + legacyTypes.forEach((type) => this.typeRegistry.registerType(type)); this.validations = setupDeps.legacyPlugins.uiExports.savedObjectValidations || {}; const savedObjectsConfig = await this.coreContext.configService @@ -332,10 +332,10 @@ export class SavedObjectsService return { status$: calculateStatus$( - this.migrator$.pipe(switchMap(migrator => migrator.getStatus$())), + this.migrator$.pipe(switchMap((migrator) => migrator.getStatus$())), setupDeps.elasticsearch.status$ ), - setClientFactoryProvider: provider => { + setClientFactoryProvider: (provider) => { if (this.started) { throw new Error('cannot call `setClientFactoryProvider` after service startup.'); } @@ -354,7 +354,7 @@ export class SavedObjectsService factory, }); }, - registerType: type => { + registerType: (type) => { if (this.started) { throw new Error('cannot call `registerType` after service startup.'); } @@ -415,7 +415,7 @@ export class SavedObjectsService }); await this.setupDeps!.elasticsearch.esNodesCompatibility$.pipe( - filter(nodes => nodes.isCompatible), + filter((nodes) => nodes.isCompatible), take(1) ).toPromise(); diff --git a/src/core/server/saved_objects/saved_objects_type_registry.mock.ts b/src/core/server/saved_objects/saved_objects_type_registry.mock.ts index 8bb66859feca2..5636dcadb444e 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.mock.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.mock.ts @@ -19,8 +19,9 @@ import { ISavedObjectTypeRegistry, SavedObjectTypeRegistry } from './saved_objects_type_registry'; -const createRegistryMock = (): jest.Mocked> => { +const createRegistryMock = (): jest.Mocked< + ISavedObjectTypeRegistry & Pick +> => { const mock = { registerType: jest.fn(), getType: jest.fn(), diff --git a/src/core/server/saved_objects/saved_objects_type_registry.test.ts b/src/core/server/saved_objects/saved_objects_type_registry.test.ts index f82822f90f489..e0f4d6fa28e50 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.test.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.test.ts @@ -44,7 +44,7 @@ describe('SavedObjectTypeRegistry', () => { expect( registry .getAllTypes() - .map(type => type.name) + .map((type) => type.name) .sort() ).toEqual(['typeA', 'typeB', 'typeC']); }); @@ -300,7 +300,7 @@ describe('SavedObjectTypeRegistry', () => { const types = registry.getImportableAndExportableTypes(); expect(types.length).toEqual(2); - expect(types.map(t => t.name)).toEqual(['typeA', 'typeD']); + expect(types.map((t) => t.name)).toEqual(['typeA', 'typeD']); }); }); }); diff --git a/src/core/server/saved_objects/saved_objects_type_registry.ts b/src/core/server/saved_objects/saved_objects_type_registry.ts index 740313a53d1e2..99262d7a31e21 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.ts @@ -64,7 +64,7 @@ export class SavedObjectTypeRegistry { * Return all {@link SavedObjectsType | types} currently registered that are importable/exportable. */ public getImportableAndExportableTypes() { - return this.getAllTypes().filter(type => this.isImportableAndExportable(type.name)); + return this.getAllTypes().filter((type) => this.isImportableAndExportable(type.name)); } /** diff --git a/src/core/server/saved_objects/service/lib/filter_utils.ts b/src/core/server/saved_objects/service/lib/filter_utils.ts index 55859f7108b26..4c31f37f63dad 100644 --- a/src/core/server/saved_objects/service/lib/filter_utils.ts +++ b/src/core/server/saved_objects/service/lib/filter_utils.ts @@ -48,22 +48,22 @@ export const validateConvertFilterToKueryNode = ( ); } - if (validationFilterKuery.some(obj => obj.error != null)) { + if (validationFilterKuery.some((obj) => obj.error != null)) { throw SavedObjectsErrorHelpers.createBadRequestError( validationFilterKuery - .filter(obj => obj.error != null) - .map(obj => obj.error) + .filter((obj) => obj.error != null) + .map((obj) => obj.error) .join('\n') ); } - validationFilterKuery.forEach(item => { + validationFilterKuery.forEach((item) => { const path: string[] = item.astPath.length === 0 ? [] : item.astPath.split('.'); const existingKueryNode: KueryNode = path.length === 0 ? filterKueryNode : get(filterKueryNode, path); if (item.isSavedObjectAttr) { existingKueryNode.arguments[0].value = existingKueryNode.arguments[0].value.split('.')[1]; - const itemType = allowedTypes.filter(t => t === item.type); + const itemType = allowedTypes.filter((t) => t === item.type); if (itemType.length === 1) { set( filterKueryNode, diff --git a/src/core/server/saved_objects/service/lib/included_fields.ts b/src/core/server/saved_objects/service/lib/included_fields.ts index c50ac22594008..33bca49e3fc58 100644 --- a/src/core/server/saved_objects/service/lib/included_fields.ts +++ b/src/core/server/saved_objects/service/lib/included_fields.ts @@ -34,7 +34,7 @@ export function includedFields(type: string | string[] = '*', fields?: string[] return sourceType .reduce((acc: string[], t) => { - return [...acc, ...sourceFields.map(f => `${t}.${f}`)]; + return [...acc, ...sourceFields.map((f) => `${t}.${f}`)]; }, []) .concat('namespace') .concat('namespaces') diff --git a/src/core/server/saved_objects/service/lib/priority_collection.test.ts b/src/core/server/saved_objects/service/lib/priority_collection.test.ts index 13180b912e7d7..62f9415927db9 100644 --- a/src/core/server/saved_objects/service/lib/priority_collection.test.ts +++ b/src/core/server/saved_objects/service/lib/priority_collection.test.ts @@ -64,6 +64,6 @@ test(`#has when empty returns false`, () => { test(`#has returns result of predicate`, () => { const priorityCollection = new PriorityCollection(); priorityCollection.add(1, 'foo'); - expect(priorityCollection.has(val => val === 'foo')).toEqual(true); - expect(priorityCollection.has(val => val === 'bar')).toEqual(false); + expect(priorityCollection.has((val) => val === 'foo')).toEqual(true); + expect(priorityCollection.has((val) => val === 'bar')).toEqual(false); }); diff --git a/src/core/server/saved_objects/service/lib/priority_collection.ts b/src/core/server/saved_objects/service/lib/priority_collection.ts index a2fe13b933347..350d549b7e8f2 100644 --- a/src/core/server/saved_objects/service/lib/priority_collection.ts +++ b/src/core/server/saved_objects/service/lib/priority_collection.ts @@ -26,7 +26,7 @@ export class PriorityCollection { private readonly array: Array> = []; public add(priority: number, value: T) { - const foundIndex = this.array.findIndex(current => { + const foundIndex = this.array.findIndex((current) => { if (priority === current.priority) { throw new Error('Already have entry with this priority'); } @@ -39,10 +39,10 @@ export class PriorityCollection { } public has(predicate: (value: T) => boolean): boolean { - return this.array.some(entry => predicate(entry.value)); + return this.array.some((entry) => predicate(entry.value)); } public toPrioritizedArray(): T[] { - return this.array.map(entry => entry.value); + return this.array.map((entry) => entry.value); } } diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index c46fcfbc6dbd7..83e037fb2da66 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -113,10 +113,10 @@ describe('SavedObjectsRepository', () => { }, }; - const createType = type => ({ + const createType = (type) => ({ name: type, mappings: { properties: mappings.properties[type].properties }, - migrations: { '1.1.1': doc => doc }, + migrations: { '1.1.1': (doc) => doc }, }); const registry = new SavedObjectTypeRegistry(); @@ -171,7 +171,7 @@ describe('SavedObjectsRepository', () => { const getMockMgetResponse = (objects, namespace) => ({ status: 200, - docs: objects.map(obj => + docs: objects.map((obj) => obj.found === false ? obj : getMockGetResponse({ ...obj, namespace }) ), }); @@ -202,10 +202,11 @@ describe('SavedObjectsRepository', () => { const expectSuccess = ({ type, id }) => expect.toBeDocumentWithoutError(type, id); const expectError = ({ type, id }) => ({ type, id, error: expect.any(Object) }); const expectErrorResult = ({ type, id }, error) => ({ type, id, error }); - const expectErrorNotFound = obj => + const expectErrorNotFound = (obj) => expectErrorResult(obj, createGenericNotFoundError(obj.type, obj.id)); - const expectErrorConflict = obj => expectErrorResult(obj, createConflictError(obj.type, obj.id)); - const expectErrorInvalidType = obj => + const expectErrorConflict = (obj) => + expectErrorResult(obj, createConflictError(obj.type, obj.id)); + const expectErrorInvalidType = (obj) => expectErrorResult(obj, createUnsupportedTypeError(obj.type, obj.id)); const expectMigrationArgs = (args, contains = true, n = 1) => { @@ -229,12 +230,12 @@ describe('SavedObjectsRepository', () => { trimIdPrefix: jest.fn(), }; const _serializer = new SavedObjectsSerializer(registry); - Object.keys(serializer).forEach(key => { + Object.keys(serializer).forEach((key) => { serializer[key].mockImplementation((...args) => _serializer[key](...args)); }); - const allTypes = registry.getAllTypes().map(type => type.name); - const allowedTypes = [...new Set(allTypes.filter(type => !registry.isHidden(type)))]; + const allTypes = registry.getAllTypes().map((type) => type.name); + const allowedTypes = [...new Set(allTypes.filter((type) => !registry.isHidden(type)))]; savedObjectsRepository = new SavedObjectsRepository({ index: '.kibana-test', @@ -251,7 +252,7 @@ describe('SavedObjectsRepository', () => { }); const mockMigrationVersion = { foo: '2.3.4' }; - const mockMigrateDocument = doc => ({ + const mockMigrateDocument = (doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -345,7 +346,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is not multi-namespace`, async () => { - const test = async type => { + const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [newNs1, newNs2], message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -355,7 +356,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when namespaces is an empty array`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -489,7 +490,7 @@ describe('SavedObjectsRepository', () => { }), ]; - const expectSuccessResult = obj => ({ + const expectSuccessResult = (obj) => ({ ...obj, migrationVersion: { [obj.type]: '1.1.1' }, version: mockVersion, @@ -511,13 +512,13 @@ describe('SavedObjectsRepository', () => { }); it(`should use the ES create method if ID is undefined and overwrite=true`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, id: undefined })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects, { overwrite: true }); expectClusterCallArgsAction(objects, { method: 'create' }); }); it(`should use the ES create method if ID is undefined and overwrite=false`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, id: undefined })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects); expectClusterCallArgsAction(objects, { method: 'create' }); }); @@ -557,8 +558,8 @@ describe('SavedObjectsRepository', () => { }); it(`adds namespaces to request body for any types that are multi-namespace`, async () => { - const test = async namespace => { - const objects = [obj1, obj2].map(x => ({ ...x, type: MULTI_NAMESPACE_TYPE })); + const test = async (namespace) => { + const objects = [obj1, obj2].map((x) => ({ ...x, type: MULTI_NAMESPACE_TYPE })); const namespaces = [namespace ?? 'default']; await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.objectContaining({ namespaces }); @@ -571,7 +572,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't add namespaces to request body for any types that are not multi-namespace`, async () => { - const test = async namespace => { + const test = async (namespace) => { const objects = [obj1, { ...obj2, type: NAMESPACE_AGNOSTIC_TYPE }]; await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.not.objectContaining({ namespaces: expect.anything() }); @@ -600,7 +601,7 @@ describe('SavedObjectsRepository', () => { }); it(`should use custom index`, async () => { - await bulkCreateSuccess([obj1, obj2].map(x => ({ ...x, type: CUSTOM_INDEX_TYPE }))); + await bulkCreateSuccess([obj1, obj2].map((x) => ({ ...x, type: CUSTOM_INDEX_TYPE }))); expectClusterCallArgsAction([obj1, obj2], { method: 'create', _index: 'custom' }); }); @@ -730,11 +731,11 @@ describe('SavedObjectsRepository', () => { it(`migrates the docs and serializes the migrated docs`, async () => { migrator.migrateDocument.mockImplementation(mockMigrateDocument); await bulkCreateSuccess([obj1, obj2]); - const docs = [obj1, obj2].map(x => ({ ...x, ...mockTimestampFields })); + const docs = [obj1, obj2].map((x) => ({ ...x, ...mockTimestampFields })); expectMigrationArgs(docs[0], true, 1); expectMigrationArgs(docs[1], true, 2); - const migratedDocs = docs.map(x => migrator.migrateDocument(x)); + const migratedDocs = docs.map((x) => migrator.migrateDocument(x)); expect(serializer.savedObjectToRaw).toHaveBeenNthCalledWith(1, migratedDocs[0]); expect(serializer.savedObjectToRaw).toHaveBeenNthCalledWith(2, migratedDocs[1]); }); @@ -762,14 +763,14 @@ describe('SavedObjectsRepository', () => { }); it(`adds namespaces to body when providing namespace for multi-namespace type`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkCreateSuccess(objects, { namespace }); expectMigrationArgs({ namespaces: [namespace] }, true, 1); expectMigrationArgs({ namespaces: [namespace] }, true, 2); }); it(`adds default namespaces to body when providing no namespace for multi-namespace type`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkCreateSuccess(objects); expectMigrationArgs({ namespaces: ['default'] }, true, 1); expectMigrationArgs({ namespaces: ['default'] }, true, 2); @@ -787,7 +788,7 @@ describe('SavedObjectsRepository', () => { it(`formats the ES response`, async () => { const result = await bulkCreateSuccess([obj1, obj2]); expect(result).toEqual({ - saved_objects: [obj1, obj2].map(x => expectSuccessResult(x)), + saved_objects: [obj1, obj2].map((x) => expectSuccessResult(x)), }); }); @@ -909,12 +910,12 @@ describe('SavedObjectsRepository', () => { it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; - let objects = [obj1, obj2].map(obj => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); + let objects = [obj1, obj2].map((obj) => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); await bulkGetSuccess(objects, { namespace }); _expectClusterCallArgs(objects, { getId }); callAdminCluster.mockReset(); - objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkGetSuccess(objects, { namespace }); _expectClusterCallArgs(objects, { getId }); }); @@ -1136,7 +1137,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesnt call Elasticsearch if there are no valid objects to update`, async () => { - const objects = [obj1, obj2].map(x => ({ ...x, type: 'unknownType' })); + const objects = [obj1, obj2].map((x) => ({ ...x, type: 'unknownType' })); await savedObjectsRepository.bulkUpdate(objects); expect(callAdminCluster).toHaveBeenCalledTimes(0); }); @@ -1149,8 +1150,8 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const test = async (references) => { + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); await bulkUpdateSuccess(objects); const expected = { doc: expect.objectContaining({ references }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; @@ -1163,8 +1164,8 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const test = async (references) => { + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); await bulkUpdateSuccess(objects); const expected = { doc: expect.not.objectContaining({ references: expect.anything() }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; @@ -1366,7 +1367,7 @@ describe('SavedObjectsRepository', () => { }); it(`includes references`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); const response = await bulkUpdateSuccess(objects); expect(response).toEqual({ saved_objects: objects.map(expectSuccessResult), @@ -1463,7 +1464,7 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { + const test = async (references) => { await createSuccess(type, attributes, { id, references }); expectClusterCallArgs({ body: expect.objectContaining({ references }), @@ -1476,7 +1477,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { + const test = async (references) => { await createSuccess(type, attributes, { id, references }); expectClusterCallArgs({ body: expect.not.objectContaining({ references: expect.anything() }), @@ -1871,7 +1872,7 @@ describe('SavedObjectsRepository', () => { describe('errors', () => { it(`throws when namespace is not a string`, async () => { - const test = async namespace => { + const test = async (namespace) => { await expect(savedObjectsRepository.deleteByNamespace(namespace)).rejects.toThrowError( `namespace is required, and must be a string` ); @@ -1904,17 +1905,17 @@ describe('SavedObjectsRepository', () => { describe('search dsl', () => { it(`constructs a query using all multi-namespace types, and another using all single-namespace types`, async () => { await deleteByNamespaceSuccess(namespace); - const allTypes = registry.getAllTypes().map(type => type.name); + const allTypes = registry.getAllTypes().map((type) => type.name); expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledWith(mappings, registry, { namespace, - type: allTypes.filter(type => !registry.isNamespaceAgnostic(type)), + type: allTypes.filter((type) => !registry.isNamespaceAgnostic(type)), }); }); }); }); describe('#find', () => { - const generateSearchResults = namespace => { + const generateSearchResults = (namespace) => { return { hits: { total: 4, @@ -2038,7 +2039,7 @@ describe('SavedObjectsRepository', () => { }); it(`should not make a cluster call when attempting to find only invalid or hidden types`, async () => { - const test = async types => { + const test = async (types) => { await savedObjectsRepository.find({ type: types }); expect(callAdminCluster).not.toHaveBeenCalled(); }; @@ -2154,7 +2155,7 @@ describe('SavedObjectsRepository', () => { }); it(`should return empty results when attempting to find only invalid or hidden types`, async () => { - const test = async types => { + const test = async (types) => { const result = await savedObjectsRepository.find({ type: types }); expect(result).toEqual(expect.objectContaining({ saved_objects: [] })); }; @@ -2468,7 +2469,7 @@ describe('SavedObjectsRepository', () => { }; it(`throws when type is not a string`, async () => { - const test = async type => { + const test = async (type) => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"type" argument must be a string`); @@ -2482,7 +2483,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when counterFieldName is not a string`, async () => { - const test = async field => { + const test = async (field) => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"counterFieldName" argument must be a string`); @@ -2610,7 +2611,7 @@ describe('SavedObjectsRepository', () => { options ) => { mockGetResponse(type, id, currentNamespaces); // this._callCluster('get', ...) - const isDelete = currentNamespaces.every(namespace => namespaces.includes(namespace)); + const isDelete = currentNamespaces.every((namespace) => namespaces.includes(namespace)); callAdminCluster.mockResolvedValue({ _id: `${type}:${id}`, ...mockVersionProps, @@ -2629,7 +2630,7 @@ describe('SavedObjectsRepository', () => { describe('cluster calls', () => { describe('delete action', () => { const deleteFromNamespacesSuccessDelete = async (expectFn, options, _type = type) => { - const test = async namespaces => { + const test = async (namespaces) => { await deleteFromNamespacesSuccess(_type, id, namespaces, namespaces, options); expectFn(); callAdminCluster.mockReset(); @@ -2680,7 +2681,7 @@ describe('SavedObjectsRepository', () => { describe('update action', () => { const deleteFromNamespacesSuccessUpdate = async (expectFn, options, _type = type) => { - const test = async remaining => { + const test = async (remaining) => { const currentNamespaces = [namespace1].concat(remaining); await deleteFromNamespacesSuccess(_type, id, [namespace1], currentNamespaces, options); expectFn(); @@ -2761,7 +2762,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is not namespace-agnostic`, async () => { - const test = async type => { + const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [namespace1, namespace2], message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -2771,7 +2772,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when namespaces is an empty array`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -2844,7 +2845,7 @@ describe('SavedObjectsRepository', () => { describe('returns', () => { it(`returns an empty object on success (delete)`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const result = await deleteFromNamespacesSuccess(type, id, namespaces, namespaces); expect(result).toEqual({}); callAdminCluster.mockReset(); @@ -2854,7 +2855,7 @@ describe('SavedObjectsRepository', () => { }); it(`returns an empty object on success (update)`, async () => { - const test = async remaining => { + const test = async (remaining) => { const currentNamespaces = [namespace1].concat(remaining); const result = await deleteFromNamespacesSuccess( type, @@ -2929,7 +2930,7 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { + const test = async (references) => { await updateSuccess(type, id, attributes, { references }); expectClusterCallArgs({ body: { doc: expect.objectContaining({ references }) }, @@ -2942,7 +2943,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { + const test = async (references) => { await updateSuccess(type, id, attributes, { references }); expectClusterCallArgs({ body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index f76b05c4af1b9..e23f8dec5927c 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -138,9 +138,9 @@ export class SavedObjectsRepository { const mappings = migrator.getActiveMappings(); const allTypes = Object.keys(getRootPropertiesObjects(mappings)); const serializer = new SavedObjectsSerializer(typeRegistry); - const visibleTypes = allTypes.filter(type => !typeRegistry.isHidden(type)); + const visibleTypes = allTypes.filter((type) => !typeRegistry.isHidden(type)); - const missingTypeMappings = includedHiddenTypes.filter(type => !allTypes.includes(type)); + const missingTypeMappings = includedHiddenTypes.filter((type) => !allTypes.includes(type)); if (missingTypeMappings.length > 0) { throw new Error( `Missing mappings for saved objects types: '${missingTypeMappings.join(', ')}'` @@ -284,7 +284,7 @@ export class SavedObjectsRepository { const time = this._getCurrentTime(); let bulkGetRequestIndexCounter = 0; - const expectedResults: Either[] = objects.map(object => { + const expectedResults: Either[] = objects.map((object) => { if (!this._allowedTypes.includes(object.type)) { return { tag: 'Left' as 'Left', @@ -331,7 +331,7 @@ export class SavedObjectsRepository { let bulkRequestIndexCounter = 0; const bulkCreateParams: object[] = []; - const expectedBulkResults: Either[] = expectedResults.map(expectedBulkGetResult => { + const expectedBulkResults: Either[] = expectedResults.map((expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { return expectedBulkGetResult; } @@ -401,7 +401,7 @@ export class SavedObjectsRepository { : undefined; return { - saved_objects: expectedBulkResults.map(expectedResult => { + saved_objects: expectedBulkResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -453,7 +453,7 @@ export class SavedObjectsRepository { preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); const existingNamespaces = getSavedObjectNamespaces(undefined, preflightResult); const remainingNamespaces = existingNamespaces?.filter( - x => x !== getNamespaceString(namespace) + (x) => x !== getNamespaceString(namespace) ); if (remainingNamespaces?.length) { @@ -530,7 +530,7 @@ export class SavedObjectsRepository { const { refresh = DEFAULT_REFRESH_SETTING } = options; const allTypes = Object.keys(getRootPropertiesObjects(this._mappings)); - const typesToUpdate = allTypes.filter(type => !this._registry.isNamespaceAgnostic(type)); + const typesToUpdate = allTypes.filter((type) => !this._registry.isNamespaceAgnostic(type)); const updateOptions = { index: this.getIndicesForTypes(typesToUpdate), @@ -599,7 +599,7 @@ export class SavedObjectsRepository { } const types = Array.isArray(type) ? type : [type]; - const allowedTypes = types.filter(t => this._allowedTypes.includes(t)); + const allowedTypes = types.filter((t) => this._allowedTypes.includes(t)); if (allowedTypes.length === 0) { return { page, @@ -702,7 +702,7 @@ export class SavedObjectsRepository { } let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Either[] = objects.map(object => { + const expectedBulkGetResults: Either[] = objects.map((object) => { const { type, id, fields } = object; if (!this._allowedTypes.includes(type)) { @@ -744,7 +744,7 @@ export class SavedObjectsRepository { : undefined; return { - saved_objects: expectedBulkGetResults.map(expectedResult => { + saved_objects: expectedBulkGetResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -981,7 +981,7 @@ export class SavedObjectsRepository { const preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); const existingNamespaces = getSavedObjectNamespaces(undefined, preflightResult); // if there are somehow no existing namespaces, allow the operation to proceed and delete this saved object - const remainingNamespaces = existingNamespaces?.filter(x => !namespaces.includes(x)); + const remainingNamespaces = existingNamespaces?.filter((x) => !namespaces.includes(x)); if (remainingNamespaces?.length) { // if there is 1 or more namespace remaining, update the saved object @@ -1057,7 +1057,7 @@ export class SavedObjectsRepository { const { namespace } = options; let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Either[] = objects.map(object => { + const expectedBulkGetResults: Either[] = objects.map((object) => { const { type, id } = object; if (!this._allowedTypes.includes(type)) { @@ -1113,7 +1113,7 @@ export class SavedObjectsRepository { let bulkUpdateRequestIndexCounter = 0; const bulkUpdateParams: object[] = []; const expectedBulkUpdateResults: Either[] = expectedBulkGetResults.map( - expectedBulkGetResult => { + (expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { return expectedBulkGetResult; } @@ -1173,7 +1173,7 @@ export class SavedObjectsRepository { : {}; return { - saved_objects: expectedBulkUpdateResults.map(expectedResult => { + saved_objects: expectedBulkUpdateResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -1326,7 +1326,7 @@ export class SavedObjectsRepository { * @param types The types whose indices should be retrieved */ private getIndicesForTypes(types: string[]) { - return unique(types.map(t => this.getIndexForType(t))); + return unique(types.map((t) => this.getIndexForType(t))); } private _getCurrentTime() { diff --git a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts index 3250737e1287d..ab80f37e6652f 100644 --- a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts +++ b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts @@ -107,7 +107,7 @@ export class SavedObjectsClientProvider { id: string, factory: SavedObjectsClientWrapperFactory ): void { - if (this._wrapperFactories.has(entry => entry.id === id)) { + if (this._wrapperFactories.has((entry) => entry.id === id)) { throw new Error(`wrapper factory with id ${id} is already defined`); } diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts index a72c21dd5eee4..a0ffa91f53671 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts @@ -43,11 +43,11 @@ const MAPPINGS = { const ALL_TYPES = Object.keys(MAPPINGS.properties); // get all possible subsets (combination) of all types const ALL_TYPE_SUBSETS = ALL_TYPES.reduce( - (subsets, value) => subsets.concat(subsets.map(set => [...set, value])), + (subsets, value) => subsets.concat(subsets.map((set) => [...set, value])), [[] as string[]] ) - .filter(x => x.length) // exclude empty set - .map(x => (x.length === 1 ? x[0] : x)); // if a subset is a single string, destructure it + .filter((x) => x.length) // exclude empty set + .map((x) => (x.length === 1 ? x[0] : x)); // if a subset is a single string, destructure it /** * Note: these tests cases are defined in the order they appear in the source code, for readability's sake @@ -163,7 +163,7 @@ describe('#getQueryParams', () => { expect.arrayContaining([ { bool: expect.objectContaining({ - should: types.map(type => ({ + should: types.map((type) => ({ bool: expect.objectContaining({ must: expect.arrayContaining([{ term: { type } }]), }), @@ -233,11 +233,11 @@ describe('#getQueryParams', () => { for (const typeOrTypes of ALL_TYPE_SUBSETS) { const result = getQueryParams({ mappings, registry, type: typeOrTypes, namespace }); const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; - expectResult(result, ...types.map(x => createTypeClause(x, namespace))); + expectResult(result, ...types.map((x) => createTypeClause(x, namespace))); } // also test with no specified type/s const result = getQueryParams({ mappings, registry, type: undefined, namespace }); - expectResult(result, ...ALL_TYPES.map(x => createTypeClause(x, namespace))); + expectResult(result, ...ALL_TYPES.map((x) => createTypeClause(x, namespace))); }; it('filters results with "namespace" field when `namespace` is not specified', () => { @@ -280,7 +280,7 @@ describe('#getQueryParams', () => { describe('`searchFields` parameter', () => { const getExpectedFields = (searchFields: string[], typeOrTypes: string | string[]) => { const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; - return searchFields.map(x => types.map(y => `${y}.${x}`)).flat(); + return searchFields.map((x) => types.map((y) => `${y}.${x}`)).flat(); }; const test = (searchFields: string[]) => { diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts index 967ce8bceaf84..40485564176a6 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts @@ -51,7 +51,7 @@ function getFieldsForTypes(types: string[], searchFields?: string[]) { let fields: string[] = []; for (const field of searchFields) { - fields = fields.concat(types.map(prefix => `${prefix}.${field}`)); + fields = fields.concat(types.map((prefix) => `${prefix}.${field}`)); } return { fields }; @@ -152,7 +152,7 @@ export function getQueryParams({ }, ] : undefined, - should: types.map(shouldType => getClauseForType(registry, namespace, shouldType)), + should: types.map((shouldType) => getClauseForType(registry, namespace, shouldType)), minimum_should_match: 1, }, }, diff --git a/src/core/server/saved_objects/status.ts b/src/core/server/saved_objects/status.ts index 66a6e2baa17a7..1823fbe95b8ba 100644 --- a/src/core/server/saved_objects/status.ts +++ b/src/core/server/saved_objects/status.ts @@ -28,7 +28,7 @@ export const calculateStatus$ = ( elasticsearchStatus$: Observable ): Observable> => { const migratorStatus$: Observable> = rawMigratorStatus$.pipe( - map(migrationStatus => { + map((migrationStatus) => { if (migrationStatus.status === 'waiting') { return { level: ServiceStatusLevels.unavailable, diff --git a/src/core/server/saved_objects/utils.test.ts b/src/core/server/saved_objects/utils.test.ts index 033aeea7c018d..21229bee489c2 100644 --- a/src/core/server/saved_objects/utils.test.ts +++ b/src/core/server/saved_objects/utils.test.ts @@ -142,7 +142,7 @@ describe('convertLegacyTypes', () => { }); it('invokes indexPattern to retrieve the index when it is a function', () => { - const indexPatternAccessor: (config: LegacyConfig) => string = jest.fn(config => { + const indexPatternAccessor: (config: LegacyConfig) => string = jest.fn((config) => { config.get('foo.bar'); return 'myIndex'; }); @@ -301,13 +301,13 @@ describe('convertLegacyTypes', () => { isImportableAndExportable: true, icon: 'iconA', defaultSearchField: 'searchFieldA', - getTitle: savedObject => savedObject.id, + getTitle: (savedObject) => savedObject.id, }, typeB: { isImportableAndExportable: false, icon: 'iconB', - getEditUrl: savedObject => `/some-url/${savedObject.id}`, - getInAppUrl: savedObject => ({ path: 'path', uiCapabilitiesPath: 'ui-path' }), + getEditUrl: (savedObject) => `/some-url/${savedObject.id}`, + getInAppUrl: (savedObject) => ({ path: 'path', uiCapabilitiesPath: 'ui-path' }), }, }, savedObjectMigrations: {}, @@ -377,7 +377,7 @@ describe('convertLegacyTypes', () => { }, savedObjectSchemas: { typeA: { - indexPattern: jest.fn(config => { + indexPattern: jest.fn((config) => { config.get('foo.bar'); return 'myIndex'; }), diff --git a/src/core/server/saved_objects/validation/index.ts b/src/core/server/saved_objects/validation/index.ts index 98dc6254178c5..b1b33f91d3fd4 100644 --- a/src/core/server/saved_objects/validation/index.ts +++ b/src/core/server/saved_objects/validation/index.ts @@ -57,7 +57,7 @@ export function docValidator(validators: PropertyValidators = {}): ValidateDoc { return function validateDoc(doc: SavedObjectDoc) { Object.keys(doc) .concat(doc.type) - .forEach(prop => { + .forEach((prop) => { const validator = validators[prop]; if (validator) { validator(doc); diff --git a/src/core/server/status/status_service.test.ts b/src/core/server/status/status_service.test.ts index 6d92a266369b9..b692cf3161901 100644 --- a/src/core/server/status/status_service.test.ts +++ b/src/core/server/status/status_service.test.ts @@ -93,7 +93,7 @@ describe('StatusService', () => { }); const statusUpdates: CoreStatus[] = []; - const subscription = setup.core$.subscribe(status => statusUpdates.push(status)); + const subscription = setup.core$.subscribe((status) => statusUpdates.push(status)); elasticsearch$.next(available); elasticsearch$.next(available); @@ -198,7 +198,7 @@ describe('StatusService', () => { }); const statusUpdates: ServiceStatus[] = []; - const subscription = setup.overall$.subscribe(status => statusUpdates.push(status)); + const subscription = setup.overall$.subscribe((status) => statusUpdates.push(status)); elasticsearch$.next(available); elasticsearch$.next(available); diff --git a/src/core/server/status/status_service.ts b/src/core/server/status/status_service.ts index b6697d8221951..ef7bed9587245 100644 --- a/src/core/server/status/status_service.ts +++ b/src/core/server/status/status_service.ts @@ -47,7 +47,7 @@ export class StatusService implements CoreService { public setup(core: SetupDeps) { const core$ = this.setupCoreStatus(core); const overall$: Observable = core$.pipe( - map(coreStatus => { + map((coreStatus) => { const summary = getSummaryStatus(Object.entries(coreStatus)); this.logger.debug(`Recalculated overall status`, { status: summary }); return summary; diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts index eab96cc80c883..9c5a0625e8fd0 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts @@ -27,7 +27,7 @@ import { getUpgradeableConfigMock } from './get_upgradeable_config.test.mock'; import { createOrUpgradeSavedConfig } from './create_or_upgrade_saved_config'; const chance = new Chance(); -describe('uiSettings/createOrUpgradeSavedConfig', function() { +describe('uiSettings/createOrUpgradeSavedConfig', function () { afterEach(() => jest.resetAllMocks()); const version = '4.0.1'; @@ -73,7 +73,7 @@ describe('uiSettings/createOrUpgradeSavedConfig', function() { }; } - describe('nothing is upgradeable', function() { + describe('nothing is upgradeable', function () { it('should create config with current version and buildNum', async () => { const { run, savedObjectsClient } = setup(); diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts index a916d4c3317a6..abf33658db545 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts @@ -43,5 +43,5 @@ export async function getUpgradeableConfig({ }); // try to find a config that we can upgrade - return savedConfigs.find(savedConfig => isConfigVersionUpgradeable(savedConfig.id, version)); + return savedConfigs.find((savedConfig) => isConfigVersionUpgradeable(savedConfig.id, version)); } diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts index 218de8e7acb3a..49d8137a65d39 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts @@ -38,9 +38,9 @@ describe('createOrUpgradeSavedConfig()', () => { let kbnServer: TestKibanaUtils['kbnServer']; - beforeAll(async function() { + beforeAll(async function () { servers = createTestServers({ - adjustTimeout: t => { + adjustTimeout: (t) => { jest.setTimeout(t); }, }); @@ -86,7 +86,7 @@ describe('createOrUpgradeSavedConfig()', () => { await kbn.stop(); }, 30000); - it('upgrades the previous version on each increment', async function() { + it('upgrades the previous version on each increment', async function () { jest.setTimeout(30000); // ------------------------------------ // upgrade to 5.4.0 diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts index feb63817fe073..5d8c4b01d0664 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts @@ -19,7 +19,7 @@ import { isConfigVersionUpgradeable } from './is_config_version_upgradeable'; -describe('savedObjects/health_check/isConfigVersionUpgradeable', function() { +describe('savedObjects/health_check/isConfigVersionUpgradeable', function () { function isUpgradeableTest(savedVersion: string, kibanaVersion: string, expected: boolean) { it(`should return ${expected} for config version ${savedVersion} and kibana version ${kibanaVersion}`, () => { expect(isConfigVersionUpgradeable(savedVersion, kibanaVersion)).toBe(expected); diff --git a/src/core/server/ui_settings/integration_tests/index.test.ts b/src/core/server/ui_settings/integration_tests/index.test.ts index db271761b39ea..e704532ee4cdf 100644 --- a/src/core/server/ui_settings/integration_tests/index.test.ts +++ b/src/core/server/ui_settings/integration_tests/index.test.ts @@ -23,7 +23,7 @@ import { docExistsSuite } from './doc_exists'; import { docMissingSuite } from './doc_missing'; import { docMissingAndIndexReadOnlySuite } from './doc_missing_and_index_read_only'; -describe('uiSettings/routes', function() { +describe('uiSettings/routes', function () { /** * The "doc missing" and "index missing" tests verify how the uiSettings * API behaves in between healthChecks, so they interact with the healthCheck diff --git a/src/core/server/ui_settings/integration_tests/lib/servers.ts b/src/core/server/ui_settings/integration_tests/lib/servers.ts index 57448541d68c5..486abd5a0c790 100644 --- a/src/core/server/ui_settings/integration_tests/lib/servers.ts +++ b/src/core/server/ui_settings/integration_tests/lib/servers.ts @@ -46,7 +46,7 @@ let services: AllServices; export async function startServers() { servers = createTestServers({ - adjustTimeout: t => jest.setTimeout(t), + adjustTimeout: (t) => jest.setTimeout(t), settings: { kbn: { uiSettings: { diff --git a/src/core/server/ui_settings/ui_settings_client.ts b/src/core/server/ui_settings/ui_settings_client.ts index 76c8284175f11..f168784a93330 100644 --- a/src/core/server/ui_settings/ui_settings_client.ts +++ b/src/core/server/ui_settings/ui_settings_client.ts @@ -122,7 +122,7 @@ export class UiSettingsClient implements IUiSettingsClient { async removeMany(keys: string[]) { const changes: Record = {}; - keys.forEach(key => { + keys.forEach((key) => { changes[key] = null; }); await this.setMany(changes); diff --git a/src/core/server/utils/crypto/pkcs12.test.ts b/src/core/server/utils/crypto/pkcs12.test.ts index e9eb72fe395ff..ccfeea27c79c6 100644 --- a/src/core/server/utils/crypto/pkcs12.test.ts +++ b/src/core/server/utils/crypto/pkcs12.test.ts @@ -65,7 +65,7 @@ describe('#readPkcs12Keystore', () => { }; const expectCA = (pkcs12ReadResult: Pkcs12ReadResult, ca = [pemCA]) => { - const result = pkcs12ReadResult.ca?.map(x => reformatPem(x)); + const result = pkcs12ReadResult.ca?.map((x) => reformatPem(x)); expect(result).toEqual(ca); }; @@ -199,7 +199,7 @@ describe('#readPkcs12Keystore', () => { describe('#readPkcs12Truststore', () => { it('reads all certificates into one CA array and discards any certificates that have keys', () => { const ca = readPkcs12Truststore(ES_P12_PATH, ES_P12_PASSWORD); - const result = ca?.map(x => reformatPem(x)); + const result = ca?.map((x) => reformatPem(x)); expect(result).toEqual([pemCA]); }); }); diff --git a/src/core/server/utils/crypto/pkcs12.ts b/src/core/server/utils/crypto/pkcs12.ts index 74f22bb685c2f..7de68a71ad72e 100644 --- a/src/core/server/utils/crypto/pkcs12.ts +++ b/src/core/server/utils/crypto/pkcs12.ts @@ -115,9 +115,9 @@ const getCerts = (p12: pkcs12.Pkcs12Pfx, pubKey?: PublicKeyData) => { let ca; let cert; if (bags && bags.length) { - const certs = bags.map(convertCert).filter(x => x !== undefined); - cert = certs.find(x => doesPubKeyMatch(x!.publicKeyData, pubKey))?.cert; - ca = certs.filter(x => !doesPubKeyMatch(x!.publicKeyData, pubKey)).map(x => x!.cert); + const certs = bags.map(convertCert).filter((x) => x !== undefined); + cert = certs.find((x) => doesPubKeyMatch(x!.publicKeyData, pubKey))?.cert; + ca = certs.filter((x) => !doesPubKeyMatch(x!.publicKeyData, pubKey)).map((x) => x!.cert); if (ca.length === 0) { ca = undefined; } diff --git a/src/core/server/uuid/resolve_uuid.test.ts b/src/core/server/uuid/resolve_uuid.test.ts index efc90c07c1fa6..eab027b532ddb 100644 --- a/src/core/server/uuid/resolve_uuid.test.ts +++ b/src/core/server/uuid/resolve_uuid.test.ts @@ -68,7 +68,7 @@ const mockWriteFile = (error?: object) => { const getConfigService = (serverUuid: string | undefined) => { const configService = configServiceMock.create(); - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { if (path === 'path') { return new BehaviorSubject({ data: 'data-folder', diff --git a/src/core/server/uuid/resolve_uuid.ts b/src/core/server/uuid/resolve_uuid.ts index 516357e10d3f7..c3e79cc519a1b 100644 --- a/src/core/server/uuid/resolve_uuid.ts +++ b/src/core/server/uuid/resolve_uuid.ts @@ -44,14 +44,8 @@ export async function resolveInstanceUuid({ logger: Logger; }): Promise { const [pathConfig, serverConfig] = await Promise.all([ - configService - .atPath(pathConfigDef.path) - .pipe(take(1)) - .toPromise(), - configService - .atPath(httpConfigDef.path) - .pipe(take(1)) - .toPromise(), + configService.atPath(pathConfigDef.path).pipe(take(1)).toPromise(), + configService.atPath(httpConfigDef.path).pipe(take(1)).toPromise(), ]); const uuidFilePath = join(pathConfig.data, FILE_NAME); diff --git a/src/core/utils/context.test.ts b/src/core/utils/context.test.ts index 4bfeddc2e08c9..dcc6c63bcf545 100644 --- a/src/core/utils/context.test.ts +++ b/src/core/utils/context.test.ts @@ -75,24 +75,24 @@ describe('ContextContainer', () => { coreId ); expect.assertions(8); - contextContainer.registerContext(coreId, 'core1', context => { + contextContainer.registerContext(coreId, 'core1', (context) => { expect(context).toEqual({}); return 'core'; }); - contextContainer.registerContext(pluginA, 'ctxFromA', context => { + contextContainer.registerContext(pluginA, 'ctxFromA', (context) => { expect(context).toEqual({ core1: 'core' }); return 'aString'; }); - contextContainer.registerContext(pluginB, 'ctxFromB', context => { + contextContainer.registerContext(pluginB, 'ctxFromB', (context) => { expect(context).toEqual({ core1: 'core', ctxFromA: 'aString' }); return 299; }); - contextContainer.registerContext(pluginC, 'ctxFromC', context => { + contextContainer.registerContext(pluginC, 'ctxFromC', (context) => { expect(context).toEqual({ core1: 'core', ctxFromA: 'aString', ctxFromB: 299 }); return false; }); - contextContainer.registerContext(pluginD, 'ctxFromD', context => { + contextContainer.registerContext(pluginD, 'ctxFromD', (context) => { expect(context).toEqual({ core1: 'core' }); return {}; }); @@ -129,13 +129,13 @@ describe('ContextContainer', () => { coreId ); contextContainer - .registerContext(pluginA, 'ctxFromA', context => { + .registerContext(pluginA, 'ctxFromA', (context) => { expect(context).toEqual({ core1: 'core', core2: 101 }); return `aString ${context.core1} ${context.core2}`; }) .registerContext(coreId, 'core1', () => 'core') .registerContext(coreId, 'core2', () => 101) - .registerContext(pluginB, 'ctxFromB', context => { + .registerContext(pluginB, 'ctxFromB', (context) => { expect(context).toEqual({ core1: 'core', core2: 101, ctxFromA: 'aString core 101' }); return 277; }); @@ -161,11 +161,11 @@ describe('ContextContainer', () => { ); contextContainer - .registerContext(coreId, 'core1', context => { + .registerContext(coreId, 'core1', (context) => { expect(context).toEqual({}); return 'core'; }) - .registerContext(coreId, 'core2', context => { + .registerContext(coreId, 'core2', (context) => { expect(context).toEqual({ core1: 'core' }); return 101; }); @@ -189,8 +189,8 @@ describe('ContextContainer', () => { ); contextContainer - .registerContext(coreId, 'core1', context => 'core') - .registerContext(pluginA, 'ctxFromA', context => 'aString'); + .registerContext(coreId, 'core1', (context) => 'core') + .registerContext(pluginA, 'ctxFromA', (context) => 'aString'); const rawHandler1 = jest.fn(() => 'handler1'); const handler1 = contextContainer.createHandler(coreId, rawHandler1); diff --git a/src/core/utils/context.ts b/src/core/utils/context.ts index de311f91d56fa..941bbceb0cd92 100644 --- a/src/core/utils/context.ts +++ b/src/core/utils/context.ts @@ -304,7 +304,7 @@ export class ContextContainer> // Contexts source created ...(this.contextNamesBySource.get(pluginId) || []), // Contexts sources's dependencies created - ...flatten(pluginDeps.map(p => this.contextNamesBySource.get(p) || [])), + ...flatten(pluginDeps.map((p) => this.contextNamesBySource.get(p) || [])), ]); } } diff --git a/src/core/utils/integration_tests/deep_freeze.test.ts b/src/core/utils/integration_tests/deep_freeze.test.ts index e6625542bc38a..f58e298fecfbf 100644 --- a/src/core/utils/integration_tests/deep_freeze.test.ts +++ b/src/core/utils/integration_tests/deep_freeze.test.ts @@ -30,7 +30,7 @@ it( execa('tsc', ['--noEmit'], { cwd: resolve(__dirname, '__fixtures__/frozen_object_mutation'), preferLocal: true, - }).catch(err => err.stdout) + }).catch((err) => err.stdout) ).resolves.toMatchInlineSnapshot(` "index.ts(28,12): error TS2540: Cannot assign to 'baz' because it is a read-only property. index.ts(36,11): error TS2540: Cannot assign to 'bar' because it is a read-only property." diff --git a/src/core/utils/map_utils.ts b/src/core/utils/map_utils.ts index 47a1d6b34b99f..2f6ec94da1283 100644 --- a/src/core/utils/map_utils.ts +++ b/src/core/utils/map_utils.ts @@ -27,7 +27,7 @@ export function mapValuesOfMap(map: Map, mapper: (item: G) => H): export function groupIntoMap(collection: T[], groupBy: (item: T) => G): Map { const map = new Map(); - collection.forEach(item => { + collection.forEach((item) => { const key = groupBy(item); const values = map.get(key) || []; values.push(item); diff --git a/src/core/utils/promise.test.ts b/src/core/utils/promise.test.ts index 97d16c5158c7b..b78b6bc5120f9 100644 --- a/src/core/utils/promise.test.ts +++ b/src/core/utils/promise.test.ts @@ -20,7 +20,7 @@ import { withTimeout } from './promise'; const delay = (ms: number, resolveValue?: any) => - new Promise(resolve => setTimeout(resolve, ms, resolveValue)); + new Promise((resolve) => setTimeout(resolve, ms, resolveValue)); describe('withTimeout', () => { it('resolves with a promise value if resolved in given timeout', async () => { @@ -44,7 +44,7 @@ describe('withTimeout', () => { await expect( withTimeout({ - promise: new Promise(i => i), + promise: new Promise((i) => i), timeout: 10, errorMessage: 'error-message', }) diff --git a/src/core/utils/unset.ts b/src/core/utils/unset.ts index 8008d4ee08ba3..88bf2503c6d69 100644 --- a/src/core/utils/unset.ts +++ b/src/core/utils/unset.ts @@ -32,8 +32,8 @@ import { get } from './get'; export function unset(obj: OBJ, atPath: string) { const paths = atPath .split('.') - .map(s => s.trim()) - .filter(v => v !== ''); + .map((s) => s.trim()) + .filter((v) => v !== ''); if (paths.length === 0) { return; } diff --git a/src/core/utils/url.test.ts b/src/core/utils/url.test.ts index 419c0cda2b8cb..7e9b6adfd3f49 100644 --- a/src/core/utils/url.test.ts +++ b/src/core/utils/url.test.ts @@ -32,7 +32,7 @@ describe('modifyUrl()', () => { test('supports modifying the passed object', () => { expect( - modifyUrl('http://localhost', parsed => { + modifyUrl('http://localhost', (parsed) => { parsed.port = '9999'; parsed.auth = 'foo:bar'; return parsed; @@ -42,7 +42,7 @@ describe('modifyUrl()', () => { test('supports changing pathname', () => { expect( - modifyUrl('http://localhost/some/path', parsed => { + modifyUrl('http://localhost/some/path', (parsed) => { parsed.pathname += '/subpath'; return parsed; }) @@ -51,7 +51,7 @@ describe('modifyUrl()', () => { test('supports changing port', () => { expect( - modifyUrl('http://localhost:5601', parsed => { + modifyUrl('http://localhost:5601', (parsed) => { parsed.port = (Number(parsed.port!) + 1).toString(); return parsed; }) @@ -60,7 +60,7 @@ describe('modifyUrl()', () => { test('supports changing protocol', () => { expect( - modifyUrl('http://localhost', parsed => { + modifyUrl('http://localhost', (parsed) => { parsed.protocol = 'mail'; parsed.slashes = false; parsed.pathname = null; diff --git a/src/dev/build/args.ts b/src/dev/build/args.ts index 49bb8e150fcdc..f411e4c962093 100644 --- a/src/dev/build/args.ts +++ b/src/dev/build/args.ts @@ -63,7 +63,7 @@ export function readCliArgs(argv: string[]): ParsedArgs { oss: null, 'version-qualifier': '', }, - unknown: flag => { + unknown: (flag) => { unknownFlags.push(flag); return false; }, diff --git a/src/dev/build/cli.js b/src/dev/build/cli.js index f23832dfcdd56..a42930f57f82d 100644 --- a/src/dev/build/cli.js +++ b/src/dev/build/cli.js @@ -62,7 +62,7 @@ if (showHelp) { process.exit(1); } -buildDistributables({ log, ...buildArgs }).catch(error => { +buildDistributables({ log, ...buildArgs }).catch((error) => { if (!isErrorLogged(error)) { log.error('Uncaught error'); log.error(error); diff --git a/src/dev/build/lib/__tests__/config.js b/src/dev/build/lib/__tests__/config.js index d9238ad1eef43..d2f408378da25 100644 --- a/src/dev/build/lib/__tests__/config.js +++ b/src/dev/build/lib/__tests__/config.js @@ -26,7 +26,7 @@ import { getConfig } from '../config'; import { getVersionInfo } from '../version_info'; describe('dev/build/lib/config', () => { - const setup = async function({ targetAllPlatforms = true } = {}) { + const setup = async function ({ targetAllPlatforms = true } = {}) { const isRelease = Boolean(Math.round(Math.random())); const config = await getConfig({ isRelease, @@ -78,7 +78,7 @@ describe('dev/build/lib/config', () => { expect( config .getTargetPlatforms() - .map(p => p.getName()) + .map((p) => p.getName()) .sort() ).to.eql(['darwin', 'linux', 'windows']); }); @@ -99,7 +99,7 @@ describe('dev/build/lib/config', () => { expect( config .getTargetPlatforms() - .map(p => p.getName()) + .map((p) => p.getName()) .sort() ).to.eql(['darwin', 'linux', 'windows']); }); diff --git a/src/dev/build/lib/__tests__/exec.js b/src/dev/build/lib/__tests__/exec.js index 4123c0e3e8ed1..8e122c65132ac 100644 --- a/src/dev/build/lib/__tests__/exec.js +++ b/src/dev/build/lib/__tests__/exec.js @@ -31,7 +31,7 @@ describe('dev/build/lib/exec', () => { const log = new ToolingLog({ level: 'verbose', writeTo: { - write: chunk => { + write: (chunk) => { onLogLine(stripAnsi(chunk)); }, }, diff --git a/src/dev/build/lib/__tests__/fs.js b/src/dev/build/lib/__tests__/fs.js index 9125ace28ce8a..0b2db4c538fb8 100644 --- a/src/dev/build/lib/__tests__/fs.js +++ b/src/dev/build/lib/__tests__/fs.js @@ -35,9 +35,7 @@ const isWindows = /^win/.test(process.platform); // get the mode of a file as a string, like 777, or 644, function getCommonMode(path) { - return statSync(path) - .mode.toString(8) - .slice(-3); + return statSync(path).mode.toString(8).slice(-3); } function assertNonAbsoluteError(error) { diff --git a/src/dev/build/lib/__tests__/runner.js b/src/dev/build/lib/__tests__/runner.js index 0cf68ed1152cd..314c2dd45d50f 100644 --- a/src/dev/build/lib/__tests__/runner.js +++ b/src/dev/build/lib/__tests__/runner.js @@ -46,8 +46,8 @@ describe('dev/build/lib/runner', () => { getLogTag: sinon.match.func, }); - const ossBuildMatcher = buildMatcher.and(sinon.match(b => b.isOss(), 'is oss build')); - const defaultBuildMatcher = buildMatcher.and(sinon.match(b => !b.isOss(), 'is not oss build')); + const ossBuildMatcher = buildMatcher.and(sinon.match((b) => b.isOss(), 'is oss build')); + const defaultBuildMatcher = buildMatcher.and(sinon.match((b) => !b.isOss(), 'is not oss build')); afterEach(() => sandbox.reset()); @@ -159,9 +159,7 @@ describe('dev/build/lib/runner', () => { }); throw new Error('expected run() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('FOO'); + expect(error).to.have.property('message').be('FOO'); sinon.assert.calledWith(onLogLine, sinon.match(/FOO/)); expect(isErrorLogged(error)).to.be(true); } @@ -177,9 +175,7 @@ describe('dev/build/lib/runner', () => { throw new Error('expected run() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('FOO'); + expect(error).to.have.property('message').be('FOO'); sinon.assert.neverCalledWith(onLogLine, sinon.match(/FOO/)); expect(isErrorLogged(error)).to.be(true); } diff --git a/src/dev/build/lib/__tests__/version_info.js b/src/dev/build/lib/__tests__/version_info.js index a4e9b49a570e6..a7329642e4f9a 100644 --- a/src/dev/build/lib/__tests__/version_info.js +++ b/src/dev/build/lib/__tests__/version_info.js @@ -34,10 +34,7 @@ describe('dev/build/lib/version_info', () => { expect(versionInfo) .to.have.property('buildSha') .match(/^[0-9a-f]{40}$/); - expect(versionInfo) - .to.have.property('buildNumber') - .a('number') - .greaterThan(1000); + expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); }); }); describe('isRelease = false', () => { @@ -54,10 +51,7 @@ describe('dev/build/lib/version_info', () => { expect(versionInfo) .to.have.property('buildSha') .match(/^[0-9a-f]{40}$/); - expect(versionInfo) - .to.have.property('buildNumber') - .a('number') - .greaterThan(1000); + expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); }); }); diff --git a/src/dev/build/lib/config.js b/src/dev/build/lib/config.js index aed47da421460..cd762d9bb1f20 100644 --- a/src/dev/build/lib/config.js +++ b/src/dev/build/lib/config.js @@ -112,7 +112,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getLinuxPlatform() { - return platforms.find(p => p.isLinux()); + return platforms.find((p) => p.isLinux()); } /** @@ -120,7 +120,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getWindowsPlatform() { - return platforms.find(p => p.isWindows()); + return platforms.find((p) => p.isWindows()); } /** @@ -128,7 +128,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getMacPlatform() { - return platforms.find(p => p.isMac()); + return platforms.find((p) => p.isMac()); } /** diff --git a/src/dev/build/lib/exec.js b/src/dev/build/lib/exec.js index c83bc13a44302..5e47500c72c5c 100644 --- a/src/dev/build/lib/exec.js +++ b/src/dev/build/lib/exec.js @@ -34,5 +34,5 @@ export async function exec(log, cmd, args, options = {}) { preferLocal: true, }); - await watchStdioForLine(proc, line => log[level](line), exitAfter); + await watchStdioForLine(proc, (line) => log[level](line), exitAfter); } diff --git a/src/dev/build/lib/fs.js b/src/dev/build/lib/fs.js index 278f6851f3421..864a07e837c3f 100644 --- a/src/dev/build/lib/fs.js +++ b/src/dev/build/lib/fs.js @@ -82,7 +82,7 @@ export async function read(path) { export async function getChildPaths(path) { assertAbsolute(path); const childNames = await readdirAsync(path); - return childNames.map(name => resolve(path, name)); + return childNames.map((name) => resolve(path, name)); } export async function deleteAll(patterns, log) { @@ -122,8 +122,8 @@ export async function deleteEmptyFolders(log, rootFolderPath, foldersToKeep) { // Delete empty is used to gather all the empty folders and // then we use del to actually delete them const emptyFoldersList = await deleteEmpty(rootFolderPath, { dryRun: true }); - const foldersToDelete = emptyFoldersList.filter(folderToDelete => { - return !foldersToKeep.some(folderToKeep => folderToDelete.includes(folderToKeep)); + const foldersToDelete = emptyFoldersList.filter((folderToDelete) => { + return !foldersToKeep.some((folderToKeep) => folderToDelete.includes(folderToKeep)); }); const deletedEmptyFolders = await del(foldersToDelete, { concurrency: 4, @@ -159,7 +159,7 @@ export async function copyAll(sourceDir, destination, options = {}) { base: destination, dot, }), - createMapStream(file => utimesAsync(file.path, time, time)), + createMapStream((file) => utimesAsync(file.path, time, time)), ]); } } @@ -171,7 +171,7 @@ export async function getFileHash(path, algo) { const readStream = fs.createReadStream(path); await new Promise((resolve, reject) => { readStream - .on('data', chunk => hash.update(chunk)) + .on('data', (chunk) => hash.update(chunk)) .on('error', reject) .on('end', resolve); }); diff --git a/src/dev/build/lib/scan.ts b/src/dev/build/lib/scan.ts index 45e61ca051879..1d77101bdfdb2 100644 --- a/src/dev/build/lib/scan.ts +++ b/src/dev/build/lib/scan.ts @@ -50,7 +50,7 @@ export function scan$(directory: string) { return Rx.concat( [path], getStat$(path).pipe( - mergeMap(stat => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), + mergeMap((stat) => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), mergeMap(getPaths$) ) ); diff --git a/src/dev/build/lib/scan_copy.test.ts b/src/dev/build/lib/scan_copy.test.ts index cda009f9137f8..ba693770445dc 100644 --- a/src/dev/build/lib/scan_copy.test.ts +++ b/src/dev/build/lib/scan_copy.test.ts @@ -31,10 +31,7 @@ const FIXTURES = resolve(__dirname, '__tests__/fixtures'); const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable'); const TMP = resolve(__dirname, '__tests__/__tmp__'); -const getCommonMode = (path: string) => - statSync(path) - .mode.toString(8) - .slice(-3); +const getCommonMode = (path: string) => statSync(path).mode.toString(8).slice(-3); // ensure WORLD_EXECUTABLE is actually executable by all beforeAll(async () => { @@ -104,7 +101,7 @@ it('applies filter function specified', async () => { await scanCopy({ source: FIXTURES, destination, - filter: record => !record.name.includes('bar'), + filter: (record) => !record.name.includes('bar'), }); expect((await getChildPaths(resolve(destination, 'foo_dir'))).sort()).toEqual([ diff --git a/src/dev/build/lib/scan_copy.ts b/src/dev/build/lib/scan_copy.ts index 0a4bfdc8d0b4f..7fa2d9b9d25a3 100644 --- a/src/dev/build/lib/scan_copy.ts +++ b/src/dev/build/lib/scan_copy.ts @@ -72,20 +72,20 @@ export async function scanCopy(options: Options) { const getChildRecords = async (parent: Record) => { const names = await readdirAsync(parent.absolute); const records = await Promise.all( - names.map(async name => { + names.map(async (name) => { const absolute = join(parent.absolute, name); const stat = await statAsync(absolute); return new Record(stat.isDirectory(), name, absolute, join(parent.absoluteDest, name)); }) ); - return records.filter(record => (filter ? filter(record) : true)); + return records.filter((record) => (filter ? filter(record) : true)); }; // create or copy each child of a directory const copyChildren = async (record: Record) => { const children = await getChildRecords(record); - await Promise.all(children.map(async child => await copy(child))); + await Promise.all(children.map(async (child) => await copy(child))); }; // create or copy a record and recurse into directories diff --git a/src/dev/build/lib/scan_delete.ts b/src/dev/build/lib/scan_delete.ts index cb4e64ce1b5f9..6e41d207e3111 100644 --- a/src/dev/build/lib/scan_delete.ts +++ b/src/dev/build/lib/scan_delete.ts @@ -49,7 +49,7 @@ export async function scanDelete(options: Options) { const { directory, regularExpressions, concurrency = 20, excludePaths } = options; assertAbsolute(directory); - (excludePaths || []).forEach(excluded => assertAbsolute(excluded)); + (excludePaths || []).forEach((excluded) => assertAbsolute(excluded)); // get an observable of absolute paths within a directory const getChildPath$ = (path: string) => @@ -66,12 +66,12 @@ export async function scanDelete(options: Options) { return Rx.EMPTY; } - if (regularExpressions.some(re => re.test(path))) { + if (regularExpressions.some((re) => re.test(path))) { return Rx.of(path); } return getStat$(path).pipe( - mergeMap(stat => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), + mergeMap((stat) => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), mergeMap(getPathsToDelete$) ); }; @@ -79,7 +79,7 @@ export async function scanDelete(options: Options) { return await Rx.of(directory) .pipe( mergeMap(getPathsToDelete$), - mergeMap(async path => await del(path), concurrency), + mergeMap(async (path) => await del(path), concurrency), count() ) .toPromise(); diff --git a/src/dev/build/tasks/clean_tasks.js b/src/dev/build/tasks/clean_tasks.js index b23db67cc1b07..ec38dd8a1195c 100644 --- a/src/dev/build/tasks/clean_tasks.js +++ b/src/dev/build/tasks/clean_tasks.js @@ -63,8 +63,8 @@ export const CleanExtraFilesFromModulesTask = { description: 'Cleaning tests, examples, docs, etc. from node_modules', async run(config, log, build) { - const makeRegexps = patterns => - patterns.map(pattern => minimatch.makeRe(pattern, { nocase: true })); + const makeRegexps = (patterns) => + patterns.map((pattern) => minimatch.makeRe(pattern, { nocase: true })); const regularExpressions = makeRegexps([ // tests @@ -205,12 +205,12 @@ export const CleanExtraBrowsersTask = { description: 'Cleaning extra browsers from platform-specific builds', async run(config, log, build) { - const getBrowserPathsForPlatform = platform => { + const getBrowserPathsForPlatform = (platform) => { const reportingDir = 'x-pack/legacy/plugins/reporting'; const chromiumDir = '.chromium'; - const chromiumPath = p => + const chromiumPath = (p) => build.resolvePathForPlatform(platform, reportingDir, chromiumDir, p); - return platforms => { + return (platforms) => { const paths = []; if (platforms.windows) { paths.push(chromiumPath('chromium-*-win32.zip')); diff --git a/src/dev/build/tasks/create_archives_sources_task.js b/src/dev/build/tasks/create_archives_sources_task.js index 999fb0481bd4b..53cf750f484a1 100644 --- a/src/dev/build/tasks/create_archives_sources_task.js +++ b/src/dev/build/tasks/create_archives_sources_task.js @@ -24,7 +24,7 @@ export const CreateArchivesSourcesTask = { description: 'Creating platform-specific archive source directories', async run(config, log, build) { await Promise.all( - config.getTargetPlatforms().map(async platform => { + config.getTargetPlatforms().map(async (platform) => { // copy all files from generic build source directory into platform-specific build directory await scanCopy({ source: build.resolvePath(), diff --git a/src/dev/build/tasks/create_package_json_task.js b/src/dev/build/tasks/create_package_json_task.js index b65d3615633a5..e7a410b4c6350 100644 --- a/src/dev/build/tasks/create_package_json_task.js +++ b/src/dev/build/tasks/create_package_json_task.js @@ -50,7 +50,9 @@ export const CreatePackageJsonTask = { }; if (build.isOss()) { - newPkg.workspaces.packages = newPkg.workspaces.packages.filter(p => !p.startsWith('x-pack')); + newPkg.workspaces.packages = newPkg.workspaces.packages.filter( + (p) => !p.startsWith('x-pack') + ); } await write(build.resolvePath('package.json'), JSON.stringify(newPkg, null, ' ')); diff --git a/src/dev/build/tasks/nodejs/__tests__/download.js b/src/dev/build/tasks/nodejs/__tests__/download.js index 81ed7a6195ae7..49cb9caaaf4ec 100644 --- a/src/dev/build/tasks/nodejs/__tests__/download.js +++ b/src/dev/build/tasks/nodejs/__tests__/download.js @@ -62,7 +62,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { }); const FOO_SHA256 = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'; - const createSendHandler = send => (req, res) => { + const createSendHandler = (send) => (req, res) => { res.statusCode = 200; res.end(send); }; @@ -91,7 +91,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { new Promise((resolve, reject) => { server.once('error', reject); }), - new Promise(resolve => { + new Promise((resolve) => { server.listen(resolve); }), ]); @@ -206,9 +206,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { }); throw new Error('Expected download() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .contain('Request failed with status code 500'); + expect(error).to.have.property('message').contain('Request failed with status code 500'); expect(reqCount).to.be(6); } }); @@ -232,9 +230,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { throw new Error('expected download() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .contain('refusing to download'); + expect(error).to.have.property('message').contain('refusing to download'); } }); }); diff --git a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js index 4c94ed776417d..9357735e3f5a3 100644 --- a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js @@ -91,9 +91,7 @@ describe('src/dev/build/tasks/nodejs/download_node_builds_task', () => { await DownloadNodeBuildsTask.run(config, log); throw new Error('Expected DownloadNodeBuildsTask to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('Download failed for reasons'); + expect(error).to.have.property('message').be('Download failed for reasons'); } }); }); diff --git a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js index 0fc151258d779..a8f732a869d2d 100644 --- a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js @@ -58,7 +58,7 @@ describe('src/dev/build/tasks/nodejs/verify_existing_node_builds_task', () => { } ); - sandbox.stub(FsNS, 'getFileHash').callsFake(path => { + sandbox.stub(FsNS, 'getFileHash').callsFake((path) => { switch (path) { case 'foo:downloadPath': return 'foo:sha256'; diff --git a/src/dev/build/tasks/nodejs/download.js b/src/dev/build/tasks/nodejs/download.js index 0bd10e5b84015..fb3294e2d1221 100644 --- a/src/dev/build/tasks/nodejs/download.js +++ b/src/dev/build/tasks/nodejs/download.js @@ -62,7 +62,7 @@ export async function download(options) { const hash = createHash('sha256'); await new Promise((resolve, reject) => { - response.data.on('data', chunk => { + response.data.on('data', (chunk) => { hash.update(chunk); writeSync(fileHandle, chunk); }); diff --git a/src/dev/build/tasks/nodejs/download_node_builds_task.js b/src/dev/build/tasks/nodejs/download_node_builds_task.js index df841960677c1..86ddb0506f972 100644 --- a/src/dev/build/tasks/nodejs/download_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/download_node_builds_task.js @@ -27,7 +27,7 @@ export const DownloadNodeBuildsTask = { async run(config, log) { const shasums = await getNodeShasums(config.getNodeVersion()); await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { url, downloadPath, downloadName } = getNodeDownloadInfo(config, platform); await download({ log, diff --git a/src/dev/build/tasks/nodejs/extract_node_builds_task.js b/src/dev/build/tasks/nodejs/extract_node_builds_task.js index 68e56ac7d4aa6..caf0a389b4cc0 100644 --- a/src/dev/build/tasks/nodejs/extract_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/extract_node_builds_task.js @@ -32,7 +32,7 @@ export const ExtractNodeBuildsTask = { description: 'Extracting node.js builds for all platforms', async run(config) { await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { downloadPath, extractDir } = getNodeDownloadInfo(config, platform); // windows executable is not extractable, it's just an .exe file if (platform.isWindows()) { diff --git a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js index 1a6adcd5d1db4..b320471fda33f 100644 --- a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js @@ -28,7 +28,7 @@ export const VerifyExistingNodeBuildsTask = { const shasums = await getNodeShasums(config.getNodeVersion()); await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { downloadPath, downloadName } = getNodeDownloadInfo(config, platform); const sha256 = await getFileHash(downloadPath, 'sha256'); diff --git a/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js b/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js index 8e8d69a4dfefa..05bfd3ca31a65 100644 --- a/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js +++ b/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js @@ -34,7 +34,7 @@ export const CleanClientModulesOnDLLTask = { const kbnPkg = config.getKibanaPkg(); const kbnPkgDependencies = (kbnPkg && kbnPkg.dependencies) || {}; const kbnWebpackLoaders = Object.keys(kbnPkgDependencies).filter( - dep => !!dep.includes('-loader') + (dep) => !!dep.includes('-loader') ); // Define the entry points for the server code in order to @@ -44,7 +44,7 @@ export const CleanClientModulesOnDLLTask = { `${baseDir}/src/cli_keystore`, `${baseDir}/src/cli_plugin`, `${baseDir}/x-pack`, - ...kbnWebpackLoaders.map(loader => `${baseDir}/node_modules/${loader}`), + ...kbnWebpackLoaders.map((loader) => `${baseDir}/node_modules/${loader}`), ]; const discoveredLegacyCorePluginEntries = await globby([ `${baseDir}/src/legacy/core_plugins/*/index.js`, @@ -84,7 +84,7 @@ export const CleanClientModulesOnDLLTask = { // consider the top modules as exceptions as the entry points // to look for other exceptions dependent on that one const manualExceptionEntries = [ - ...manualExceptionModules.map(module => `${baseDir}/node_modules/${module}`), + ...manualExceptionModules.map((module) => `${baseDir}/node_modules/${module}`), ]; // dependencies for declared exception modules diff --git a/src/dev/build/tasks/nodejs_modules/webpack_dll.js b/src/dev/build/tasks/nodejs_modules/webpack_dll.js index 72910226bb04a..8de5e582c3d36 100644 --- a/src/dev/build/tasks/nodejs_modules/webpack_dll.js +++ b/src/dev/build/tasks/nodejs_modules/webpack_dll.js @@ -31,7 +31,7 @@ function checkDllEntryAccess(entry, baseDir = '') { export async function getDllEntries(manifestPaths, whiteListedModules, baseDir = '') { // Read and parse all manifests const manifests = await Promise.all( - manifestPaths.map(async manifestPath => JSON.parse(await read(manifestPath))) + manifestPaths.map(async (manifestPath) => JSON.parse(await read(manifestPath))) ); // Process and group modules from all manifests @@ -58,8 +58,8 @@ export async function getDllEntries(manifestPaths, whiteListedModules, baseDir = // Only includes modules who are not in the white list of modules // and that are node_modules - return manifestsModules.filter(entry => { - const isWhiteListed = whiteListedModules.some(nonEntry => + return manifestsModules.filter((entry) => { + const isWhiteListed = whiteListedModules.some((nonEntry) => normalizePosixPath(entry).includes(`node_modules/${nonEntry}`) ); const isNodeModule = entry.includes('node_modules'); @@ -113,7 +113,7 @@ export async function cleanDllModuleFromEntryPath(logger, entryPath) { ]); await deleteAll( - filesToDelete.filter(path => { + filesToDelete.filter((path) => { const relativePath = relative(moduleDir, path); return !relativePath.endsWith('package.json') || relativePath.includes('node_modules'); }) diff --git a/src/dev/build/tasks/path_length_task.js b/src/dev/build/tasks/path_length_task.js index b108b8820575b..29ab9ce5a2499 100644 --- a/src/dev/build/tasks/path_length_task.js +++ b/src/dev/build/tasks/path_length_task.js @@ -30,10 +30,10 @@ export const PathLengthTask = { const buildRoot = build.resolvePath(); await scan$(buildRoot) .pipe( - map(path => relative(buildRoot, path)), - filter(relativePath => relativePath.length > 200), + map((path) => relative(buildRoot, path)), + filter((relativePath) => relativePath.length > 200), toArray(), - tap(tooLongPaths => { + tap((tooLongPaths) => { if (!tooLongPaths.length) { return; } diff --git a/src/dev/code_coverage/ingest_coverage/either.js b/src/dev/code_coverage/ingest_coverage/either.js index bdab6e5882d26..a52fd2f7212d6 100644 --- a/src/dev/code_coverage/ingest_coverage/either.js +++ b/src/dev/code_coverage/ingest_coverage/either.js @@ -20,9 +20,9 @@ /* eslint new-cap: 0 */ /* eslint no-unused-vars: 0 */ -export const Right = x => ({ - chain: f => f(x), - map: f => Right(f(x)), +export const Right = (x) => ({ + chain: (f) => f(x), + map: (f) => Right(f(x)), fold: (f, g) => g(x), inspect: () => `Right(${x})`, }); @@ -35,9 +35,9 @@ export function right(x) { return Right.of(x); } -export const Left = x => ({ - chain: f => Left(x), - map: f => Left(x), +export const Left = (x) => ({ + chain: (f) => Left(x), + map: (f) => Left(x), fold: (f, g) => f(x), inspect: () => `Left(${x})`, }); @@ -50,10 +50,10 @@ export function left(x) { return Left.of(x); } -export const fromNullable = x => +export const fromNullable = (x) => x !== null && x !== undefined && x !== false && x !== 'undefined' ? Right(x) : Left(null); -export const tryCatch = f => { +export const tryCatch = (f) => { try { return Right(f()); } catch (e) { diff --git a/src/dev/code_coverage/ingest_coverage/ingest.js b/src/dev/code_coverage/ingest_coverage/ingest.js index 769fe250a8e18..9167bea17ae05 100644 --- a/src/dev/code_coverage/ingest_coverage/ingest.js +++ b/src/dev/code_coverage/ingest_coverage/ingest.js @@ -28,9 +28,9 @@ const node = process.env.ES_HOST || 'http://localhost:9200'; const redacted = redact(node); const client = new Client({ node }); -const indexName = body => (body.isTotal ? TOTALS_INDEX : COVERAGE_INDEX); +const indexName = (body) => (body.isTotal ? TOTALS_INDEX : COVERAGE_INDEX); -export const ingest = log => async body => { +export const ingest = (log) => async (body) => { const index = indexName(body); if (process.env.NODE_ENV === 'integration_test') { @@ -80,10 +80,7 @@ ${red('Perhaps the coverage data was not merged properly?\n')} } function partial(x) { - return x - .split('\n') - .splice(0, 2) - .join('\n'); + return x.split('\n').splice(0, 2).join('\n'); } function redact(x) { const url = new URL(x); diff --git a/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js b/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js index 2ffb005993619..dcd78250986df 100644 --- a/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js +++ b/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js @@ -37,9 +37,9 @@ const env = { NODE_ENV: 'integration_test', COVERAGE_INGESTION_KIBANA_ROOT: '/var/lib/jenkins/workspace/elastic+kibana+code-coverage/kibana', }; -const includesSiteUrlPredicate = x => x.includes('staticSiteUrl'); +const includesSiteUrlPredicate = (x) => x.includes('staticSiteUrl'); const siteUrlLines = specificLinesOnly(includesSiteUrlPredicate); -const splitByNewLine = x => x.split('\n'); +const splitByNewLine = (x) => x.split('\n'); const siteUrlsSplitByNewLine = siteUrlLines(splitByNewLine); const siteUrlsSplitByNewLineWithoutBlanks = siteUrlsSplitByNewLine(notBlankLines); const verboseArgs = [ @@ -56,7 +56,7 @@ describe('Ingesting coverage', () => { describe(`to the coverage index`, () => { const mutableCoverageIndexChunks = []; - beforeAll(done => { + beforeAll((done) => { const ingestAndMutateAsync = ingestAndMutate(done); const ingestAndMutateAsyncWithPath = ingestAndMutateAsync(bothIndexesPath); const verboseIngestAndMutateAsyncWithPath = ingestAndMutateAsyncWithPath(verboseArgs); @@ -78,19 +78,19 @@ describe('Ingesting coverage', () => { }); function ingestAndMutate(done) { - return summaryPathSuffix => args => xs => { + return (summaryPathSuffix) => (args) => (xs) => { const coverageSummaryPath = resolve(MOCKS_DIR, summaryPathSuffix); const opts = [...args, coverageSummaryPath]; const ingest = spawn(process.execPath, opts, { cwd: ROOT_DIR, env }); - ingest.stdout.on('data', x => xs.push(x + '')); + ingest.stdout.on('data', (x) => xs.push(x + '')); ingest.on('close', done); }; } function specificLinesOnly(predicate) { - return splitByNewLine => notBlankLines => xs => - xs.filter(predicate).map(x => splitByNewLine(x).reduce(notBlankLines)); + return (splitByNewLine) => (notBlankLines) => (xs) => + xs.filter(predicate).map((x) => splitByNewLine(x).reduce(notBlankLines)); } function notBlankLines(acc, item) { @@ -99,8 +99,8 @@ function notBlankLines(acc, item) { } function expectAllRegexesToPass(staticSiteUrlRegexes) { - return urlLine => - Object.entries(staticSiteUrlRegexes).forEach(regexTuple => { + return (urlLine) => + Object.entries(staticSiteUrlRegexes).forEach((regexTuple) => { if (!regexTuple[1].test(urlLine)) throw new Error( `\n### ${green('FAILED')}\nAsserting: [\n\t${green( diff --git a/src/dev/code_coverage/ingest_coverage/json_stream.js b/src/dev/code_coverage/ingest_coverage/json_stream.js index fbc704b6372f2..edc329309df92 100644 --- a/src/dev/code_coverage/ingest_coverage/json_stream.js +++ b/src/dev/code_coverage/ingest_coverage/json_stream.js @@ -20,4 +20,4 @@ import oboe from 'oboe'; import { createReadStream } from 'fs'; -export default jsonSummaryPath => oboe(createReadStream(jsonSummaryPath)); +export default (jsonSummaryPath) => oboe(createReadStream(jsonSummaryPath)); diff --git a/src/dev/code_coverage/ingest_coverage/process.js b/src/dev/code_coverage/ingest_coverage/process.js index ecd09e0b2fd1a..6b9c8f09febfe 100644 --- a/src/dev/code_coverage/ingest_coverage/process.js +++ b/src/dev/code_coverage/ingest_coverage/process.js @@ -46,11 +46,11 @@ const addPrePopulatedTimeStamp = addTimeStamp(process.env.TIME_STAMP); const preamble = pipe(statsAndstaticSiteUrl, rootDirAndOrigPath, buildId, addPrePopulatedTimeStamp); const addTestRunnerAndStaticSiteUrl = pipe(testRunner, staticSite(staticSiteUrlBase)); -const transform = jsonSummaryPath => log => vcsInfo => { +const transform = (jsonSummaryPath) => (log) => (vcsInfo) => { const objStream = jsonStream(jsonSummaryPath).on('done', noop); const itemizeVcsInfo = itemizeVcs(vcsInfo); - const jsonSummary$ = _ => objStream.on('node', '!.*', _); + const jsonSummary$ = (_) => objStream.on('node', '!.*', _); fromEventPattern(jsonSummary$) .pipe( @@ -60,7 +60,7 @@ const transform = jsonSummaryPath => log => vcsInfo => { map(ciRunUrl), map(addJsonSummaryPath(jsonSummaryPath)), map(addTestRunnerAndStaticSiteUrl), - concatMap(x => of(x).pipe(delay(ms))) + concatMap((x) => of(x).pipe(delay(ms))) ) .subscribe(ingest(log)); }; @@ -73,8 +73,8 @@ function rootDirAndOrigPath(obj) { }; } -const mutateVcsInfo = vcsInfo => x => vcsInfo.push(x.trimStart().trimEnd()); -const vcsInfoLines$ = vcsInfoFilePath => { +const mutateVcsInfo = (vcsInfo) => (x) => vcsInfo.push(x.trimStart().trimEnd()); +const vcsInfoLines$ = (vcsInfoFilePath) => { const rl = readline.createInterface({ input: createReadStream(vcsInfoFilePath) }); return fromEvent(rl, 'line').pipe(takeUntil(fromEvent(rl, 'close'))); }; @@ -88,7 +88,7 @@ export const prok = ({ jsonSummaryPath, vcsInfoFilePath }, log) => { const vcsInfo = []; vcsInfoLines$(vcsInfoFilePath).subscribe( mutateVcsInfo(vcsInfo), - err => log.error(err), + (err) => log.error(err), always(xformWithPath(vcsInfo)) ); }; diff --git a/src/dev/code_coverage/ingest_coverage/transforms.js b/src/dev/code_coverage/ingest_coverage/transforms.js index d5a4d8933e36b..cecaf1e192b8c 100644 --- a/src/dev/code_coverage/ingest_coverage/transforms.js +++ b/src/dev/code_coverage/ingest_coverage/transforms.js @@ -20,7 +20,7 @@ import { left, right, fromNullable } from './either'; import { always, id, noop } from './utils'; -const maybeTotal = x => (x === 'total' ? left(x) : right(x)); +const maybeTotal = (x) => (x === 'total' ? left(x) : right(x)); const trimLeftFrom = (text, x) => x.substr(x.indexOf(text)); @@ -33,43 +33,43 @@ export const statsAndstaticSiteUrl = (...xs) => { }; }; -export const addJsonSummaryPath = jsonSummaryPath => obj => ({ jsonSummaryPath, ...obj }); +export const addJsonSummaryPath = (jsonSummaryPath) => (obj) => ({ jsonSummaryPath, ...obj }); -export const truncate = text => obj => { +export const truncate = (text) => (obj) => { const { staticSiteUrl } = obj; if (staticSiteUrl.includes(text)) obj.staticSiteUrl = trimLeftFrom(text, staticSiteUrl); return obj; }; -export const addTimeStamp = ts => obj => ({ +export const addTimeStamp = (ts) => (obj) => ({ ...obj, '@timestamp': ts, }); -const setTotal = x => obj => (obj.isTotal = x); +const setTotal = (x) => (obj) => (obj.isTotal = x); const mutateTrue = setTotal(true); const mutateFalse = setTotal(false); -const root = urlBase => ts => testRunnerType => +const root = (urlBase) => (ts) => (testRunnerType) => `${urlBase}/${ts}/${testRunnerType.toLowerCase()}-combined`; -const prokForTotalsIndex = mutateTrue => urlRoot => obj => +const prokForTotalsIndex = (mutateTrue) => (urlRoot) => (obj) => right(obj) .map(mutateTrue) .map(always(`${urlRoot}/index.html`)) .fold(noop, id); -const prokForCoverageIndex = root => mutateFalse => urlRoot => obj => siteUrl => +const prokForCoverageIndex = (root) => (mutateFalse) => (urlRoot) => (obj) => (siteUrl) => right(siteUrl) - .map(x => { + .map((x) => { mutateFalse(obj); return x; }) - .map(x => x.replace(root, '')) - .map(x => `${urlRoot}${x}.html`) + .map((x) => x.replace(root, '')) + .map((x) => `${urlRoot}${x}.html`) .fold(noop, id); -export const staticSite = urlBase => obj => { +export const staticSite = (urlBase) => (obj) => { const { staticSiteUrl, testRunnerType, COVERAGE_INGESTION_KIBANA_ROOT } = obj; const ts = obj['@timestamp']; const urlRoot = root(urlBase)(ts)(testRunnerType); @@ -82,27 +82,27 @@ export const staticSite = urlBase => obj => { return { ...obj, staticSiteUrl: prokForBoth() }; }; -export const coveredFilePath = obj => { +export const coveredFilePath = (obj) => { const { staticSiteUrl, COVERAGE_INGESTION_KIBANA_ROOT } = obj; const withoutCoveredFilePath = always(obj); const leadingSlashRe = /^\//; - const maybeDropLeadingSlash = x => (leadingSlashRe.test(x) ? right(x) : left(x)); - const dropLeadingSlash = x => x.replace(leadingSlashRe, ''); - const dropRoot = root => x => + const maybeDropLeadingSlash = (x) => (leadingSlashRe.test(x) ? right(x) : left(x)); + const dropLeadingSlash = (x) => x.replace(leadingSlashRe, ''); + const dropRoot = (root) => (x) => maybeDropLeadingSlash(x.replace(root, '')).fold(id, dropLeadingSlash); return maybeTotal(staticSiteUrl) .map(dropRoot(COVERAGE_INGESTION_KIBANA_ROOT)) - .fold(withoutCoveredFilePath, coveredFilePath => ({ ...obj, coveredFilePath })); + .fold(withoutCoveredFilePath, (coveredFilePath) => ({ ...obj, coveredFilePath })); }; -export const ciRunUrl = obj => - fromNullable(process.env.CI_RUN_URL).fold(always(obj), ciRunUrl => ({ ...obj, ciRunUrl })); +export const ciRunUrl = (obj) => + fromNullable(process.env.CI_RUN_URL).fold(always(obj), (ciRunUrl) => ({ ...obj, ciRunUrl })); const size = 50; -const truncateCommitMsg = x => (x.length > size ? `${x.slice(0, 50)}...` : x); +const truncateCommitMsg = (x) => (x.length > size ? `${x.slice(0, 50)}...` : x); -export const itemizeVcs = vcsInfo => obj => { +export const itemizeVcs = (vcsInfo) => (obj) => { const [branch, sha, author, commitMsg] = vcsInfo; return { ...obj, @@ -115,12 +115,12 @@ export const itemizeVcs = vcsInfo => obj => { }, }; }; -export const testRunner = obj => { +export const testRunner = (obj) => { const { jsonSummaryPath } = obj; let testRunnerType = 'other'; - const upperTestRunnerType = x => { + const upperTestRunnerType = (x) => { if (jsonSummaryPath.includes(x)) { testRunnerType = x.toUpperCase(); return; @@ -135,7 +135,7 @@ export const testRunner = obj => { }; }; -export const buildId = obj => { +export const buildId = (obj) => { const { env } = process; if (env.BUILD_ID) obj.BUILD_ID = env.BUILD_ID; diff --git a/src/dev/code_coverage/ingest_coverage/utils.js b/src/dev/code_coverage/ingest_coverage/utils.js index df064e73842e7..7d817bdf7a6f3 100644 --- a/src/dev/code_coverage/ingest_coverage/utils.js +++ b/src/dev/code_coverage/ingest_coverage/utils.js @@ -21,7 +21,7 @@ import chalk from 'chalk'; export const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); export const noop = () => {}; -export const green = x => chalk.greenBright.bold(x); -export const id = x => x; -export const always = x => () => x; -export const pretty = x => JSON.stringify(x, null, 2); +export const green = (x) => chalk.greenBright.bold(x); +export const id = (x) => x; +export const always = (x) => () => x; +export const pretty = (x) => JSON.stringify(x, null, 2); diff --git a/src/dev/eslint/lint_files.ts b/src/dev/eslint/lint_files.ts index 80c493233f39a..ba16163fc9bd3 100644 --- a/src/dev/eslint/lint_files.ts +++ b/src/dev/eslint/lint_files.ts @@ -38,7 +38,7 @@ export function lintFiles(log: ToolingLog, files: File[], { fix }: { fix?: boole fix, }); - const paths = files.map(file => file.getRelativePath()); + const paths = files.map((file) => file.getRelativePath()); const report = cli.executeOnFiles(paths); if (fix) { diff --git a/src/dev/eslint/pick_files_to_lint.ts b/src/dev/eslint/pick_files_to_lint.ts index b96781fc3a611..dc6713c5efd00 100644 --- a/src/dev/eslint/pick_files_to_lint.ts +++ b/src/dev/eslint/pick_files_to_lint.ts @@ -31,7 +31,7 @@ import { File } from '../file'; export function pickFilesToLint(log: ToolingLog, files: File[]) { const cli = new CLIEngine({}); - return files.filter(file => { + return files.filter((file) => { if (!file.isJs() && !file.isTypescript()) { return; } diff --git a/src/dev/globs.js b/src/dev/globs.js index 3d1637ff97f18..1289be7599ca9 100644 --- a/src/dev/globs.js +++ b/src/dev/globs.js @@ -20,7 +20,7 @@ import minimatch from 'minimatch'; export function matchesAnyGlob(path, globs) { - return globs.some(pattern => + return globs.some((pattern) => minimatch(path, pattern, { dot: true, }) diff --git a/src/dev/i18n/config.ts b/src/dev/i18n/config.ts index cd59408947d9b..c11ced51bce65 100644 --- a/src/dev/i18n/config.ts +++ b/src/dev/i18n/config.ts @@ -51,7 +51,7 @@ export async function assignConfigFromPath( for (const [namespace, namespacePaths] of Object.entries(additionalConfig.paths)) { const paths = Array.isArray(namespacePaths) ? namespacePaths : [namespacePaths]; - config.paths[namespace] = paths.map(path => normalizePath(resolve(configPath, '..', path))); + config.paths[namespace] = paths.map((path) => normalizePath(resolve(configPath, '..', path))); } for (const exclude of additionalConfig.exclude) { @@ -80,15 +80,17 @@ export function filterConfigPaths(inputPaths: string[], config: I18nConfig) { // If input path is the sub path of or equal to any available path, include it. if ( - availablePaths.some(path => normalizedPath.startsWith(`${path}/`) || path === normalizedPath) + availablePaths.some( + (path) => normalizedPath.startsWith(`${path}/`) || path === normalizedPath + ) ) { pathsForExtraction.add(normalizedPath); } else { // Otherwise go through all available paths and see if any of them is the sub // path of the input path (empty normalized path corresponds to root or above). availablePaths - .filter(path => !normalizedPath || path.startsWith(`${normalizedPath}/`)) - .forEach(ePath => pathsForExtraction.add(ePath)); + .filter((path) => !normalizedPath || path.startsWith(`${normalizedPath}/`)) + .forEach((ePath) => pathsForExtraction.add(ePath)); } } diff --git a/src/dev/i18n/extract_default_translations.js b/src/dev/i18n/extract_default_translations.js index 9daf431ad5401..e70c666422f7b 100644 --- a/src/dev/i18n/extract_default_translations.js +++ b/src/dev/i18n/extract_default_translations.js @@ -38,8 +38,8 @@ function addMessageToMap(targetMap, key, value, reporter) { } function filterEntries(entries, exclude) { - return entries.filter(entry => - exclude.every(excludedPath => !normalizePath(entry).startsWith(excludedPath)) + return entries.filter((entry) => + exclude.every((excludedPath) => !normalizePath(entry).startsWith(excludedPath)) ); } @@ -47,7 +47,7 @@ export function validateMessageNamespace(id, filePath, allowedPaths, reporter) { const normalizedPath = normalizePath(filePath); const [expectedNamespace] = Object.entries(allowedPaths).find(([, pluginPaths]) => - pluginPaths.some(pluginPath => normalizedPath.startsWith(`${pluginPath}/`)) + pluginPaths.some((pluginPath) => normalizedPath.startsWith(`${pluginPath}/`)) ); if (!id.startsWith(`${expectedNamespace}.`)) { @@ -107,7 +107,7 @@ export async function extractMessagesFromPathToMap(inputPath, targetMap, config, return Promise.all( categorizedEntries.map(async ([entries, extractFunction]) => { const files = await Promise.all( - filterEntries(entries, config.exclude).map(async entry => { + filterEntries(entries, config.exclude).map(async (entry) => { return { name: entry, content: await readFileAsync(entry), diff --git a/src/dev/i18n/extractors/code.test.js b/src/dev/i18n/extractors/code.test.js index 34861aee38352..726afedd9f929 100644 --- a/src/dev/i18n/extractors/code.test.js +++ b/src/dev/i18n/extractors/code.test.js @@ -94,11 +94,11 @@ describe('isIntlFormatMessageFunction', () => { test('detects intl.formatMessage call expression', () => { const callExpressionNodes = [ ...traverseNodes(parse(intlFormatMessageSource).program.body), - ].filter(node => isCallExpression(node)); + ].filter((node) => isCallExpression(node)); expect(callExpressionNodes).toHaveLength(4); expect( - callExpressionNodes.every(callExpressionNode => + callExpressionNodes.every((callExpressionNode) => isIntlFormatMessageFunction(callExpressionNode) ) ).toBe(true); @@ -108,7 +108,7 @@ describe('isIntlFormatMessageFunction', () => { describe('isFormattedMessageElement', () => { test('detects FormattedMessage jsx element', () => { const AST = parse(formattedMessageSource, { plugins: ['jsx'] }); - const jsxOpeningElementNode = [...traverseNodes(AST.program.body)].find(node => + const jsxOpeningElementNode = [...traverseNodes(AST.program.body)].find((node) => isJSXOpeningElement(node) ); diff --git a/src/dev/i18n/extractors/html.js b/src/dev/i18n/extractors/html.js index 5b45738209264..6c7b982b872a5 100644 --- a/src/dev/i18n/extractors/html.js +++ b/src/dev/i18n/extractors/html.js @@ -68,7 +68,7 @@ function parseExpression(expression) { */ function parseFilterObjectExpression(expression, messageId) { const ast = parseExpression(expression); - const objectExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const objectExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isObjectExpression(node) ); @@ -80,7 +80,9 @@ function parseFilterObjectExpression(expression, messageId) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => objectExpressionNode.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => + objectExpressionNode.properties.find((property) => isPropertyWithKey(property, key)) + ); const message = messageProperty ? formatJSString(extractMessageValueFromNode(messageProperty.value, messageId)) @@ -99,7 +101,7 @@ function parseFilterObjectExpression(expression, messageId) { function parseIdExpression(expression) { const ast = parseExpression(expression); - const stringNode = [...traverseNodes(ast.program.body)].find(node => isStringLiteral(node)); + const stringNode = [...traverseNodes(ast.program.body)].find((node) => isStringLiteral(node)); if (!stringNode) { throw createFailError(`Message id should be a string literal, but got: \n${expression}`); @@ -131,15 +133,13 @@ function trimOneTimeBindingOperator(string) { } function* extractExpressions(htmlContent) { - const elements = cheerio - .load(htmlContent)('*') - .toArray(); + const elements = cheerio.load(htmlContent)('*').toArray(); for (const element of elements) { for (const node of element.children) { if (node.type === 'text') { yield* (node.data.match(ANGULAR_EXPRESSION_REGEX) || []) - .filter(expression => expression.includes(I18N_FILTER_MARKER)) + .filter((expression) => expression.includes(I18N_FILTER_MARKER)) .map(trimCurlyBraces); } } @@ -232,7 +232,7 @@ function* getDirectiveMessages(htmlContent, reporter) { try { if (element.values) { const ast = parseExpression(element.values); - const valuesObjectNode = [...traverseNodes(ast.program.body)].find(node => + const valuesObjectNode = [...traverseNodes(ast.program.body)].find((node) => isObjectExpression(node) ); const valuesKeys = extractValuesKeysFromNode(valuesObjectNode); diff --git a/src/dev/i18n/extractors/i18n_call.js b/src/dev/i18n/extractors/i18n_call.js index 118cf63ce8a30..79aeee0ee2c5f 100644 --- a/src/dev/i18n/extractors/i18n_call.js +++ b/src/dev/i18n/extractors/i18n_call.js @@ -52,7 +52,7 @@ export function extractI18nCallMessages(node) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => optionsSubTree.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => optionsSubTree.properties.find((property) => isPropertyWithKey(property, key))); const message = messageProperty ? formatJSString(extractMessageValueFromNode(messageProperty.value, messageId)) diff --git a/src/dev/i18n/extractors/i18n_call.test.js b/src/dev/i18n/extractors/i18n_call.test.js index fd2873b5f8d43..7292ec83ec3b2 100644 --- a/src/dev/i18n/extractors/i18n_call.test.js +++ b/src/dev/i18n/extractors/i18n_call.test.js @@ -41,19 +41,19 @@ describe('dev/i18n/extractors/i18n_call', () => { test('extracts "i18n" and "i18n.translate" functions call message', () => { let callExpressionNode = [ ...traverseNodes(parse(i18nCallMessageSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); callExpressionNode = [ ...traverseNodes(parse(translateCallMessageSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); callExpressionNode = [ ...traverseNodes(parse(i18nCallMessageWithTemplateLiteralSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); }); @@ -62,7 +62,7 @@ describe('dev/i18n/extractors/i18n_call', () => { const source = ` i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Message description' }); `; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -71,7 +71,7 @@ i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Mes test('throws if properties object is not provided', () => { const source = `i18n('message-id');`; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -83,7 +83,7 @@ i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Mes const message = 'Default message'; i18n('message-id', { defaultMessage: message }); `; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -92,7 +92,7 @@ i18n('message-id', { defaultMessage: message }); test('throws on empty defaultMessage', () => { const source = `i18n('message-id', { defaultMessage: '' });`; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); diff --git a/src/dev/i18n/extractors/pug.js b/src/dev/i18n/extractors/pug.js index a19d2183af2a1..20fc72a404843 100644 --- a/src/dev/i18n/extractors/pug.js +++ b/src/dev/i18n/extractors/pug.js @@ -56,7 +56,9 @@ export function* extractPugMessages(buffer, reporter) { for (const expression of expressions) { try { const ast = parsePugExpression(expression); - const node = [...traverseNodes(ast.program.body)].find(node => isI18nTranslateFunction(node)); + const node = [...traverseNodes(ast.program.body)].find((node) => + isI18nTranslateFunction(node) + ); if (node) { yield extractI18nCallMessages(node); diff --git a/src/dev/i18n/extractors/react.js b/src/dev/i18n/extractors/react.js index b5a55a825312b..6d3719faaeb61 100644 --- a/src/dev/i18n/extractors/react.js +++ b/src/dev/i18n/extractors/react.js @@ -50,7 +50,7 @@ export function extractIntlMessages(node) { 'id', DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, - ].map(key => options.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => options.properties.find((property) => isPropertyWithKey(property, key))); const messageId = messageIdProperty ? formatJSString(extractMessageIdFromNode(messageIdProperty.value)) @@ -92,7 +92,9 @@ export function extractFormattedMessages(node) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => node.attributes.find(attribute => isJSXIdentifier(attribute.name, { name: key }))); + ].map((key) => + node.attributes.find((attribute) => isJSXIdentifier(attribute.name, { name: key })) + ); const messageId = messageIdAttribute ? formatHTMLString(extractMessageIdFromNode(messageIdAttribute.value)) diff --git a/src/dev/i18n/extractors/react.test.js b/src/dev/i18n/extractors/react.test.js index d363672626ee9..f6fc85d28f139 100644 --- a/src/dev/i18n/extractors/react.test.js +++ b/src/dev/i18n/extractors/react.test.js @@ -83,7 +83,7 @@ describe('dev/i18n/extractors/react', () => { describe('extractIntlMessages', () => { test('extracts messages from "intl.formatMessage" function call', () => { const ast = parse(intlFormatMessageCallSource, { plugins: ['jsx'] }); - const expressionNode = [...traverseNodes(ast.program.body)].find(node => + const expressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -93,7 +93,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if message id is not a string literal', () => { const source = intlFormatMessageCallErrorSources[0]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -103,7 +103,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if defaultMessage value is not a string literal', () => { const source = intlFormatMessageCallErrorSources[1]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -113,7 +113,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if description value is not a string literal', () => { const source = intlFormatMessageCallErrorSources[2]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -125,7 +125,7 @@ describe('dev/i18n/extractors/react', () => { test('extracts messages from "" element', () => { const ast = parse(formattedMessageElementSource, { plugins: ['jsx'] }); const jsxOpeningElementNode = [...traverseNodes(ast.program.body)].find( - node => + (node) => isJSXOpeningElement(node) && isJSXIdentifier(node.name, { name: 'FormattedMessage' }) ); diff --git a/src/dev/i18n/integrate_locale_files.ts b/src/dev/i18n/integrate_locale_files.ts index 2ac8768ed72ad..d8ccccca15559 100644 --- a/src/dev/i18n/integrate_locale_files.ts +++ b/src/dev/i18n/integrate_locale_files.ts @@ -116,7 +116,7 @@ function groupMessagesByNamespace( ) { const localizedMessagesByNamespace = new Map(); for (const [messageId, messageValue] of localizedMessagesMap) { - const namespace = knownNamespaces.find(key => messageId.startsWith(`${key}.`)); + const namespace = knownNamespaces.find((key) => messageId.startsWith(`${key}.`)); if (!namespace) { throw createFailError(`Unknown namespace in id ${messageId}.`); } diff --git a/src/dev/i18n/serializers/json5.ts b/src/dev/i18n/serializers/json5.ts index 5b09764ce4d9b..a1c89d5ff8cf2 100644 --- a/src/dev/i18n/serializers/json5.ts +++ b/src/dev/i18n/serializers/json5.ts @@ -26,9 +26,7 @@ const ESCAPE_SINGLE_QUOTE_REGEX = /\\([\s\S])|(')/g; export const serializeToJson5: Serializer = (messages, formats = i18n.formats) => { // .slice(0, -4): remove closing curly braces from json to append messages let jsonBuffer = Buffer.from( - JSON5.stringify({ formats, messages: {} }, { quote: `'`, space: 2 }) - .slice(0, -4) - .concat('\n') + JSON5.stringify({ formats, messages: {} }, { quote: `'`, space: 2 }).slice(0, -4).concat('\n') ); for (const [mapKey, mapValue] of messages) { diff --git a/src/dev/i18n/tasks/check_compatibility.ts b/src/dev/i18n/tasks/check_compatibility.ts index 3c5f8c23466a4..5900bf5aff252 100644 --- a/src/dev/i18n/tasks/check_compatibility.ts +++ b/src/dev/i18n/tasks/check_compatibility.ts @@ -29,7 +29,7 @@ export interface I18nFlags { export function checkCompatibility(config: I18nConfig, flags: I18nFlags, log: ToolingLog) { const { fix, ignoreIncompatible, ignoreUnused, ignoreMissing } = flags; - return config.translations.map(translationsPath => ({ + return config.translations.map((translationsPath) => ({ task: async ({ messages }: { messages: Map }) => { // If `fix` is set we should try apply all possible fixes and override translations file. await integrateLocaleFiles(messages, { diff --git a/src/dev/i18n/tasks/check_configs.ts b/src/dev/i18n/tasks/check_configs.ts index ffb9a499fbb43..89d55cae07ffd 100644 --- a/src/dev/i18n/tasks/check_configs.ts +++ b/src/dev/i18n/tasks/check_configs.ts @@ -28,7 +28,7 @@ export function checkConfigs(additionalConfigPaths: string | string[] = []) { const configPaths = [kibanaRC, xpackRC, ...arrayify(additionalConfigPaths)]; - return configPaths.map(configPath => ({ + return configPaths.map((configPath) => ({ task: async (context: { reporter: ErrorReporter }) => { try { await checkConfigNamespacePrefix(configPath); diff --git a/src/dev/i18n/tasks/extract_default_translations.ts b/src/dev/i18n/tasks/extract_default_translations.ts index 8ff2bc14abafd..b8f4ede69526d 100644 --- a/src/dev/i18n/tasks/extract_default_translations.ts +++ b/src/dev/i18n/tasks/extract_default_translations.ts @@ -30,7 +30,7 @@ export function extractDefaultMessages(config: I18nConfig, inputPaths: string[]) )} None of input paths is covered by the mappings in .i18nrc.json.` ); } - return filteredPaths.map(filteredPath => ({ + return filteredPaths.map((filteredPath) => ({ task: async (context: { messages: Map; reporter: ErrorReporter; diff --git a/src/dev/i18n/tasks/extract_untracked_translations.ts b/src/dev/i18n/tasks/extract_untracked_translations.ts index 7c640d566dea2..39f8a1cc59c6b 100644 --- a/src/dev/i18n/tasks/extract_untracked_translations.ts +++ b/src/dev/i18n/tasks/extract_untracked_translations.ts @@ -67,10 +67,10 @@ export async function extractUntrackedMessagesTask({ for (const [entries, extractFunction] of categorizedEntries) { const files = await Promise.all( filterEntries(entries, config.exclude) - .filter(entry => { + .filter((entry) => { const normalizedEntry = normalizePath(entry); return !availablePaths.some( - availablePath => + (availablePath) => normalizedEntry.startsWith(`${normalizePath(availablePath)}/`) || normalizePath(availablePath) === normalizedEntry ); @@ -93,7 +93,7 @@ export async function extractUntrackedMessagesTask({ } export function extractUntrackedMessages(inputPaths: string[]) { - return inputPaths.map(inputPath => ({ + return inputPaths.map((inputPath) => ({ title: `Checking untracked messages in ${inputPath}`, task: async (context: { reporter: ErrorReporter; config: I18nConfig }) => { const { reporter, config } = context; diff --git a/src/dev/i18n/tasks/merge_configs.ts b/src/dev/i18n/tasks/merge_configs.ts index ec005f0ce9367..6e7b89fe4a668 100644 --- a/src/dev/i18n/tasks/merge_configs.ts +++ b/src/dev/i18n/tasks/merge_configs.ts @@ -27,7 +27,7 @@ export function mergeConfigs(additionalConfigPaths: string | string[] = []) { const configPaths = [kibanaRC, xpackRC, ...arrayify(additionalConfigPaths)]; - return configPaths.map(configPath => ({ + return configPaths.map((configPath) => ({ task: async (context: { reporter: ErrorReporter; config?: I18nConfig }) => { try { context.config = await assignConfigFromPath(context.config, configPath); diff --git a/src/dev/i18n/utils.js b/src/dev/i18n/utils.js index 091056c0837c3..1d1c3118e0852 100644 --- a/src/dev/i18n/utils.js +++ b/src/dev/i18n/utils.js @@ -55,7 +55,7 @@ export function normalizePath(inputPath) { } export function difference(left = [], right = []) { - return left.filter(value => !right.includes(value)); + return left.filter((value) => !right.includes(value)); } export function isPropertyWithKey(property, identifierName) { @@ -103,7 +103,9 @@ export function* traverseNodes(nodes) { // if node is an object / array, traverse all of its object values if (node && typeof node === 'object') { - yield* traverseNodes(Object.values(node).filter(value => value && typeof value === 'object')); + yield* traverseNodes( + Object.values(node).filter((value) => value && typeof value === 'object') + ); } } } @@ -187,7 +189,7 @@ export function checkValuesProperty(prefixedValuesKeys, defaultMessage, messageI return; } - const valuesKeys = prefixedValuesKeys.map(key => + const valuesKeys = prefixedValuesKeys.map((key) => key.startsWith(HTML_KEY_PREFIX) ? key.slice(HTML_KEY_PREFIX.length) : key ); @@ -309,7 +311,7 @@ export function extractValuesKeysFromNode(node, messageId) { throw createFailError(`"values" value should be an inline object literal ("${messageId}").`); } - return node.properties.map(property => + return node.properties.map((property) => isStringLiteral(property.key) ? property.key.value : property.key.name ); } @@ -318,7 +320,7 @@ export class ErrorReporter { errors = []; withContext(context) { - return { report: error => this.report(error, context) }; + return { report: (error) => this.report(error, context) }; } report(error, context) { diff --git a/src/dev/i18n/utils.test.js b/src/dev/i18n/utils.test.js index 7019218d4e249..49c42d3b577ad 100644 --- a/src/dev/i18n/utils.test.js +++ b/src/dev/i18n/utils.test.js @@ -32,7 +32,7 @@ import { } from './utils'; const i18nTranslateSources = ['i18n', 'i18n.translate'].map( - callee => ` + (callee) => ` ${callee}('plugin_1.id_1', { values: { key: 'value', @@ -64,14 +64,14 @@ describe('i18n utils', () => { test('should detect i18n translate function call', () => { let source = i18nTranslateSources[0]; - let expressionStatementNode = [...traverseNodes(parse(source).program.body)].find(node => + let expressionStatementNode = [...traverseNodes(parse(source).program.body)].find((node) => isExpressionStatement(node) ); expect(isI18nTranslateFunction(expressionStatementNode.expression)).toBe(true); source = i18nTranslateSources[1]; - expressionStatementNode = [...traverseNodes(parse(source).program.body)].find(node => + expressionStatementNode = [...traverseNodes(parse(source).program.body)].find((node) => isExpressionStatement(node) ); @@ -81,7 +81,7 @@ describe('i18n utils', () => { test('should detect object property with defined key', () => { const objectExpresssionNode = [ ...traverseNodes(parse(objectPropertySource).program.body), - ].find(node => isObjectExpression(node)); + ].find((node) => isObjectExpression(node)); const [objectExpresssionProperty] = objectExpresssionNode.properties; expect(isPropertyWithKey(objectExpresssionProperty, 'id')).toBe(true); @@ -183,7 +183,7 @@ describe('i18n utils', () => { i18n('namespace.id', { defaultMessage: 'Very ' + 'long ' + 'concatenated ' + 'string', });`; - const objectProperty = [...traverseNodes(parse(source).program.body)].find(node => + const objectProperty = [...traverseNodes(parse(source).program.body)].find((node) => isObjectProperty(node) ); diff --git a/src/dev/jest/config.integration.js b/src/dev/jest/config.integration.js index e13d0289a7e9b..2fd6bd120d553 100644 --- a/src/dev/jest/config.integration.js +++ b/src/dev/jest/config.integration.js @@ -27,7 +27,7 @@ export default { '**/integration_tests/**/*.test.tsx', ], testPathIgnorePatterns: config.testPathIgnorePatterns.filter( - pattern => !pattern.includes('integration_tests') + (pattern) => !pattern.includes('integration_tests') ), reporters: [ 'default', diff --git a/src/dev/jest/junit_reporter.js b/src/dev/jest/junit_reporter.js index 0f8003f4ed6a1..f33358c081a06 100644 --- a/src/dev/jest/junit_reporter.js +++ b/src/dev/jest/junit_reporter.js @@ -58,8 +58,8 @@ export default class JestJUnitReporter { { skipNullAttributes: true } ); - const msToIso = ms => (ms ? new Date(ms).toISOString().slice(0, -5) : undefined); - const msToSec = ms => (ms ? (ms / 1000).toFixed(3) : undefined); + const msToIso = (ms) => (ms ? new Date(ms).toISOString().slice(0, -5) : undefined); + const msToSec = (ms) => (ms ? (ms / 1000).toFixed(3) : undefined); root.att({ name: 'jest', @@ -71,7 +71,7 @@ export default class JestJUnitReporter { }); // top level test results are the files/suites - results.testResults.forEach(suite => { + results.testResults.forEach((suite) => { const suiteEl = root.ele('testsuite', { name: relative(rootDirectory, suite.testFilePath), timestamp: msToIso(suite.perfStats.start), @@ -85,14 +85,14 @@ export default class JestJUnitReporter { // nested in there are the tests in that file const relativePath = dirname(relative(rootDirectory, suite.testFilePath)); const classname = `${reportName}.${relativePath.replace(/\./g, '·')}`; - suite.testResults.forEach(test => { + suite.testResults.forEach((test) => { const testEl = suiteEl.ele('testcase', { classname, name: [...test.ancestorTitles, test.title].join(' '), time: msToSec(test.duration), }); - test.failureMessages.forEach(message => { + test.failureMessages.forEach((message) => { testEl.ele('failure').dat(escapeCdata(message)); }); diff --git a/src/dev/jest/setup/mocks.js b/src/dev/jest/setup/mocks.js index 095c82bd50fbd..6e7160e858cd7 100644 --- a/src/dev/jest/setup/mocks.js +++ b/src/dev/jest/setup/mocks.js @@ -54,6 +54,6 @@ jest.mock('@elastic/eui/lib/services/react', () => { // This is for performance, but when used in certain Jest scernarios it can be nondeterministic. // Jest tests are never concerned about the state prior to batch completion, so we bypass batching entirely. return { - enqueueStateChange: fn => fn(), + enqueueStateChange: (fn) => fn(), }; }); diff --git a/src/dev/jest/setup/polyfills.js b/src/dev/jest/setup/polyfills.js index a3342883d084e..9e4f1db9ac289 100644 --- a/src/dev/jest/setup/polyfills.js +++ b/src/dev/jest/setup/polyfills.js @@ -20,7 +20,7 @@ // bluebird < v3.3.5 does not work with MutationObserver polyfill // when MutationObserver exists, bluebird avoids using node's builtin async schedulers const bluebird = require('bluebird'); -bluebird.Promise.setScheduler(function(fn) { +bluebird.Promise.setScheduler(function (fn) { global.setImmediate.call(global, fn); }); diff --git a/src/dev/license_checker/run_check_licenses_cli.ts b/src/dev/license_checker/run_check_licenses_cli.ts index b011e8ff6ecb2..0267a1a90d4fe 100644 --- a/src/dev/license_checker/run_check_licenses_cli.ts +++ b/src/dev/license_checker/run_check_licenses_cli.ts @@ -35,7 +35,7 @@ run( // Assert if the found licenses in the production // packages are valid assertLicensesValid({ - packages: packages.filter(pkg => !pkg.isDevOnly), + packages: packages.filter((pkg) => !pkg.isDevOnly), validLicenses: LICENSE_WHITELIST, }); log.success('All production dependency licenses are allowed'); @@ -44,7 +44,7 @@ run( // if the dev flag is found if (flags.dev) { assertLicensesValid({ - packages: packages.filter(pkg => pkg.isDevOnly), + packages: packages.filter((pkg) => pkg.isDevOnly), validLicenses: LICENSE_WHITELIST.concat(DEV_ONLY_LICENSE_WHITELIST), }); log.success('All development dependency licenses are allowed'); diff --git a/src/dev/license_checker/valid.ts b/src/dev/license_checker/valid.ts index 9142955185a1a..f24f8a9bfdba7 100644 --- a/src/dev/license_checker/valid.ts +++ b/src/dev/license_checker/valid.ts @@ -37,7 +37,7 @@ interface Options { */ export function assertLicensesValid({ packages, validLicenses }: Options) { const invalidMsgs = packages.reduce((acc, pkg) => { - const invalidLicenses = pkg.licenses.filter(license => !validLicenses.includes(license)); + const invalidLicenses = pkg.licenses.filter((license) => !validLicenses.includes(license)); if (pkg.licenses.length && !invalidLicenses.length) { return acc; @@ -57,7 +57,7 @@ export function assertLicensesValid({ packages, validLicenses }: Options) { `Non-conforming licenses:\n${invalidMsgs .join('\n') .split('\n') - .map(l => ` ${l}`) + .map((l) => ` ${l}`) .join('\n')}` ); } diff --git a/src/dev/notice/bundled_notices.js b/src/dev/notice/bundled_notices.js index 1bdf526460016..a4710a79b0610 100644 --- a/src/dev/notice/bundled_notices.js +++ b/src/dev/notice/bundled_notices.js @@ -25,11 +25,11 @@ import glob from 'glob'; export async function getBundledNotices(packageDirectory) { const pattern = resolve(packageDirectory, '*{LICENSE,NOTICE}*'); - const paths = await fcb(cb => glob(pattern, cb)); + const paths = await fcb((cb) => glob(pattern, cb)); return Promise.all( - paths.map(async path => ({ + paths.map(async (path) => ({ path, - text: await fcb(cb => readFile(path, 'utf8', cb)), + text: await fcb((cb) => readFile(path, 'utf8', cb)), })) ); } diff --git a/src/dev/notice/cli.js b/src/dev/notice/cli.js index e5377d7f177d2..34217ef48a33b 100644 --- a/src/dev/notice/cli.js +++ b/src/dev/notice/cli.js @@ -41,7 +41,7 @@ const log = new ToolingLog({ }); if (unknownFlags.length) { - log.error(`Unknown flags ${unknownFlags.map(f => `"${f}"`).join(',')}`); + log.error(`Unknown flags ${unknownFlags.map((f) => `"${f}"`).join(',')}`); process.exitCode = 1; opts.help = true; } @@ -90,7 +90,7 @@ if (opts.help) { 'NOTICE.txt is out of date, run `node scripts/notice` to update and commit the results.' ); process.exit(1); -})().catch(error => { +})().catch((error) => { log.error(error); process.exit(1); }); diff --git a/src/dev/notice/generate_notice_from_source.ts b/src/dev/notice/generate_notice_from_source.ts index 6dd47db929f45..fb74bed0f26f4 100644 --- a/src/dev/notice/generate_notice_from_source.ts +++ b/src/dev/notice/generate_notice_from_source.ts @@ -62,7 +62,7 @@ export async function generateNoticeFromSource({ productName, directory, log }: const noticeComments: string[] = []; await new Promise((resolve, reject) => { files - .on('data', file => { + .on('data', (file) => { log.verbose(`Checking for @notice comments in ${file.relative}`); const source = file.contents.toString('utf8'); @@ -86,7 +86,7 @@ export async function generateNoticeFromSource({ productName, directory, log }: noticeText += '\n---\n'; noticeText += comment .split(NEWLINE_RE) - .map(line => + .map((line) => line // trim whitespace .trim() diff --git a/src/dev/notice/generate_package_notice_text.js b/src/dev/notice/generate_package_notice_text.js index 77c080d258e12..673f34fc57bf1 100644 --- a/src/dev/notice/generate_package_notice_text.js +++ b/src/dev/notice/generate_package_notice_text.js @@ -19,7 +19,7 @@ import { getBundledNotices } from './bundled_notices'; -const concatNotices = notices => notices.map(notice => notice.text).join('\n'); +const concatNotices = (notices) => notices.map((notice) => notice.text).join('\n'); export async function generatePackageNoticeText(pkg) { const bundledNotices = concatNotices(await getBundledNotices(pkg.directory)); diff --git a/src/dev/npm/integration_tests/installed_packages.test.ts b/src/dev/npm/integration_tests/installed_packages.test.ts index 75cd0e5607698..58c954cbc12f7 100644 --- a/src/dev/npm/integration_tests/installed_packages.test.ts +++ b/src/dev/npm/integration_tests/installed_packages.test.ts @@ -27,11 +27,11 @@ import { REPO_ROOT } from '../../constants'; const FIXTURE1_ROOT = resolve(__dirname, '__fixtures__/fixture1'); describe('src/dev/npm/installed_packages', () => { - describe('getInstalledPackages()', function() { + describe('getInstalledPackages()', function () { let kibanaPackages: InstalledPackage[]; let fixture1Packages: InstalledPackage[]; - beforeAll(async function() { + beforeAll(async function () { [kibanaPackages, fixture1Packages] = await Promise.all([ getInstalledPackages({ directory: REPO_ROOT, @@ -76,16 +76,16 @@ describe('src/dev/npm/installed_packages', () => { }); it('returns a single entry for every package/version combo', () => { - const tags = kibanaPackages.map(pkg => `${pkg.name}@${pkg.version}`); + const tags = kibanaPackages.map((pkg) => `${pkg.name}@${pkg.version}`); expect(tags).toEqual(uniq(tags)); }); it('does not include root package in the list', () => { - if (kibanaPackages.find(pkg => pkg.name === 'kibana')) { + if (kibanaPackages.find((pkg) => pkg.name === 'kibana')) { throw new Error('Expected getInstalledPackages(kibana) to not include kibana pkg'); } - if (fixture1Packages.find(pkg => pkg.name === 'fixture1')) { + if (fixture1Packages.find((pkg) => pkg.name === 'fixture1')) { throw new Error('Expected getInstalledPackages(fixture1) to not include fixture1 pkg'); } }); diff --git a/src/dev/precommit_hook/check_file_casing.js b/src/dev/precommit_hook/check_file_casing.js index be0fbe22457bf..ec77d9a8bad3c 100644 --- a/src/dev/precommit_hook/check_file_casing.js +++ b/src/dev/precommit_hook/check_file_casing.js @@ -35,7 +35,7 @@ const NON_SNAKE_CASE_RE = /[A-Z \-]/; const NON_KEBAB_CASE_RE = /[A-Z \_]/; function listPaths(paths) { - return paths.map(path => ` - ${path}`).join('\n'); + return paths.map((path) => ` - ${path}`).join('\n'); } /** @@ -78,7 +78,7 @@ async function checkForKebabCase(log, files) { return acc.concat( parents.filter( - parent => + (parent) => matchesAnyGlob(parent, KEBAB_CASE_DIRECTORY_GLOBS) && NON_KEBAB_CASE_RE.test(basename(parent)) ) @@ -109,7 +109,7 @@ async function checkForSnakeCase(log, files) { const errorPaths = []; const warningPaths = []; - files.forEach(file => { + files.forEach((file) => { const path = file.getRelativePath(); if (TEMPORARILY_IGNORED_PATHS.includes(path)) { diff --git a/src/dev/precommit_hook/get_files_for_commit.js b/src/dev/precommit_hook/get_files_for_commit.js index 418e6d1d0a852..dc5560be0d1ad 100644 --- a/src/dev/precommit_hook/get_files_for_commit.js +++ b/src/dev/precommit_hook/get_files_for_commit.js @@ -33,16 +33,16 @@ import { File } from '../file'; export async function getFilesForCommit() { const simpleGit = new SimpleGit(REPO_ROOT); - const output = await fcb(cb => simpleGit.diff(['--name-status', '--cached'], cb)); + const output = await fcb((cb) => simpleGit.diff(['--name-status', '--cached'], cb)); return ( output .split('\n') // Ignore blank lines - .filter(line => line.trim().length > 0) + .filter((line) => line.trim().length > 0) // git diff --name-status outputs lines with two OR three parts // separated by a tab character - .map(line => line.trim().split('\t')) + .map((line) => line.trim().split('\t')) .map(([status, ...paths]) => { // ignore deleted files if (status === 'D') { diff --git a/src/dev/prs/helpers.ts b/src/dev/prs/helpers.ts index d25db1a79a1b9..b10b30806942b 100644 --- a/src/dev/prs/helpers.ts +++ b/src/dev/prs/helpers.ts @@ -25,7 +25,7 @@ import { takeUntil } from 'rxjs/operators'; * Convert a Readable stream to an observable of lines */ export const getLine$ = (stream: Readable) => { - return new Rx.Observable(subscriber => { + return new Rx.Observable((subscriber) => { let buffer = ''; return Rx.fromEvent(stream, 'data') .pipe(takeUntil(Rx.fromEvent(stream, 'close'))) diff --git a/src/dev/prs/run_update_prs_cli.ts b/src/dev/prs/run_update_prs_cli.ts index bb7f50758a28c..49668199a26d4 100644 --- a/src/dev/prs/run_update_prs_cli.ts +++ b/src/dev/prs/run_update_prs_cli.ts @@ -48,7 +48,7 @@ run( throw createFlagError('invalid --repo-dir, expected a single string'); } - const prNumbers = flags._.map(arg => Pr.parseInput(arg)); + const prNumbers = flags._.map((arg) => Pr.parseInput(arg)); /** * Call the Gitub API once for each PR to get the targetRef so we know which branch to pull @@ -56,7 +56,7 @@ run( */ const api = new GithubApi(accessToken); const prs = await Promise.all( - prNumbers.map(async prNumber => { + prNumbers.map(async (prNumber) => { const { targetRef, owner, sourceBranch } = await api.getPrInfo(prNumber); return new Pr(prNumber, targetRef, owner, sourceBranch); }) @@ -73,7 +73,7 @@ run( await Promise.all([ proc.then(() => log.debug(` - ${cmd} exited with 0`)), Rx.merge(getLine$(proc.stdout), getLine$(proc.stderr)) - .pipe(tap(line => log.debug(line))) + .pipe(tap((line) => log.debug(line))) .toPromise(), ]); }; @@ -130,9 +130,7 @@ run( `) + '\n' ); - await getLine$(process.stdin) - .pipe(first()) - .toPromise(); + await getLine$(process.stdin).pipe(first()).toPromise(); try { await execInDir('git', ['diff-index', '--quiet', 'HEAD', '--']); diff --git a/src/dev/renovate/config.ts b/src/dev/renovate/config.ts index fae424982c930..09283e6a5bf2d 100644 --- a/src/dev/renovate/config.ts +++ b/src/dev/renovate/config.ts @@ -85,11 +85,11 @@ export const RENOVATE_CONFIG = { * Define groups of packages that should be updated/configured together */ packageRules: [ - ...RENOVATE_PACKAGE_GROUPS.map(group => ({ + ...RENOVATE_PACKAGE_GROUPS.map((group) => ({ groupSlug: group.name, groupName: `${group.name} related packages`, - packagePatterns: maybeMap(group.packageWords, word => wordRegExp(word).source), - packageNames: maybeFlatMap(group.packageNames, name => [name, getTypePackageName(name)]), + packagePatterns: maybeMap(group.packageWords, (word) => wordRegExp(word).source), + packageNames: maybeFlatMap(group.packageNames, (name) => [name, getTypePackageName(name)]), labels: group.extraLabels && [...DEFAULT_LABELS, ...group.extraLabels], enabled: group.enabled === false ? false : undefined, allowedVersions: group.allowedVersions || undefined, diff --git a/src/dev/renovate/package_groups.ts b/src/dev/renovate/package_groups.ts index 9f5aa8556ac21..d051f956d14df 100644 --- a/src/dev/renovate/package_groups.ts +++ b/src/dev/renovate/package_groups.ts @@ -214,9 +214,9 @@ for (const dep of getAllDepNames()) { // determine if one of the existing groups has typesFor in its // packageNames or if any of the packageWords is in typesFor const existing = RENOVATE_PACKAGE_GROUPS.some( - group => + (group) => (group.packageNames || []).includes(typesFor) || - (group.packageWords || []).some(word => wordRegExp(word).test(typesFor)) + (group.packageWords || []).some((word) => wordRegExp(word).test(typesFor)) ); if (existing) { diff --git a/src/dev/run_check_file_casing.js b/src/dev/run_check_file_casing.js index 87107b43d9ba0..bdbf1827897e7 100644 --- a/src/dev/run_check_file_casing.js +++ b/src/dev/run_check_file_casing.js @@ -39,7 +39,7 @@ run(async ({ log }) => { ], }); - const files = paths.map(path => new File(path)); + const files = paths.map((path) => new File(path)); await checkFileCasing(log, files); }); diff --git a/src/dev/run_check_lockfile_symlinks.js b/src/dev/run_check_lockfile_symlinks.js index b912ea9ddb87e..5ebb7952e2cf3 100644 --- a/src/dev/run_check_lockfile_symlinks.js +++ b/src/dev/run_check_lockfile_symlinks.js @@ -55,13 +55,15 @@ run(async ({ log }) => { ], }); - const files = paths.map(path => new File(path)); + const files = paths.map((path) => new File(path)); await checkLockfileSymlinks(log, files); }); async function checkLockfileSymlinks(log, files) { - const filtered = files.filter(file => !matchesAnyGlob(file.getRelativePath(), IGNORE_FILE_GLOBS)); + const filtered = files.filter( + (file) => !matchesAnyGlob(file.getRelativePath(), IGNORE_FILE_GLOBS) + ); await checkOnlyLockfileAtProjectRoot(filtered); await checkSuperfluousSymlinks(log, filtered); await checkMissingSymlinks(log, filtered); @@ -72,8 +74,8 @@ async function checkOnlyLockfileAtProjectRoot(files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const stats = lstatSync(path); @@ -93,8 +95,8 @@ async function checkSuperfluousSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const stats = lstatSync(path); @@ -146,8 +148,8 @@ async function checkMissingSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), MANIFEST_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), MANIFEST_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const lockfilePath = `${parent}/yarn.lock`; @@ -185,8 +187,8 @@ async function checkIncorrectSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const stats = lstatSync(path); if (!stats.isSymbolicLink()) { @@ -218,5 +220,5 @@ function getCorrectSymlink(path) { } function listPaths(paths) { - return paths.map(path => ` - ${path}`).join('\n'); + return paths.map((path) => ` - ${path}`).join('\n'); } diff --git a/src/dev/run_check_published_api_changes.ts b/src/dev/run_check_published_api_changes.ts index 6d5fa04a93951..45dafe1b415e3 100644 --- a/src/dev/run_check_published_api_changes.ts +++ b/src/dev/run_check_published_api_changes.ts @@ -268,14 +268,14 @@ async function run( const results = await Promise.all( folders - .filter(folder => (opts.filter.length ? folder.match(opts.filter) : true)) - .map(folder => run(folder, { log, opts })) + .filter((folder) => (opts.filter.length ? folder.match(opts.filter) : true)) + .map((folder) => run(folder, { log, opts })) ); - if (results.find(r => r === false) !== undefined) { + if (results.find((r) => r === false) !== undefined) { process.exitCode = 1; } -})().catch(e => { +})().catch((e) => { console.log(e); process.exitCode = 1; }); diff --git a/src/dev/run_i18n_extract.ts b/src/dev/run_i18n_extract.ts index 106c8f10cb5cc..208c86d4acecc 100644 --- a/src/dev/run_i18n_extract.ts +++ b/src/dev/run_i18n_extract.ts @@ -60,8 +60,8 @@ run( }, { title: 'Writing to file', - enabled: ctx => outputDir && ctx.messages.size, - task: async ctx => { + enabled: (ctx) => outputDir && ctx.messages.size, + task: async (ctx) => { const sortedMessages = [...ctx.messages].sort(([key1], [key2]) => key1.localeCompare(key2) ); diff --git a/src/dev/run_prettier_on_changed.ts b/src/dev/run_prettier_on_changed.ts index deca4fa1be3ce..776d4d5ffd389 100644 --- a/src/dev/run_prettier_on_changed.ts +++ b/src/dev/run_prettier_on_changed.ts @@ -57,10 +57,10 @@ run(async function getChangedFiles({ log }) { const changedFiles = changedFileStatuses .split('\n') // Ignore blank lines - .filter(line => line.trim().length > 0) + .filter((line) => line.trim().length > 0) // git diff --name-status outputs lines with two OR three parts // separated by a tab character - .map(line => line.trim().split('\t')) + .map((line) => line.trim().split('\t')) .map(([status, ...paths]) => { // ignore deleted files if (status === 'D') { @@ -75,7 +75,7 @@ run(async function getChangedFiles({ log }) { }) .filter((file): file is File => Boolean(file)); - const pathsToLint = Eslint.pickFilesToLint(log, changedFiles).map(f => f.getAbsolutePath()); + const pathsToLint = Eslint.pickFilesToLint(log, changedFiles).map((f) => f.getAbsolutePath()); if (pathsToLint.length > 0) { log.debug('[prettier] run on %j files: ', pathsToLint.length, pathsToLint); diff --git a/src/dev/sass/build_sass.js b/src/dev/sass/build_sass.js index 1ff7c700d0386..7075bcf55adf5 100644 --- a/src/dev/sass/build_sass.js +++ b/src/dev/sass/build_sass.js @@ -44,7 +44,7 @@ const build = async ({ log, kibanaDir, styleSheetPaths, watch }) => { sourceMap: true, }); - bundles.forEach(bundle => { + bundles.forEach((bundle) => { log.debug(`Compiled SCSS: ${bundle.sourcePath} (theme=${bundle.theme})`); }); @@ -63,9 +63,7 @@ export async function buildSass({ log, kibanaDir, watch }) { const scanDirs = [resolve(kibanaDir, 'src/legacy/core_plugins')]; const paths = [resolve(kibanaDir, 'x-pack')]; const { spec$, disabledSpec$ } = findPluginSpecs({ plugins: { scanDirs, paths } }); - const allPlugins = await Rx.merge(spec$, disabledSpec$) - .pipe(toArray()) - .toPromise(); + const allPlugins = await Rx.merge(spec$, disabledSpec$).pipe(toArray()).toPromise(); const uiExports = collectUiExports(allPlugins); const { styleSheetPaths } = uiExports; @@ -73,17 +71,17 @@ export async function buildSass({ log, kibanaDir, watch }) { log.verbose(styleSheetPaths); if (watch) { - const debouncedBuild = debounce(async path => { + const debouncedBuild = debounce(async (path) => { let buildPaths = styleSheetPaths; if (path) { - buildPaths = styleSheetPaths.filter(styleSheetPath => + buildPaths = styleSheetPaths.filter((styleSheetPath) => path.includes(styleSheetPath.urlImports.publicDir) ); } await build({ log, kibanaDir, styleSheetPaths: buildPaths, watch }); }); - const watchPaths = styleSheetPaths.map(styleSheetPath => styleSheetPath.urlImports.publicDir); + const watchPaths = styleSheetPaths.map((styleSheetPath) => styleSheetPath.urlImports.publicDir); await build({ log, kibanaDir, styleSheetPaths }); diff --git a/src/dev/sasslint/lint_files.js b/src/dev/sasslint/lint_files.js index b9df6a1fa9abb..3a560b4a6ea1a 100644 --- a/src/dev/sasslint/lint_files.js +++ b/src/dev/sasslint/lint_files.js @@ -30,7 +30,7 @@ import { createFailError } from '@kbn/dev-utils'; * @return {undefined} */ export function lintFiles(log, files) { - const paths = files.map(file => file.getRelativePath()); + const paths = files.map((file) => file.getRelativePath()); const report = sassLint.lintFiles( paths.join(', '), diff --git a/src/dev/sasslint/pick_files_to_lint.js b/src/dev/sasslint/pick_files_to_lint.js index c4d8af7bb674f..57c38d0069e06 100644 --- a/src/dev/sasslint/pick_files_to_lint.js +++ b/src/dev/sasslint/pick_files_to_lint.js @@ -28,7 +28,7 @@ const sassLintConfig = safeLoad(fs.readFileSync(sassLintPath)); const { files: { include: includeGlobs }, } = sassLintConfig; -const includeRegex = includeGlobs.map(glob => makeRe(glob)); +const includeRegex = includeGlobs.map((glob) => makeRe(glob)); function matchesInclude(file) { for (let i = 0; i < includeRegex.length; i++) { @@ -40,5 +40,5 @@ function matchesInclude(file) { } export function pickFilesToLint(log, files) { - return files.filter(file => file.isSass()).filter(matchesInclude); + return files.filter((file) => file.isSass()).filter(matchesInclude); } diff --git a/src/dev/storybook/run_storybook_cli.ts b/src/dev/storybook/run_storybook_cli.ts index efb618a48cd6e..7f97cff91aaaa 100644 --- a/src/dev/storybook/run_storybook_cli.ts +++ b/src/dev/storybook/run_storybook_cli.ts @@ -24,7 +24,7 @@ import { storybookAliases } from './aliases'; import { clean } from './commands/clean'; run( - async params => { + async (params) => { const { flags, log } = params; const { _: [alias], @@ -62,7 +62,7 @@ run( Available aliases: ${Object.keys(storybookAliases) - .map(alias => `📕 ${alias}`) + .map((alias) => `📕 ${alias}`) .join('\n ')} Add your alias in src/dev/storybook/aliases.ts diff --git a/src/dev/typescript/exec_in_projects.ts b/src/dev/typescript/exec_in_projects.ts index a34f2bdd28670..5197aa67c7268 100644 --- a/src/dev/typescript/exec_in_projects.ts +++ b/src/dev/typescript/exec_in_projects.ts @@ -37,7 +37,7 @@ export function execInProjects( getArgs: (project: Project) => string[] ) { const list = new Listr( - projects.map(project => ({ + projects.map((project) => ({ task: () => execa(cmd, getArgs(project), { // execute in the current working directory so that relative paths in errors @@ -46,7 +46,7 @@ export function execInProjects( env: chalk.enabled ? { FORCE_COLOR: 'true' } : {}, stdio: ['ignore', 'pipe', 'pipe'], preferLocal: true, - }).catch(error => { + }).catch((error) => { throw new ProjectFailure(project, error); }), title: project.name, diff --git a/src/dev/typescript/get_ts_project_for_absolute_path.ts b/src/dev/typescript/get_ts_project_for_absolute_path.ts index 68ce70685b607..54d7e950834a4 100644 --- a/src/dev/typescript/get_ts_project_for_absolute_path.ts +++ b/src/dev/typescript/get_ts_project_for_absolute_path.ts @@ -35,7 +35,7 @@ import { PROJECTS } from './projects'; export function getTsProjectForAbsolutePath(path: string): Project { const relPath = relative(REPO_ROOT, path); const file = new File(resolve(REPO_ROOT, path)); - const projects = PROJECTS.filter(p => p.isAbsolutePathSelected(path)); + const projects = PROJECTS.filter((p) => p.isAbsolutePathSelected(path)); if (!projects.length) { throw new Error( @@ -44,7 +44,7 @@ export function getTsProjectForAbsolutePath(path: string): Project { } if (projects.length !== 1 && !file.isTypescriptAmbient()) { - const configPaths = projects.map(p => `"${relative(REPO_ROOT, p.tsConfigPath)}"`); + const configPaths = projects.map((p) => `"${relative(REPO_ROOT, p.tsConfigPath)}"`); const pathsMsg = `${configPaths.slice(0, -1).join(', ')} or ${ configPaths[configPaths.length - 1] diff --git a/src/dev/typescript/project.ts b/src/dev/typescript/project.ts index 623c248144ff6..4cf87d812a0b3 100644 --- a/src/dev/typescript/project.ts +++ b/src/dev/typescript/project.ts @@ -27,7 +27,7 @@ import { REPO_ROOT } from '../constants'; function makeMatchers(directory: string, patterns: string[]) { return patterns.map( - pattern => + (pattern) => new Minimatch(resolve(directory, pattern), { dot: true, }) @@ -45,7 +45,7 @@ function parseTsConfig(path: string) { } function testMatchers(matchers: IMinimatch[], path: string) { - return matchers.some(matcher => matcher.match(path)); + return matchers.some((matcher) => matcher.match(path)); } export class Project { diff --git a/src/dev/typescript/projects.ts b/src/dev/typescript/projects.ts index 5019c8bd22341..b368949cc33e1 100644 --- a/src/dev/typescript/projects.ts +++ b/src/dev/typescript/projects.ts @@ -40,19 +40,19 @@ export const PROJECTS = [ // both took closer to 1000ms. ...glob .sync('packages/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('examples/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('x-pack/examples/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('test/plugin_functional/plugins/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('test/interpreter_functional/plugins/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ]; export function filterProjectsByFlag(projectFlag?: string) { @@ -61,5 +61,5 @@ export function filterProjectsByFlag(projectFlag?: string) { } const tsConfigPath = resolve(projectFlag); - return PROJECTS.filter(project => project.tsConfigPath === tsConfigPath); + return PROJECTS.filter((project) => project.tsConfigPath === tsConfigPath); } diff --git a/src/dev/typescript/run_check_ts_projects_cli.ts b/src/dev/typescript/run_check_ts_projects_cli.ts index 85f3d473dce6b..b0c125ea47829 100644 --- a/src/dev/typescript/run_check_ts_projects_cli.ts +++ b/src/dev/typescript/run_check_ts_projects_cli.ts @@ -51,7 +51,7 @@ export async function runCheckTsProjectsCli() { log.verbose('Checking %s', file.getAbsolutePath()); - const projects = PROJECTS.filter(p => p.isAbsolutePathSelected(file.getAbsolutePath())); + const projects = PROJECTS.filter((p) => p.isAbsolutePathSelected(file.getAbsolutePath())); if (projects.length === 0) { isNotInTsProject.push(file); } @@ -68,7 +68,7 @@ export async function runCheckTsProjectsCli() { if (isNotInTsProject.length) { log.error( `The following files do not belong to a tsconfig.json file, or that tsconfig.json file is not listed in src/dev/typescript/projects.ts\n${isNotInTsProject - .map(file => ` - ${file.getRelativePath()}`) + .map((file) => ` - ${file.getRelativePath()}`) .join('\n')}` ); } @@ -76,7 +76,7 @@ export async function runCheckTsProjectsCli() { if (isInMultipleTsProjects.length) { log.error( `The following files belong to multiple tsconfig.json files listed in src/dev/typescript/projects.ts\n${isInMultipleTsProjects - .map(file => ` - ${file.getRelativePath()}`) + .map((file) => ` - ${file.getRelativePath()}`) .join('\n')}` ); } diff --git a/src/dev/typescript/run_type_check_cli.ts b/src/dev/typescript/run_type_check_cli.ts index 1f0e4b48b7b4b..1417d30484678 100644 --- a/src/dev/typescript/run_type_check_cli.ts +++ b/src/dev/typescript/run_type_check_cli.ts @@ -80,14 +80,14 @@ export function runTypeCheckCli() { } const tscArgs = ['--noEmit', '--pretty', ...(opts['skip-lib-check'] ? ['--skipLibCheck'] : [])]; - const projects = filterProjectsByFlag(opts.project).filter(p => !p.disableTypeCheck); + const projects = filterProjectsByFlag(opts.project).filter((p) => !p.disableTypeCheck); if (!projects.length) { log.error(`Unable to find project at ${opts.project}`); process.exit(1); } - execInProjects(log, projects, process.execPath, project => [ + execInProjects(log, projects, process.execPath, (project) => [ ...(project.name === 'x-pack' ? ['--max-old-space-size=4096'] : []), require.resolve('typescript/bin/tsc'), ...['--project', project.tsConfigPath], diff --git a/src/es_archiver/actions/edit.ts b/src/es_archiver/actions/edit.ts index de63081a1ea1b..afa51a3b96477 100644 --- a/src/es_archiver/actions/edit.ts +++ b/src/es_archiver/actions/edit.ts @@ -44,13 +44,13 @@ export async function editAction({ cwd: prefix ? resolve(dataDir, prefix) : dataDir, absolute: true, }) - ).map(path => ({ + ).map((path) => ({ path, rawPath: path.slice(0, -3), })); await Promise.all( - archives.map(async archive => { + archives.map(async (archive) => { await createPromiseFromStreams([ Fs.createReadStream(archive.path), createGunzip(), @@ -70,7 +70,7 @@ export async function editAction({ await handler(); await Promise.all( - archives.map(async archive => { + archives.map(async (archive) => { await createPromiseFromStreams([ Fs.createReadStream(archive.rawPath), createGzip({ level: Z_BEST_COMPRESSION }), diff --git a/src/es_archiver/actions/load.ts b/src/es_archiver/actions/load.ts index ae7799205b299..19b5b9e75f31a 100644 --- a/src/es_archiver/actions/load.ts +++ b/src/es_archiver/actions/load.ts @@ -43,7 +43,7 @@ import { // are not listened for const pipeline = (...streams: Readable[]) => streams.reduce((source, dest) => - source.once('error', error => dest.emit('error', error)).pipe(dest as any) + source.once('error', (error) => dest.emit('error', error)).pipe(dest as any) ); export async function loadAction({ @@ -70,7 +70,7 @@ export async function loadAction({ // order, so that createIndexStream can track the state of indexes // across archives and properly skip docs from existing indexes const recordStream = concatStreamProviders( - files.map(filename => () => { + files.map((filename) => () => { log.info('[%s] Loading %j', name, filename); return pipeline( @@ -105,7 +105,7 @@ export async function loadAction({ }); // If we affected the Kibana index, we need to ensure it's migrated... - if (Object.keys(result).some(k => k.startsWith('.kibana'))) { + if (Object.keys(result).some((k) => k.startsWith('.kibana'))) { await migrateKibanaIndex({ client, kbnClient }); if (kibanaPluginIds.includes('spaces')) { diff --git a/src/es_archiver/actions/rebuild_all.ts b/src/es_archiver/actions/rebuild_all.ts index f35b2ca49c666..dfbd51300e04d 100644 --- a/src/es_archiver/actions/rebuild_all.ts +++ b/src/es_archiver/actions/rebuild_all.ts @@ -33,7 +33,7 @@ import { } from '../lib'; async function isDirectory(path: string): Promise { - const stats: Stats = await fromNode(cb => stat(path, cb)); + const stats: Stats = await fromNode((cb) => stat(path, cb)); return stats.isDirectory(); } @@ -71,7 +71,7 @@ export async function rebuildAllAction({ createWriteStream(tempFile), ] as [Readable, ...Writable[]]); - await fromNode(cb => rename(tempFile, childPath, cb)); + await fromNode((cb) => rename(tempFile, childPath, cb)); log.info(`${archiveName} Rebuilt ${childName}`); } } diff --git a/src/es_archiver/cli.ts b/src/es_archiver/cli.ts index 252f99f8f47af..98888b81d9a31 100644 --- a/src/es_archiver/cli.ts +++ b/src/es_archiver/cli.ts @@ -69,34 +69,34 @@ cmd cmd .command('load ') .description('load the archive in --dir with ') - .action(name => execute(archiver => archiver.load(name))); + .action((name) => execute((archiver) => archiver.load(name))); cmd .command('unload ') .description('remove indices created by the archive in --dir with ') - .action(name => execute(archiver => archiver.unload(name))); + .action((name) => execute((archiver) => archiver.unload(name))); cmd .command('empty-kibana-index') .description( '[internal] Delete any Kibana indices, and initialize the Kibana index as Kibana would do on startup.' ) - .action(() => execute(archiver => archiver.emptyKibanaIndex())); + .action(() => execute((archiver) => archiver.emptyKibanaIndex())); cmd .command('edit [prefix]') .description( 'extract the archives under the prefix, wait for edits to be completed, and then recompress the archives' ) - .action(prefix => - execute(archiver => + .action((prefix) => + execute((archiver) => archiver.edit(prefix, async () => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); - await new Promise(resolveInput => { + await new Promise((resolveInput) => { rl.question(`Press enter when you're done`, () => { rl.close(); resolveInput(); @@ -109,11 +109,11 @@ cmd cmd .command('rebuild-all') .description('[internal] read and write all archives in --dir to remove any inconsistencies') - .action(() => execute(archiver => archiver.rebuildAll())); + .action(() => execute((archiver) => archiver.rebuildAll())); cmd.parse(process.argv); -const missingCommand = cmd.args.every(a => !((a as any) instanceof Command)); +const missingCommand = cmd.args.every((a) => !((a as any) instanceof Command)); if (missingCommand) { execute(); } diff --git a/src/es_archiver/lib/__tests__/stats.ts b/src/es_archiver/lib/__tests__/stats.ts index 28e337b3da529..0ab7d161feb6e 100644 --- a/src/es_archiver/lib/__tests__/stats.ts +++ b/src/es_archiver/lib/__tests__/stats.ts @@ -28,7 +28,7 @@ function createBufferedLog(): ToolingLog & { buffer: string } { const log: ToolingLog = new ToolingLog({ level: 'debug', writeTo: { - write: chunk => ((log as any).buffer += chunk), + write: (chunk) => ((log as any).buffer += chunk), }, }); (log as any).buffer = ''; @@ -47,7 +47,7 @@ function assertDeepClones(a: any, b: any) { expect(one).to.eql(two); expect(one).to.not.be(two); const keys = uniq(Object.keys(one).concat(Object.keys(two))); - keys.forEach(k => { + keys.forEach((k) => { path.push(k); recurse(one[k], two[k]); path.pop(); diff --git a/src/es_archiver/lib/archives/__tests__/format.ts b/src/es_archiver/lib/archives/__tests__/format.ts index f472f094134d7..f3829273ea808 100644 --- a/src/es_archiver/lib/archives/__tests__/format.ts +++ b/src/es_archiver/lib/archives/__tests__/format.ts @@ -31,7 +31,7 @@ import { import { createFormatArchiveStreams } from '../format'; const INPUTS = [1, 2, { foo: 'bar' }, [1, 2]]; -const INPUT_JSON = INPUTS.map(i => JSON.stringify(i, null, 2)).join('\n\n'); +const INPUT_JSON = INPUTS.map((i) => JSON.stringify(i, null, 2)).join('\n\n'); describe('esArchiver createFormatArchiveStreams', () => { describe('{ gzip: false }', () => { @@ -39,7 +39,7 @@ describe('esArchiver createFormatArchiveStreams', () => { const streams = createFormatArchiveStreams({ gzip: false }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); it('streams consume js values and produces buffers', async () => { @@ -50,7 +50,7 @@ describe('esArchiver createFormatArchiveStreams', () => { ] as [Readable, ...Writable[]]); expect(output.length).to.be.greaterThan(0); - output.forEach(b => expect(b).to.be.a(Buffer)); + output.forEach((b) => expect(b).to.be.a(Buffer)); }); it('product is pretty-printed JSON separated by two newlines', async () => { @@ -69,7 +69,7 @@ describe('esArchiver createFormatArchiveStreams', () => { const streams = createFormatArchiveStreams({ gzip: true }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); it('streams consume js values and produces buffers', async () => { @@ -80,7 +80,7 @@ describe('esArchiver createFormatArchiveStreams', () => { ] as [Readable, ...Writable[]]); expect(output.length).to.be.greaterThan(0); - output.forEach(b => expect(b).to.be.a(Buffer)); + output.forEach((b) => expect(b).to.be.a(Buffer)); }); it('output can be gunzipped', async () => { diff --git a/src/es_archiver/lib/archives/__tests__/parse.ts b/src/es_archiver/lib/archives/__tests__/parse.ts index ba30156b5af39..50cbdfe06f361 100644 --- a/src/es_archiver/lib/archives/__tests__/parse.ts +++ b/src/es_archiver/lib/archives/__tests__/parse.ts @@ -36,7 +36,7 @@ describe('esArchiver createParseArchiveStreams', () => { const streams = createParseArchiveStreams({ gzip: false }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); describe('streams', () => { @@ -73,7 +73,7 @@ describe('esArchiver createParseArchiveStreams', () => { it('provides each JSON object as soon as it is parsed', async () => { let onReceived: (resolved: any) => void; - const receivedPromise = new Promise(resolve => (onReceived = resolve)); + const receivedPromise = new Promise((resolve) => (onReceived = resolve)); const input = new PassThrough(); const check = new Transform({ writableObjectMode: true, @@ -124,7 +124,7 @@ describe('esArchiver createParseArchiveStreams', () => { const streams = createParseArchiveStreams({ gzip: true }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); describe('streams', () => { diff --git a/src/es_archiver/lib/archives/format.ts b/src/es_archiver/lib/archives/format.ts index 9bef4c9adbf05..ac18147ad6948 100644 --- a/src/es_archiver/lib/archives/format.ts +++ b/src/es_archiver/lib/archives/format.ts @@ -26,7 +26,7 @@ import { RECORD_SEPARATOR } from './constants'; export function createFormatArchiveStreams({ gzip = false }: { gzip?: boolean } = {}) { return [ - createMapStream(record => stringify(record, { space: ' ' })), + createMapStream((record) => stringify(record, { space: ' ' })), createIntersperseStream(RECORD_SEPARATOR), gzip ? createGzip({ level: Z_BEST_COMPRESSION }) : new PassThrough(), ]; diff --git a/src/es_archiver/lib/archives/parse.ts b/src/es_archiver/lib/archives/parse.ts index 0f4460c925019..1d650815f9358 100644 --- a/src/es_archiver/lib/archives/parse.ts +++ b/src/es_archiver/lib/archives/parse.ts @@ -29,7 +29,7 @@ export function createParseArchiveStreams({ gzip = false } = {}) { gzip ? createGunzip() : new PassThrough(), createReplaceStream('\r\n', '\n'), createSplitStream(RECORD_SEPARATOR), - createFilterStream(l => !!l.match(/[^\s]/)), - createMapStream(json => JSON.parse(json.trim())), + createFilterStream((l) => !!l.match(/[^\s]/)), + createMapStream((json) => JSON.parse(json.trim())), ]; } diff --git a/src/es_archiver/lib/directory.ts b/src/es_archiver/lib/directory.ts index 8581207fa795d..3a48e576f44ce 100644 --- a/src/es_archiver/lib/directory.ts +++ b/src/es_archiver/lib/directory.ts @@ -21,6 +21,6 @@ import { readdir } from 'fs'; import { fromNode } from 'bluebird'; export async function readDirectory(path: string) { - const allNames = await fromNode(cb => readdir(path, cb)); - return allNames.filter(name => !name.startsWith('.')); + const allNames = await fromNode((cb) => readdir(path, cb)); + return allNames.filter((name) => !name.startsWith('.')); } diff --git a/src/es_archiver/lib/docs/__tests__/stubs.ts b/src/es_archiver/lib/docs/__tests__/stubs.ts index 698d62e450cb4..d8d961fa054ff 100644 --- a/src/es_archiver/lib/docs/__tests__/stubs.ts +++ b/src/es_archiver/lib/docs/__tests__/stubs.ts @@ -55,7 +55,7 @@ export const createStubClient = ( responses: Array<(name: string, params: any) => any | Promise> = [] ): MockClient => { const createStubClientMethod = (name: string) => - sinon.spy(async params => { + sinon.spy(async (params) => { if (responses.length === 0) { throw new Error(`unexpected client.${name} call`); } diff --git a/src/es_archiver/lib/docs/index_doc_records_stream.ts b/src/es_archiver/lib/docs/index_doc_records_stream.ts index 8236ae8adb6db..a21227aae66c2 100644 --- a/src/es_archiver/lib/docs/index_doc_records_stream.ts +++ b/src/es_archiver/lib/docs/index_doc_records_stream.ts @@ -26,7 +26,7 @@ export function createIndexDocRecordsStream(client: Client, stats: Stats, progre async function indexDocs(docs: any[]) { const body: any[] = []; - docs.forEach(doc => { + docs.forEach((doc) => { stats.indexedDoc(doc.index); body.push( { diff --git a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts b/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts index 7a3712ca1a336..fe927483da7b0 100644 --- a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts +++ b/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts @@ -63,10 +63,10 @@ describe('esArchiver: createGenerateIndexRecordsStream()', () => { const params = (client.indices.get as sinon.SinonSpy).args[0][0]; expect(params).to.have.property('filterPath'); const filters: string[] = params.filterPath; - expect(filters.some(path => path.includes('index.creation_date'))).to.be(true); - expect(filters.some(path => path.includes('index.uuid'))).to.be(true); - expect(filters.some(path => path.includes('index.version'))).to.be(true); - expect(filters.some(path => path.includes('index.provided_name'))).to.be(true); + expect(filters.some((path) => path.includes('index.creation_date'))).to.be(true); + expect(filters.some((path) => path.includes('index.uuid'))).to.be(true); + expect(filters.some((path) => path.includes('index.version'))).to.be(true); + expect(filters.some((path) => path.includes('index.provided_name'))).to.be(true); }); it('produces one index record for each index name it receives', async () => { diff --git a/src/es_archiver/lib/indices/__tests__/stubs.ts b/src/es_archiver/lib/indices/__tests__/stubs.ts index 3f4682299c38d..c894468dcfcf6 100644 --- a/src/es_archiver/lib/indices/__tests__/stubs.ts +++ b/src/es_archiver/lib/indices/__tests__/stubs.ts @@ -35,7 +35,7 @@ export const createStubStats = (): StubStats => archivedIndex: sinon.stub(), getTestSummary() { const summary: Record = {}; - Object.keys(this).forEach(key => { + Object.keys(this).forEach((key) => { if (this[key].callCount) { summary[key] = this[key].callCount; } @@ -74,7 +74,7 @@ const createEsClientError = (errorType: string) => { }; const indexAlias = (aliases: Record, index: string) => - Object.keys(aliases).find(k => aliases[k] === index); + Object.keys(aliases).find((k) => aliases[k] === index); type StubClient = Client; @@ -133,15 +133,15 @@ export const createStubClient = ( }), delete: sinon.spy(async ({ index }) => { const indices = Array.isArray(index) ? index : [index]; - if (indices.every(ix => existingIndices.includes(ix))) { + if (indices.every((ix) => existingIndices.includes(ix))) { // Delete aliases associated with our indices - indices.forEach(ix => { - const alias = Object.keys(aliases).find(k => aliases[k] === ix); + indices.forEach((ix) => { + const alias = Object.keys(aliases).find((k) => aliases[k] === ix); if (alias) { delete aliases[alias]; } }); - indices.forEach(ix => existingIndices.splice(existingIndices.indexOf(ix), 1)); + indices.forEach((ix) => existingIndices.splice(existingIndices.indexOf(ix), 1)); return { ok: true }; } else { throw createEsClientError('index_not_found_exception'); diff --git a/src/es_archiver/lib/indices/delete_index.ts b/src/es_archiver/lib/indices/delete_index.ts index e3fca587fbc3d..d7ef20b072b26 100644 --- a/src/es_archiver/lib/indices/delete_index.ts +++ b/src/es_archiver/lib/indices/delete_index.ts @@ -109,7 +109,7 @@ export async function waitForSnapshotCompletion(client: Client, index: string, l while (await isSnapshotPending(repository, found.snapshot)) { // wait a bit before getting status again - await new Promise(resolve => setTimeout(resolve, 500)); + await new Promise((resolve) => setTimeout(resolve, 500)); } return; diff --git a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts b/src/es_archiver/lib/records/__tests__/filter_records_stream.ts index d5830478decba..f4f9f32e239ea 100644 --- a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts +++ b/src/es_archiver/lib/records/__tests__/filter_records_stream.ts @@ -66,6 +66,6 @@ describe('esArchiver: createFilterRecordsStream()', () => { ]); expect(output).to.have.length(3); - expect(output.map(o => o.type)).to.eql([type1, type1, type1]); + expect(output.map((o) => o.type)).to.eql([type1, type1, type1]); }); }); diff --git a/src/es_archiver/lib/stats.ts b/src/es_archiver/lib/stats.ts index c69b764fc7290..c7b98c42d3efb 100644 --- a/src/es_archiver/lib/stats.ts +++ b/src/es_archiver/lib/stats.ts @@ -101,7 +101,7 @@ export function createStats(name: string, log: ToolingLog) { public createdIndex(index: string, metadata: Record = {}) { getOrCreate(index).created = true; info('Created index %j', index); - Object.keys(metadata).forEach(key => { + Object.keys(metadata).forEach((key) => { debug('%j %s %j', index, key, metadata[key]); }); } @@ -113,7 +113,7 @@ export function createStats(name: string, log: ToolingLog) { public archivedIndex(index: string, metadata: Record = {}) { getOrCreate(index).archived = true; info('Archived %j', index); - Object.keys(metadata).forEach(key => { + Object.keys(metadata).forEach((key) => { debug('%j %s %j', index, key, metadata[key]); }); } @@ -147,7 +147,7 @@ export function createStats(name: string, log: ToolingLog) { */ public forEachIndex(fn: (index: string, stats: IndexStats) => void) { const clone = this.toJSON(); - Object.keys(clone).forEach(index => { + Object.keys(clone).forEach((index) => { fn(index, clone[index]); }); } diff --git a/src/fixtures/agg_resp/geohash_grid.js b/src/fixtures/agg_resp/geohash_grid.js index 98d3128f7eb2c..0e576a88ab36a 100644 --- a/src/fixtures/agg_resp/geohash_grid.js +++ b/src/fixtures/agg_resp/geohash_grid.js @@ -40,14 +40,14 @@ export default function GeoHashGridAggResponseFixture() { _.range(97, 122) // a-z ); - const tags = _.times(_.random(4, 20), function(i) { + const tags = _.times(_.random(4, 20), function (i) { // random number of tags let docCount = 0; - const buckets = _.times(_.random(40, 200), function() { + const buckets = _.times(_.random(40, 200), function () { return _.sample(geoHashCharts, 3).join(''); }) .sort() - .map(function(geoHash) { + .map(function (geoHash) { const count = _.random(1, 5000); docCount += count; diff --git a/src/fixtures/logstash_fields.js b/src/fixtures/logstash_fields.js index 35a059f0c11f6..a824a94dbd939 100644 --- a/src/fixtures/logstash_fields.js +++ b/src/fixtures/logstash_fields.js @@ -52,7 +52,7 @@ function stubbedLogstashFields() { ['script number', 'long', true, false, { script: '1234' }], ['script date', 'date', true, false, { script: '1234', lang: 'painless' }], ['script murmur3', 'murmur3', true, false, { script: '1234' }], - ].map(function(row) { + ].map(function (row) { const [name, esType, aggregatable, searchable, metadata = {}, subType = undefined] = row; const { diff --git a/src/fixtures/mock_index_patterns.js b/src/fixtures/mock_index_patterns.js index 648fb13156816..f14fb02bd1ec7 100644 --- a/src/fixtures/mock_index_patterns.js +++ b/src/fixtures/mock_index_patterns.js @@ -20,7 +20,7 @@ import sinon from 'sinon'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; -export default function(Private) { +export default function (Private) { const indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); const getIndexPatternStub = sinon.stub().resolves(indexPatterns); diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 42454df2837f7..919274390d4d0 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -20,24 +20,24 @@ import _ from 'lodash'; let values = {}; export default { - get: function(path, def) { + get: function (path, def) { return _.get(values, path, def); }, - set: function(path, val) { + set: function (path, val) { _.set(values, path, val); return val; }, - setSilent: function(path, val) { + setSilent: function (path, val) { _.set(values, path, val); return val; }, emit: _.noop, on: _.noop, off: _.noop, - clearAllKeys: function() { + clearAllKeys: function () { values = {}; }, - _reset: function() { + _reset: function () { values = {}; }, }; diff --git a/src/fixtures/stubbed_logstash_index_pattern.js b/src/fixtures/stubbed_logstash_index_pattern.js index e20d1b5cd7717..5bb926799fcf6 100644 --- a/src/fixtures/stubbed_logstash_index_pattern.js +++ b/src/fixtures/stubbed_logstash_index_pattern.js @@ -26,7 +26,7 @@ import { npSetup } from '../legacy/ui/public/new_platform/new_platform.karma_moc export default function stubbedLogstashIndexPatternService() { const mockLogstashFields = stubbedLogstashFields(); - const fields = mockLogstashFields.map(function(field) { + const fields = mockLogstashFields.map(function (field) { const kbnType = getKbnFieldType(field.type); if (!kbnType || kbnType.name === 'unknown') { @@ -41,7 +41,13 @@ export default function stubbedLogstashIndexPatternService() { }; }); - const indexPattern = new StubIndexPattern('logstash-*', cfg => cfg, 'time', fields, npSetup.core); + const indexPattern = new StubIndexPattern( + 'logstash-*', + (cfg) => cfg, + 'time', + fields, + npSetup.core + ); indexPattern.id = 'logstash-*'; indexPattern.isTimeNanosBased = () => false; diff --git a/src/fixtures/stubbed_search_source.js b/src/fixtures/stubbed_search_source.js index b444a9a27a6b1..4e43dcf70a7f3 100644 --- a/src/fixtures/stubbed_search_source.js +++ b/src/fixtures/stubbed_search_source.js @@ -30,7 +30,7 @@ export default function stubSearchSource(Private, $q, Promise) { setField: sinon.spy(), fetch: sinon.spy(), destroy: sinon.spy(), - getField: function(param) { + getField: function (param) { switch (param) { case 'index': return indexPattern; @@ -38,11 +38,11 @@ export default function stubSearchSource(Private, $q, Promise) { throw new Error(`Param "${param}" is not implemented in the stubbed search source`); } }, - crankResults: function() { + crankResults: function () { deferedResult.resolve(searchResponse); deferedResult = $q.defer(); }, - onResults: function() { + onResults: function () { onResultsCount++; // Up to the test to resolve this manually @@ -50,10 +50,10 @@ export default function stubSearchSource(Private, $q, Promise) { // someHandler.resolve(require('fixtures/search_response')) return deferedResult.promise; }, - getOnResultsCount: function() { + getOnResultsCount: function () { return onResultsCount; }, - _flatten: function() { + _flatten: function () { return Promise.resolve({ index: indexPattern, body: {} }); }, _requestStartHandlers: [], diff --git a/src/legacy/core_plugins/apm_oss/index.js b/src/legacy/core_plugins/apm_oss/index.js index 5923c1e85ee12..b7ab6797c0de9 100644 --- a/src/legacy/core_plugins/apm_oss/index.js +++ b/src/legacy/core_plugins/apm_oss/index.js @@ -52,7 +52,7 @@ export default function apmOss(kibana) { 'spanIndices', 'metricsIndices', 'onboardingIndices', - ].map(type => server.config().get(`apm_oss.${type}`)) + ].map((type) => server.config().get(`apm_oss.${type}`)) ) ); }, diff --git a/src/legacy/core_plugins/console_legacy/index.ts b/src/legacy/core_plugins/console_legacy/index.ts index af080fd5ace9c..c588b941112d1 100644 --- a/src/legacy/core_plugins/console_legacy/index.ts +++ b/src/legacy/core_plugins/console_legacy/index.ts @@ -28,7 +28,7 @@ export const readLegacyEsConfig = () => { }; // eslint-disable-next-line import/no-default-export -export default function(kibana: any) { +export default function (kibana: any) { return new kibana.Plugin({ id: 'console_legacy', diff --git a/src/legacy/core_plugins/elasticsearch/index.js b/src/legacy/core_plugins/elasticsearch/index.js index 35dd6562aed98..a7d6810ac6158 100644 --- a/src/legacy/core_plugins/elasticsearch/index.js +++ b/src/legacy/core_plugins/elasticsearch/index.js @@ -22,7 +22,7 @@ import { createProxy } from './server/lib/create_proxy'; import { handleESError } from './server/lib/handle_es_error'; import { versionHealthCheck } from './lib/version_health_check'; -export default function(kibana) { +export default function (kibana) { let defaultVars; return new kibana.Plugin({ @@ -49,7 +49,7 @@ export default function(kibana) { }; const clusters = new Map(); - server.expose('getCluster', name => { + server.expose('getCluster', (name) => { if (name === 'admin') { return adminCluster; } diff --git a/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts b/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts index 5806c31b78414..0331153cdf615 100644 --- a/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts +++ b/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts @@ -43,7 +43,7 @@ describe('Elasticsearch plugin', () => { kibanaVersion: '8.0.0', }); - beforeAll(async function() { + beforeAll(async function () { const settings = { elasticsearch: {}, adjustTimeout: (t: any) => { @@ -72,12 +72,12 @@ describe('Elasticsearch plugin', () => { await root.shutdown(); }, 30000); - it("should set it's status to green when all nodes are compatible", done => { + it("should set it's status to green when all nodes are compatible", (done) => { jest.setTimeout(30000); elasticsearch.status.on('green', () => done()); }); - it("should set it's status to red when some nodes aren't compatible", done => { + it("should set it's status to red when some nodes aren't compatible", (done) => { esNodesCompatibility$.next({ isCompatible: false, incompatibleNodes: [], diff --git a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js index 4ee8307f490eb..b1a106d2aae5d 100644 --- a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js +++ b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js @@ -20,7 +20,7 @@ export const versionHealthCheck = (esPlugin, logWithMetadata, esNodesCompatibility$) => { esPlugin.status.yellow('Waiting for Elasticsearch'); - return new Promise(resolve => { + return new Promise((resolve) => { esNodesCompatibility$.subscribe(({ isCompatible, message, kibanaVersion, warningNodes }) => { if (!isCompatible) { esPlugin.status.red(message); diff --git a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js index ba7c95bcdfec5..4c03c0c0105ee 100644 --- a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js +++ b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js @@ -20,7 +20,7 @@ import { versionHealthCheck } from './version_health_check'; import { Subject } from 'rxjs'; describe('plugins/elasticsearch', () => { - describe('lib/health_version_check', function() { + describe('lib/health_version_check', function () { let plugin; let logWithMetadata; @@ -37,7 +37,7 @@ describe('plugins/elasticsearch', () => { jest.clearAllMocks(); }); - it('returned promise resolves when all nodes are compatible ', function() { + it('returned promise resolves when all nodes are compatible ', function () { const esNodesCompatibility$ = new Subject(); const versionHealthyPromise = versionHealthCheck( plugin, @@ -48,7 +48,7 @@ describe('plugins/elasticsearch', () => { return expect(versionHealthyPromise).resolves.toBe(undefined); }); - it('should set elasticsearch plugin status to green when all nodes are compatible', function() { + it('should set elasticsearch plugin status to green when all nodes are compatible', function () { const esNodesCompatibility$ = new Subject(); versionHealthCheck(plugin, logWithMetadata, esNodesCompatibility$); expect(plugin.status.yellow).toHaveBeenCalledWith('Waiting for Elasticsearch'); @@ -58,7 +58,7 @@ describe('plugins/elasticsearch', () => { expect(plugin.status.red).not.toHaveBeenCalled(); }); - it('should set elasticsearch plugin status to red when some nodes are incompatible', function() { + it('should set elasticsearch plugin status to red when some nodes are incompatible', function () { const esNodesCompatibility$ = new Subject(); versionHealthCheck(plugin, logWithMetadata, esNodesCompatibility$); expect(plugin.status.yellow).toHaveBeenCalledWith('Waiting for Elasticsearch'); diff --git a/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js b/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js index 9ec4598674d5d..ccab1a3b830b6 100644 --- a/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js +++ b/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js @@ -21,8 +21,8 @@ import expect from '@kbn/expect'; import { handleESError } from '../handle_es_error'; import { errors as esErrors } from 'elasticsearch'; -describe('handleESError', function() { - it('should transform elasticsearch errors into boom errors with the same status code', function() { +describe('handleESError', function () { + it('should transform elasticsearch errors into boom errors with the same status code', function () { const conflict = handleESError(new esErrors.Conflict()); expect(conflict.isBoom).to.be(true); expect(conflict.output.statusCode).to.be(409); @@ -40,21 +40,19 @@ describe('handleESError', function() { expect(badRequest.output.statusCode).to.be(400); }); - it('should return an unknown error without transforming it', function() { + it('should return an unknown error without transforming it', function () { const unknown = new Error('mystery error'); expect(handleESError(unknown)).to.be(unknown); }); - it('should return a boom 503 server timeout error for ES connection errors', function() { + it('should return a boom 503 server timeout error for ES connection errors', function () { expect(handleESError(new esErrors.ConnectionFault()).output.statusCode).to.be(503); expect(handleESError(new esErrors.ServiceUnavailable()).output.statusCode).to.be(503); expect(handleESError(new esErrors.NoConnections()).output.statusCode).to.be(503); expect(handleESError(new esErrors.RequestTimeout()).output.statusCode).to.be(503); }); - it('should throw an error if called with a non-error argument', function() { - expect(handleESError) - .withArgs('notAnError') - .to.throwException(); + it('should throw an error if called with a non-error argument', function () { + expect(handleESError).withArgs('notAnError').to.throwException(); }); }); diff --git a/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js b/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js index 85bc57f89e91c..7302241c46939 100644 --- a/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js +++ b/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js @@ -43,7 +43,7 @@ export function createProxy(server) { body: payload.toString('utf8'), }, { signal } - ).finally(r => h.response(r)); + ).finally((r) => h.response(r)); }), }); diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 5807c439bd277..ef56ae0e2380c 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -32,22 +32,16 @@ import { kbnBaseUrl } from '../../../plugins/kibana_legacy/server'; const mkdirAsync = promisify(Fs.mkdir); -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ id: 'kibana', - config: function(Joi) { + config: function (Joi) { return Joi.object({ enabled: Joi.boolean().default(true), index: Joi.string().default('.kibana'), - autocompleteTerminateAfter: Joi.number() - .integer() - .min(1) - .default(100000), + autocompleteTerminateAfter: Joi.number().integer().min(1).default(100000), // TODO Also allow units here like in elasticsearch config once this is moved to the new platform - autocompleteTimeout: Joi.number() - .integer() - .min(1) - .default(1000), + autocompleteTimeout: Joi.number().integer().min(1).default(1000), }).default(); }, @@ -96,7 +90,7 @@ export default function(kibana) { uiSettingDefaults: getUiSettingDefaults(), }, - preInit: async function(server) { + preInit: async function (server) { try { // Create the data directory (recursively, if the a parent dir doesn't exist). // If it already exists, does nothing. @@ -108,7 +102,7 @@ export default function(kibana) { } }, - init: async function(server) { + init: async function (server) { const { usageCollection } = server.newPlatform.setup.plugins; // routes importApi(server); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js index e4ad8a5638fd1..504b00808718b 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js @@ -35,8 +35,8 @@ let $timeout; let indexPattern; -const init = function($elem, props) { - ngMock.inject(function($rootScope, $compile, _$timeout_) { +const init = function ($elem, props) { + ngMock.inject(function ($rootScope, $compile, _$timeout_) { $timeout = _$timeout_; $parentScope = $rootScope; _.assign($parentScope, props); @@ -44,7 +44,7 @@ const init = function($elem, props) { $compile($elem)($parentScope); // I think the prereq requires this? - $timeout(function() { + $timeout(function () { $elem.scope().$digest(); }, 0); @@ -52,19 +52,19 @@ const init = function($elem, props) { }); }; -const destroy = function() { +const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; -describe('docTable', function() { +describe('docTable', function () { let $elem; before(() => setScopedHistory(createBrowserHistory())); beforeEach(() => pluginInstance.initializeInnerAngular()); beforeEach(() => pluginInstance.initializeServices()); beforeEach(ngMock.module('app/discover')); - beforeEach(function() { + beforeEach(function () { $elem = angular.element(` `); - ngMock.inject(function(Private) { + ngMock.inject(function (Private) { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); }); init($elem, { @@ -87,15 +87,15 @@ describe('docTable', function() { $scope.$digest(); }); - afterEach(function() { + afterEach(function () { destroy(); }); - it('should compile', function() { + it('should compile', function () { expect($elem.text()).to.not.be.empty(); }); - it('should have an addRows function that increases the row count', function() { + it('should have an addRows function that increases the row count', function () { expect($scope.addRows).to.be.a(Function); $scope.$digest(); expect($scope.limit).to.be(50); @@ -103,7 +103,7 @@ describe('docTable', function() { expect($scope.limit).to.be(100); }); - it('should reset the row limit when results are received', function() { + it('should reset the row limit when results are received', function () { $scope.limit = 100; expect($scope.limit).to.be(100); $scope.hits = [...hits]; @@ -111,7 +111,7 @@ describe('docTable', function() { expect($scope.limit).to.be(50); }); - it('should have a header and a table element', function() { + it('should have a header and a table element', function () { $scope.$digest(); expect($elem.find('thead').length).to.be(1); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js index 4a8736cc0d6a4..9bb0ebc76474d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js @@ -37,7 +37,7 @@ angular .service('debounce', ['$timeout', DebounceProviderTimeout]) .directive('fixedScroll', FixedScrollProvider); -describe('FixedScroll directive', function() { +describe('FixedScroll directive', function () { const sandbox = sinon.createSandbox(); let compile; @@ -45,13 +45,13 @@ describe('FixedScroll directive', function() { const trash = []; beforeEach(ngMock.module(testModuleName)); beforeEach( - ngMock.inject(function($compile, $rootScope, $timeout) { + ngMock.inject(function ($compile, $rootScope, $timeout) { flushPendingTasks = function flushPendingTasks() { $rootScope.$digest(); $timeout.flush(); }; - compile = function(ratioY, ratioX) { + compile = function (ratioY, ratioX) { if (ratioX == null) ratioX = ratioY; // since the directive works at the sibling level we create a @@ -93,15 +93,15 @@ describe('FixedScroll directive', function() { }) ); - afterEach(function() { - trash.splice(0).forEach(function($el) { + afterEach(function () { + trash.splice(0).forEach(function ($el) { $el.remove(); }); sandbox.restore(); }); - it('does nothing when not needed', function() { + it('does nothing when not needed', function () { let els = compile(0.5, 1.5); expect(els.$scroller).to.have.length(0); @@ -109,23 +109,23 @@ describe('FixedScroll directive', function() { expect(els.$scroller).to.have.length(0); }); - it('attaches a scroller below the element when the content is larger then the container', function() { + it('attaches a scroller below the element when the content is larger then the container', function () { const els = compile(1.5); expect(els.$scroller).to.have.length(1); }); - it('copies the width of the container', function() { + it('copies the width of the container', function () { const els = compile(1.5); expect(els.$scroller.width()).to.be(els.$container.width()); }); - it('mimics the scrollWidth of the element', function() { + it('mimics the scrollWidth of the element', function () { 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() { + describe('scroll event handling / tug of war prevention', function () { + it('listens when needed, unlistens when not needed', function () { const on = sandbox.spy($.fn, 'on'); const off = sandbox.spy($.fn, 'off'); @@ -143,7 +143,7 @@ describe('FixedScroll directive', function() { // the this values should be different expect(spy.thisValues[0].is(spy.thisValues[1])).to.be(false); // but they should be either $scroller or $container - spy.thisValues.forEach(function($this) { + spy.thisValues.forEach(function ($this) { if ($this.is(els.$scroller) || $this.is(els.$container)) return; expect.fail('expected ' + name + ' to be called with $scroller or $container'); }); @@ -153,21 +153,21 @@ describe('FixedScroll directive', function() { [ { from: '$container', to: '$scroller' }, { from: '$scroller', to: '$container' }, - ].forEach(function(names) { - describe('scroll events ' + JSON.stringify(names), function() { + ].forEach(function (names) { + describe('scroll events ' + JSON.stringify(names), function () { let spy; let els; let $from; let $to; - beforeEach(function() { + beforeEach(function () { spy = sandbox.spy($.fn, 'scrollLeft'); els = compile(1.5); $from = els[names.from]; $to = els[names.to]; }); - it('transfers the scrollLeft', function() { + it('transfers the scrollLeft', function () { expect(spy.callCount).to.be(0); $from.scroll(); expect(spy.callCount).to.be(2); @@ -188,7 +188,7 @@ describe('FixedScroll directive', function() { * but the browser seems to be very careful about triggering the event too much * and I can't reliably recreate the browsers behavior in a test. So... faking it! */ - it('prevents tug of war by ignoring echo scroll events', function() { + it('prevents tug of war by ignoring echo scroll events', function () { $from.scroll(); expect(spy.callCount).to.be(2); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js index 2a34ace8f1312..29c301bf065c4 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js @@ -28,7 +28,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta import { setScopedHistory } from '../../../../../../plugins/discover/public/kibana_services'; import { createBrowserHistory } from 'history'; -describe('Doc Table', function() { +describe('Doc Table', function () { let $parentScope; let $scope; @@ -42,7 +42,7 @@ describe('Doc Table', function() { before(() => setScopedHistory(createBrowserHistory())); beforeEach(ngMock.module('app/discover')); beforeEach( - ngMock.inject(function($rootScope, Private) { + ngMock.inject(function ($rootScope, Private) { $parentScope = $rootScope; $parentScope.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); mapping = $parentScope.indexPattern.fields; @@ -50,7 +50,7 @@ describe('Doc Table', function() { // Stub `getConverterFor` for a field in the indexPattern to return mock data. // Returns `val` if provided, otherwise generates fake data for the field. fakeRowVals = getFakeRowVals('formatted', 0, mapping); - stubFieldFormatConverter = function($root, field, val) { + stubFieldFormatConverter = function ($root, field, val) { const convertFn = (value, type, options) => { if (val) { return val; @@ -67,8 +67,8 @@ describe('Doc Table', function() { ); // Sets up the directive, take an element, and a list of properties to attach to the parent scope. - const init = function($elem, props) { - ngMock.inject(function($compile) { + const init = function ($elem, props) { + ngMock.inject(function ($compile) { _.assign($parentScope, props); $compile($elem)($parentScope); $elem.scope().$digest(); @@ -76,19 +76,19 @@ describe('Doc Table', function() { }); }; - const destroy = function() { + const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; // For testing column removing/adding for the header and the rows - const columnTests = function(elemType, parentElem) { - it('should create a time column if the timefield is defined', function() { + const columnTests = function (elemType, parentElem) { + it('should create a time column if the timefield is defined', function () { const childElems = parentElem.find(elemType); expect(childElems.length).to.be(1); }); - it('should be able to add and remove columns', function() { + it('should be able to add and remove columns', function () { let childElems; stubFieldFormatConverter($parentScope, 'bytes'); @@ -114,7 +114,7 @@ describe('Doc Table', function() { expect($(childElems[1]).text()).to.contain('request_body'); }); - it('should create only the toggle column if there is no timeField', function() { + it('should create only the toggle column if there is no timeField', function () { delete parentElem.scope().indexPattern.timeFieldName; parentElem.scope().$digest(); @@ -123,7 +123,7 @@ describe('Doc Table', function() { }); }; - describe('kbnTableRow', function() { + describe('kbnTableRow', function () { const $elem = angular.element( ' stubFieldFormatConverter($root, f.name)); + $root.indexPattern.fields.forEach((f) => stubFieldFormatConverter($root, f.name)); $row = $('').attr({ 'kbn-table-row': 'row', @@ -262,26 +262,16 @@ describe('Doc Table', function() { $before = $row.find('td'); expect($before).to.have.length(3); - expect( - $before - .eq(0) - .text() - .trim() - ).to.be(''); - expect( - $before - .eq(1) - .text() - .trim() - ).to.match(/^time_formatted/); + expect($before.eq(0).text().trim()).to.be(''); + expect($before.eq(1).text().trim()).to.match(/^time_formatted/); }) ); - afterEach(function() { + afterEach(function () { $row.remove(); }); - it('handles a new column', function() { + it('handles a new column', function () { $root.columns.push('bytes'); $root.$apply(); @@ -290,15 +280,10 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); }); - it('handles two new columns at once', function() { + it('handles two new columns at once', function () { $root.columns.push('bytes'); $root.columns.push('request_body'); $root.$apply(); @@ -308,21 +293,11 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(4) - .text() - .trim() - ).to.match(/^request_body_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(4).text().trim()).to.match(/^request_body_formatted/); }); - it('handles three new columns in odd places', function() { + it('handles three new columns in odd places', function () { $root.columns = ['@timestamp', 'bytes', '_source', 'request_body']; $root.$apply(); @@ -330,28 +305,13 @@ describe('Doc Table', function() { expect($after).to.have.length(6); expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^@timestamp_formatted/); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); expect($after[4]).to.be($before[2]); - expect( - $after - .eq(5) - .text() - .trim() - ).to.match(/^request_body_formatted/); + expect($after.eq(5).text().trim()).to.match(/^request_body_formatted/); }); - it('handles a removed column', function() { + it('handles a removed column', function () { _.pull($root.columns, '_source'); $root.$apply(); @@ -361,7 +321,7 @@ describe('Doc Table', function() { expect($after[1]).to.be($before[1]); }); - it('handles two removed columns', function() { + it('handles two removed columns', function () { // first add a column $root.columns.push('@timestamp'); $root.$apply(); @@ -379,7 +339,7 @@ describe('Doc Table', function() { expect($after[1]).to.be($before[1]); }); - it('handles three removed random columns', function() { + it('handles three removed random columns', function () { // first add two column $root.columns.push('@timestamp', 'bytes'); $root.$apply(); @@ -396,15 +356,10 @@ describe('Doc Table', function() { expect($after).to.have.length(3); expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^@timestamp_formatted/); + expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); }); - it('handles two columns with the same content', function() { + it('handles two columns with the same content', function () { stubFieldFormatConverter($root, 'request_body', fakeRowVals.bytes); $root.columns.length = 0; @@ -414,21 +369,11 @@ describe('Doc Table', function() { const $after = $row.find('td'); expect($after).to.have.length(4); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(2).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); }); - it('handles two columns swapping position', function() { + it('handles two columns swapping position', function () { $root.columns.push('bytes'); $root.$apply(); @@ -446,7 +391,7 @@ describe('Doc Table', function() { expect($after[3]).to.be($mid[2]); }); - it('handles four columns all reversing position', function() { + it('handles four columns all reversing position', function () { $root.columns.push('bytes', 'response', '@timestamp'); $root.$apply(); @@ -466,7 +411,7 @@ describe('Doc Table', function() { expect($after[5]).to.be($mid[2]); }); - it('handles multiple columns with the same name', function() { + it('handles multiple columns with the same name', function () { $root.columns.push('bytes', 'bytes', 'bytes'); $root.$apply(); @@ -475,24 +420,9 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(4) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(5) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(4).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(5).text().trim()).to.match(/^bytes_formatted/); }); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js index de85bec011eeb..413afaa90d4f2 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js @@ -35,7 +35,7 @@ import { tabifiedData } from './tabified_data'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { configureAppAngularModule } from '../../../../../../plugins/kibana_legacy/public/angular'; -describe('Table Vis - AggTable Directive', function() { +describe('Table Vis - AggTable Directive', function () { let $rootScope; let $compile; let settings; @@ -50,7 +50,7 @@ describe('Table Vis - AggTable Directive', function() { beforeEach(ngMock.module('kibana/table_vis')); beforeEach( - ngMock.inject(function($injector, config) { + ngMock.inject(function ($injector, config) { settings = config; $rootScope = $injector.get('$rootScope'); @@ -59,14 +59,14 @@ describe('Table Vis - AggTable Directive', function() { ); let $scope; - beforeEach(function() { + beforeEach(function () { $scope = $rootScope.$new(); }); - afterEach(function() { + afterEach(function () { $scope.$destroy(); }); - it('renders a simple response properly', function() { + it('renders a simple response properly', function () { $scope.dimensions = { metrics: [{ accessor: 0, format: { id: 'number' }, params: {} }], buckets: [], @@ -83,7 +83,7 @@ describe('Table Vis - AggTable Directive', function() { expect($el.find('td').text()).to.eql('1,000'); }); - it('renders nothing if the table is empty', function() { + it('renders nothing if the table is empty', function () { $scope.dimensions = {}; $scope.table = null; const $el = $compile('')( @@ -94,7 +94,7 @@ describe('Table Vis - AggTable Directive', function() { expect($el.find('tbody').length).to.be(0); }); - it('renders a complex response properly', async function() { + it('renders a complex response properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -124,15 +124,13 @@ describe('Table Vis - AggTable Directive', function() { } } - $rows.each(function() { + $rows.each(function () { // 6 cells in every row const $cells = $(this).find('td'); expect($cells.length).to.be(6); - const txts = $cells.map(function() { - return $(this) - .text() - .trim(); + const txts = $cells.map(function () { + return $(this).text().trim(); }); // two character country code @@ -149,7 +147,7 @@ describe('Table Vis - AggTable Directive', function() { }); }); - describe('renders totals row', function() { + describe('renders totals row', function () { async function totalsRowTest(totalFunc, expected) { function setDefaultTimezone() { moment.tz.setDefault(settings.get('dateFormat:tz')); @@ -192,19 +190,15 @@ describe('Table Vis - AggTable Directive', function() { expect($cells.length).to.be(6); for (let i = 0; i < 6; i++) { - expect( - $($cells[i]) - .text() - .trim() - ).to.be(expected[i]); + expect($($cells[i]).text().trim()).to.be(expected[i]); } settings.set('dateFormat:tz', oldTimezoneSetting); off(); } - it('as count', async function() { + it('as count', async function () { await totalsRowTest('count', ['18', '18', '18', '18', '18', '18']); }); - it('as min', async function() { + it('as min', async function () { await totalsRowTest('min', [ '', '2014-09-28', @@ -214,7 +208,7 @@ describe('Table Vis - AggTable Directive', function() { '11', ]); }); - it('as max', async function() { + it('as max', async function () { await totalsRowTest('max', [ '', '2014-10-03', @@ -224,16 +218,16 @@ describe('Table Vis - AggTable Directive', function() { '837', ]); }); - it('as avg', async function() { + it('as avg', async function () { await totalsRowTest('avg', ['', '', '87,221.5', '', '64.667', '206.833']); }); - it('as sum', async function() { + it('as sum', async function () { await totalsRowTest('sum', ['', '', '1,569,987', '', '1,164', '3,723']); }); }); - describe('aggTable.toCsv()', function() { - it('escapes rows and columns properly', function() { + describe('aggTable.toCsv()', function () { + it('escapes rows and columns properly', function () { const $el = $compile('')( $scope ); @@ -255,7 +249,7 @@ describe('Table Vis - AggTable Directive', function() { ); }); - it('exports rows and columns properly', async function() { + it('exports rows and columns properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -310,7 +304,7 @@ describe('Table Vis - AggTable Directive', function() { ); }); - it('exports formatted rows and columns properly', async function() { + it('exports formatted rows and columns properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -335,7 +329,7 @@ describe('Table Vis - AggTable Directive', function() { $tableScope.table = $scope.table; // Create our own converter since the ones we use for tests don't actually transform the provided value - $tableScope.formattedColumns[0].formatter.convert = v => `${v}_formatted`; + $tableScope.formattedColumns[0].formatter.convert = (v) => `${v}_formatted`; const formatted = aggTable.toCsv(true); expect(formatted).to.be( @@ -369,7 +363,7 @@ describe('Table Vis - AggTable Directive', function() { }); }); - it('renders percentage columns', async function() { + it('renders percentage columns', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -397,22 +391,12 @@ describe('Table Vis - AggTable Directive', function() { const $headings = $el.find('th'); expect($headings.length).to.be(7); - expect( - $headings - .eq(3) - .text() - .trim() - ).to.be('Average bytes percentages'); - - const countColId = $scope.table.columns.find(col => col.name === $scope.percentageCol).id; - const counts = $scope.table.rows.map(row => row[countColId]); + expect($headings.eq(3).text().trim()).to.be('Average bytes percentages'); + + const countColId = $scope.table.columns.find((col) => col.name === $scope.percentageCol).id; + const counts = $scope.table.rows.map((row) => row[countColId]); const total = counts.reduce((sum, curr) => sum + curr, 0); - const $percentageColValues = $el.find('tbody tr').map((i, el) => - $(el) - .find('td') - .eq(3) - .text() - ); + const $percentageColValues = $el.find('tbody tr').map((i, el) => $(el).find('td').eq(3).text()); $percentageColValues.each((i, value) => { const percentage = `${round((counts[i] / total) * 100, 3)}%`; @@ -420,23 +404,23 @@ describe('Table Vis - AggTable Directive', function() { }); }); - describe('aggTable.exportAsCsv()', function() { + describe('aggTable.exportAsCsv()', function () { let origBlob; function FakeBlob(slices, opts) { this.slices = slices; this.opts = opts; } - beforeEach(function() { + beforeEach(function () { origBlob = window.Blob; window.Blob = FakeBlob; }); - afterEach(function() { + afterEach(function () { window.Blob = origBlob; }); - it('calls _saveAs properly', function() { + it('calls _saveAs properly', function () { const $el = $compile('')($scope); $scope.$digest(); @@ -468,7 +452,7 @@ describe('Table Vis - AggTable Directive', function() { expect(call.args[1]).to.be('somefilename.csv'); }); - it('should use the export-title attribute', function() { + it('should use the export-title attribute', function () { const expected = 'export file name'; const $el = $compile( `` diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js index 3cd7de393d66a..99b397167009d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js @@ -31,7 +31,7 @@ import { npStart } from 'ui/new_platform'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { configureAppAngularModule } from '../../../../../../plugins/kibana_legacy/public/angular'; -describe('Table Vis - AggTableGroup Directive', function() { +describe('Table Vis - AggTableGroup Directive', function () { let $rootScope; let $compile; @@ -45,21 +45,21 @@ describe('Table Vis - AggTableGroup Directive', function() { beforeEach(ngMock.module('kibana/table_vis')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $compile = $injector.get('$compile'); }) ); let $scope; - beforeEach(function() { + beforeEach(function () { $scope = $rootScope.$new(); }); - afterEach(function() { + afterEach(function () { $scope.$destroy(); }); - it('renders a simple split response properly', function() { + it('renders a simple split response properly', function () { $scope.dimensions = { metrics: [{ accessor: 0, format: { id: 'number' }, params: {} }], buckets: [], @@ -80,7 +80,7 @@ describe('Table Vis - AggTableGroup Directive', function() { expect($el.find('kbn-agg-table').length).to.be(1); }); - it('renders nothing if the table list is empty', function() { + it('renders nothing if the table list is empty', function () { const $el = $( '' ); @@ -96,7 +96,7 @@ describe('Table Vis - AggTableGroup Directive', function() { expect($subTables.length).to.be(0); }); - it('renders a complex response properly', function() { + it('renders a complex response properly', function () { $scope.dimensions = { splitRow: [{ accessor: 0, params: {} }], buckets: [ @@ -122,7 +122,7 @@ describe('Table Vis - AggTableGroup Directive', function() { const $subTableHeaders = $el.find('.kbnAggTable__groupHeader'); expect($subTableHeaders.length).to.be(3); - $subTableHeaders.each(function(i) { + $subTableHeaders.each(function (i) { expect($(this).text()).to.be(group.tables[i].title); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js index 8f08f6a1f37e6..35c7b77687b94 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js @@ -32,7 +32,7 @@ import { seedColors } from '../../../../../../plugins/charts/public/services/col // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { TagCloud } from '../../../../../../plugins/vis_type_tagcloud/public/components/tag_cloud'; -describe('tag cloud tests', function() { +describe('tag cloud tests', function () { const minValue = 1; const maxValue = 9; const midValue = (minValue + maxValue) / 2; @@ -126,30 +126,30 @@ describe('tag cloud tests', function() { sqrtScaleTest, biggerFontTest, trimDataTest, - ].forEach(function(test) { + ].forEach(function (test) { describe(`should position elements correctly for options: ${JSON.stringify( test.options - )}`, function() { - beforeEach(async function() { + )}`, function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(test.data); tagCloud.setOptions(test.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(test.expected, textElements, tagCloud); }) @@ -157,9 +157,9 @@ describe('tag cloud tests', function() { }); }); - [5, 100, 200, 300, 500].forEach(function(timeout) { - describe(`should only send single renderComplete event at the very end, using ${timeout}ms timeout`, function() { - beforeEach(async function() { + [5, 100, 200, 300, 500].forEach(function (timeout) { + describe(`should only send single renderComplete event at the very end, using ${timeout}ms timeout`, function () { + beforeEach(async function () { setupDOM(); //TagCloud takes at least 600ms to complete (due to d3 animation) @@ -171,21 +171,21 @@ describe('tag cloud tests', function() { //this timeout modifies the settings before the cloud is rendered. //the cloud needs to use the correct options setTimeout(() => tagCloud.setOptions(logScaleTest.options), timeout); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) @@ -193,63 +193,63 @@ describe('tag cloud tests', function() { }); }); - describe('should use the latest state before notifying (when modifying options multiple times)', function() { - beforeEach(async function() { + describe('should use the latest state before notifying (when modifying options multiple times)', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); tagCloud.setOptions(logScaleTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) ); }); - describe('should use the latest state before notifying (when modifying data multiple times)', function() { - beforeEach(async function() { + describe('should use the latest state before notifying (when modifying data multiple times)', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); tagCloud.setData(trimDataTest.data); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(trimDataTest.expected, textElements, tagCloud); }) ); }); - describe('should not get multiple render-events', function() { + describe('should not get multiple render-events', function () { let counter; - beforeEach(function() { + beforeEach(function () { counter = 0; setupDOM(); return new Promise((resolve, reject) => { @@ -283,21 +283,21 @@ describe('tag cloud tests', function() { it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) ); }); - describe('should show correct data when state-updates are interleaved with resize event', function() { - beforeEach(async function() { + describe('should show correct data when state-updates are interleaved with resize event', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(logScaleTest.data); @@ -312,43 +312,43 @@ describe('tag cloud tests', function() { tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); }, 200); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(baseTest.expected, textElements, tagCloud); }) ); }); - describe(`should not put elements in view when container is too small`, function() { - beforeEach(async function() { + describe(`should not put elements in view when container is too small`, function () { + beforeEach(async function () { setupDOM(); domNode.style.width = '1px'; domNode.style.height = '1px'; tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); - it('completeness should not be ok', function() { + it('completeness should not be ok', function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.INCOMPLETE); }); - it('positions should not be ok', function() { + it('positions should not be ok', function () { const textElements = domNode.querySelectorAll('text'); for (let i = 0; i < textElements; i++) { const bbox = textElements[i].getBoundingClientRect(); @@ -357,8 +357,8 @@ describe('tag cloud tests', function() { }); }); - describe(`tags should fit after making container bigger`, function() { - beforeEach(async function() { + describe(`tags should fit after making container bigger`, function () { + beforeEach(async function () { setupDOM(); domNode.style.width = '1px'; domNode.style.height = '1px'; @@ -366,50 +366,50 @@ describe('tag cloud tests', function() { tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); //make bigger domNode.style.width = '512px'; domNode.style.height = '512px'; tagCloud.resize(); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); }); - describe(`tags should no longer fit after making container smaller`, function() { - beforeEach(async function() { + describe(`tags should no longer fit after making container smaller`, function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); //make smaller domNode.style.width = '1px'; domNode.style.height = '1px'; tagCloud.resize(); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); - it('completeness should not be ok', function() { + it('completeness should not be ok', function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.INCOMPLETE); }); }); - describe('tagcloudscreenshot', function() { + describe('tagcloudscreenshot', function () { let imageComparator; - beforeEach(async function() { + beforeEach(async function () { setupDOM(); imageComparator = new ImageComparator(); }); @@ -419,12 +419,12 @@ describe('tag cloud tests', function() { teardownDOM(); }); - it('should render simple image', async function() { + it('should render simple image', async function () { tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); const mismatchedPixels = await imageComparator.compareDOMContents( domNode.innerHTML, @@ -522,7 +522,7 @@ describe('tag cloud tests', function() { const centered = largest[1] === 0 && largest[2] === 0; const halfWidth = debugInfo.size.width / 2; const halfHeight = debugInfo.size.height / 2; - const inside = debugInfo.positions.filter(position => { + const inside = debugInfo.positions.filter((position) => { const x = position.x + halfWidth; const y = position.y + halfHeight; return 0 <= x && x <= debugInfo.size.width && 0 <= y && y <= debugInfo.size.height; @@ -532,7 +532,7 @@ describe('tag cloud tests', function() { } function handleExpectedBlip(assertion) { - return function() { + return function () { if (!shouldAssert()) { return; } diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js index 040ee18916fa2..4a6e9e7765213 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js @@ -42,7 +42,7 @@ import { setFormatService } from '../../../../../../plugins/vis_type_tagcloud/pu const THRESHOLD = 0.65; const PIXEL_DIFF = 64; -describe('TagCloudVisualizationTest', function() { +describe('TagCloudVisualizationTest', function () { let domNode; let vis; let imageComparator; @@ -76,8 +76,8 @@ describe('TagCloudVisualizationTest', function() { beforeEach(ngMock.module('kibana')); - describe('TagCloudVisualization - basics', function() { - beforeEach(async function() { + describe('TagCloudVisualization - basics', function () { + beforeEach(async function () { const visType = new BaseVisType(createTagCloudVisTypeDefinition({ colors: seedColors })); setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -91,12 +91,12 @@ describe('TagCloudVisualizationTest', function() { }); }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('simple draw', async function() { + it('simple draw', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { @@ -118,7 +118,7 @@ describe('TagCloudVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('with resize', async function() { + it('with resize', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -149,7 +149,7 @@ describe('TagCloudVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('with param change', async function() { + it('with param change', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { resize: false, diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js index 691318e32245b..6d6eb69e66792 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js @@ -139,7 +139,7 @@ describe('VegaVisualizations', () => { beforeEach(ngMock.module('kibana')); beforeEach( ngMock.inject(() => { - setInjectedVarFunc(injectedVar => { + setInjectedVarFunc((injectedVar) => { switch (injectedVar) { case 'mapConfig': return { @@ -186,7 +186,7 @@ describe('VegaVisualizations', () => { ); describe('VegaVisualization - basics', () => { - beforeEach(async function() { + beforeEach(async function () { setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -195,12 +195,12 @@ describe('VegaVisualizations', () => { }); }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('should show vegalite graph and update on resize (may fail in dev env)', async function() { + it('should show vegalite graph and update on resize (may fail in dev env)', async function () { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); @@ -223,7 +223,7 @@ describe('VegaVisualizations', () => { } }); - it('should show vega graph (may fail in dev env)', async function() { + it('should show vega graph (may fail in dev env)', async function () { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js index 8a542fec0639c..7a68e847f13b1 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js @@ -42,15 +42,13 @@ const $visCanvas = $('
') let count = 0; const visHeight = $visCanvas.height(); -$visCanvas.new = function() { +$visCanvas.new = function () { count += 1; if (count > 1) $visCanvas.height(visHeight * count); - return $('
') - .addClass('visChart') - .appendTo($visCanvas); + return $('
').addClass('visChart').appendTo($visCanvas); }; -afterEach(function() { +afterEach(function () { $visCanvas.empty(); if (count > 1) $visCanvas.height(visHeight); count = 0; diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js index 81fef155daf57..6790c49691dfd 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js @@ -25,7 +25,7 @@ import { ChartTitle } from '../../../../../../../plugins/vis_type_vislib/public/ import { VisConfig } from '../../../../../../../plugins/vis_type_vislib/public/vislib/lib/vis_config'; import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; -describe('Vislib ChartTitle Class Test Suite', function() { +describe('Vislib ChartTitle Class Test Suite', function () { let mockUiState; let chartTitle; let el; @@ -90,15 +90,9 @@ describe('Vislib ChartTitle Class Test Suite', function() { beforeEach(() => { mockUiState = getMockUiState(); - el = d3 - .select('body') - .append('div') - .attr('class', 'visWrapper') - .datum(data); + el = d3.select('body').append('div').attr('class', 'visWrapper').datum(data); - el.append('div') - .attr('class', 'chart-title') - .style('height', '20px'); + el.append('div').attr('class', 'chart-title').style('height', '20px'); const visConfig = new VisConfig( { @@ -115,31 +109,26 @@ describe('Vislib ChartTitle Class Test Suite', function() { chartTitle = new ChartTitle(visConfig); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { chartTitle.render(); }); - it('should append an svg to div', function() { + it('should append an svg to div', function () { expect(el.select('.chart-title').selectAll('svg').length).to.be(1); }); - it('should append text', function() { - expect( - !!el - .select('.chart-title') - .selectAll('svg') - .selectAll('text') - ).to.be(true); + it('should append text', function () { + expect(!!el.select('.chart-title').selectAll('svg').selectAll('text')).to.be(true); }); }); - describe('draw Method', function() { - it('should be a function', function() { + describe('draw Method', function () { + it('should be a function', function () { expect(_.isFunction(chartTitle.draw())).to.be(true); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js index eb4e109690c37..4f8cee2651a9f 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js @@ -27,20 +27,16 @@ import data from '../../../../../../../plugins/vis_type_vislib/public/fixtures/m import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib Dispatch Class Test Suite', function() { +describe('Vislib Dispatch Class Test Suite', function () { function destroyVis(vis) { vis.destroy(); } function getEls(element, n, type) { - return d3 - .select(element) - .data(new Array(n)) - .enter() - .append(type); + return d3.select(element).data(new Array(n)).enter().append(type); } - describe('', function() { + describe('', function () { let vis; let mockUiState; @@ -50,14 +46,14 @@ describe('Vislib Dispatch Class Test Suite', function() { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { destroyVis(vis); }); - it('implements on, off, emit methods', function() { + it('implements on, off, emit methods', function () { const events = _.pluck(vis.handler.charts, 'events'); expect(events.length).to.be.above(0); - events.forEach(function(dispatch) { + events.forEach(function (dispatch) { expect(dispatch).to.have.property('on'); expect(dispatch).to.have.property('off'); expect(dispatch).to.have.property('emit'); @@ -65,7 +61,7 @@ describe('Vislib Dispatch Class Test Suite', function() { }); }); - describe('Stock event handlers', function() { + describe('Stock event handlers', function () { let vis; let mockUiState; @@ -76,19 +72,19 @@ describe('Vislib Dispatch Class Test Suite', function() { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { destroyVis(vis); }); - describe('addEvent method', function() { - it('returns a function that binds the passed event to a selection', function() { + describe('addEvent method', function () { + it('returns a function that binds the passed event to a selection', function () { const chart = _.first(vis.handler.charts); const apply = chart.events.addEvent('event', _.noop); expect(apply).to.be.a('function'); const els = getEls(vis.element, 3, 'div'); apply(els); - els.each(function() { + els.each(function () { expect(d3.select(this).on('event')).to.be(_.noop); }); }); @@ -97,21 +93,21 @@ describe('Vislib Dispatch Class Test Suite', function() { // test the addHoverEvent, addClickEvent methods by // checking that they return function which bind the events expected function checkBoundAddMethod(name, event) { - describe(name + ' method', function() { - it('should be a function', function() { - vis.handler.charts.forEach(function(chart) { + describe(name + ' method', function () { + it('should be a function', function () { + vis.handler.charts.forEach(function (chart) { expect(chart.events[name]).to.be.a('function'); }); }); - it('returns a function that binds ' + event + ' events to a selection', function() { + it('returns a function that binds ' + event + ' events to a selection', function () { const chart = _.first(vis.handler.charts); const apply = chart.events[name](chart.series[0].chartEl); expect(apply).to.be.a('function'); const els = getEls(vis.element, 3, 'div'); apply(els); - els.each(function() { + els.each(function () { expect(d3.select(this).on(event)).to.be.a('function'); }); }); @@ -122,9 +118,9 @@ describe('Vislib Dispatch Class Test Suite', function() { checkBoundAddMethod('addMouseoutEvent', 'mouseout'); checkBoundAddMethod('addClickEvent', 'click'); - describe('addMousePointer method', function() { - it('should be a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('addMousePointer method', function () { + it('should be a function', function () { + vis.handler.charts.forEach(function (chart) { const pointer = chart.events.addMousePointer; expect(_.isFunction(pointer)).to.be(true); @@ -177,14 +173,14 @@ describe('Vislib Dispatch Class Test Suite', function() { }); }); - describe('Custom event handlers', function() { - it('should attach whatever gets passed on vis.on() to chart.events', function(done) { + describe('Custom event handlers', function () { + it('should attach whatever gets passed on vis.on() to chart.events', function (done) { const vis = getVis(); const mockUiState = getMockUiState(); vis.on('someEvent', _.noop); vis.render(data, mockUiState); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect(chart.events.listenerCount('someEvent')).to.be(1); }); @@ -192,13 +188,13 @@ describe('Vislib Dispatch Class Test Suite', function() { done(); }); - it('can be added after rendering', function() { + it('can be added after rendering', function () { const vis = getVis(); const mockUiState = getMockUiState(); vis.render(data, mockUiState); vis.on('someEvent', _.noop); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect(chart.events.listenerCount('someEvent')).to.be(1); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js index 27f7f4ed3e073..e4f75c47e621c 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js @@ -31,8 +31,8 @@ import { getVis } from '../../_vis_fixture'; const dateHistogramArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dateHistogramArray.forEach(function(data, i) { - describe('Vislib Handler Test Suite for ' + names[i] + ' Data', function() { +dateHistogramArray.forEach(function (data, i) { + describe('Vislib Handler Test Suite for ' + names[i] + ' Data', function () { const events = ['click', 'brush']; let vis; @@ -41,100 +41,100 @@ dateHistogramArray.forEach(function(data, i) { vis.render(data, getMockUiState()); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('render Method', function() { - it('should render charts', function() { + describe('render Method', function () { + it('should render charts', function () { expect(vis.handler.charts.length).to.be.greaterThan(0); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('svg').length).to.be(1); }); }); }); - describe('enable Method', function() { + describe('enable Method', function () { let charts; - beforeEach(function() { + beforeEach(function () { charts = vis.handler.charts; - charts.forEach(function(chart) { - events.forEach(function(event) { + charts.forEach(function (chart) { + events.forEach(function (event) { vis.handler.enable(event, chart); }); }); }); - it('should add events to chart and emit to the Events class', function() { - charts.forEach(function(chart) { - events.forEach(function(event) { + it('should add events to chart and emit to the Events class', function () { + charts.forEach(function (chart) { + events.forEach(function (event) { expect(chart.events.listenerCount(event)).to.be.above(0); }); }); }); }); - describe('disable Method', function() { + describe('disable Method', function () { let charts; - beforeEach(function() { + beforeEach(function () { charts = vis.handler.charts; - charts.forEach(function(chart) { - events.forEach(function(event) { + charts.forEach(function (chart) { + events.forEach(function (event) { vis.handler.disable(event, chart); }); }); }); - it('should remove events from the chart', function() { - charts.forEach(function(chart) { - events.forEach(function(event) { + it('should remove events from the chart', function () { + charts.forEach(function (chart) { + events.forEach(function (event) { expect(chart.events.listenerCount(event)).to.be(0); }); }); }); }); - describe('removeAll Method', function() { - beforeEach(function() { + describe('removeAll Method', function () { + beforeEach(function () { vis.handler.removeAll(vis.element); }); - it('should remove all DOM elements from the el', function() { + it('should remove all DOM elements from the el', function () { expect($(vis.element).children().length).to.be(0); }); }); - describe('error Method', function() { - beforeEach(function() { + describe('error Method', function () { + beforeEach(function () { vis.handler.error('This is an error!'); }); - it('should return an error classed DOM element with a text message', function() { + it('should return an error classed DOM element with a text message', function () { expect($(vis.element).find('.error').length).to.be(1); expect($('.error h4').html()).to.be('This is an error!'); }); }); - describe('destroy Method', function() { - beforeEach(function() { + describe('destroy Method', function () { + beforeEach(function () { vis.handler.destroy(); }); - it('should destroy all the charts in the visualization', function() { + it('should destroy all the charts in the visualization', function () { expect(vis.handler.charts.length).to.be(0); }); }); - describe('event proxying', function() { - it('should only pass the original event object to downstream handlers', function(done) { + describe('event proxying', function () { + it('should only pass the original event object to downstream handlers', function (done) { const event = {}; const chart = vis.handler.charts[0]; - const mockEmitter = function() { + const mockEmitter = function () { const args = Array.from(arguments); expect(args.length).to.be(2); expect(args[0]).to.be('click'); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js index 505b0a04c6183..7ad962fefc341 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js @@ -34,8 +34,8 @@ import { getVis } from '../../_vis_fixture'; const dateHistogramArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dateHistogramArray.forEach(function(data, i) { - describe('Vislib Layout Class Test Suite for ' + names[i] + ' Data', function() { +dateHistogramArray.forEach(function (data, i) { + describe('Vislib Layout Class Test Suite for ' + names[i] + ' Data', function () { let vis; let mockUiState; let numberOfCharts; @@ -52,8 +52,8 @@ dateHistogramArray.forEach(function(data, i) { vis.destroy(); }); - describe('createLayout Method', function() { - it('should append all the divs', function() { + describe('createLayout Method', function () { + it('should append all the divs', function () { expect($(vis.element).find('.visWrapper').length).to.be(1); expect($(vis.element).find('.visAxis--y').length).to.be(2); expect($(vis.element).find('.visWrapper__column').length).to.be(1); @@ -68,8 +68,8 @@ dateHistogramArray.forEach(function(data, i) { }); }); - describe('layout Method', function() { - beforeEach(function() { + describe('layout Method', function () { + beforeEach(function () { const visConfig = new VisConfig( { type: 'histogram', @@ -82,28 +82,24 @@ dateHistogramArray.forEach(function(data, i) { testLayout = new Layout(visConfig); }); - it('should append a div with the correct class name', function() { + it('should append a div with the correct class name', function () { expect($(vis.element).find('.chart').length).to.be(numberOfCharts); }); - it('should bind data to the DOM element', function() { - expect( - !!$(vis.element) - .find('.chart') - .data() - ).to.be(true); + it('should bind data to the DOM element', function () { + expect(!!$(vis.element).find('.chart').data()).to.be(true); }); - it('should create children', function() { + it('should create children', function () { expect(typeof $(vis.element).find('.x-axis-div')).to.be('object'); }); - it('should call split function when provided', function() { + it('should call split function when provided', function () { expect(typeof $(vis.element).find('.x-axis-div')).to.be('object'); }); - it('should throw errors when incorrect arguments provided', function() { - expect(function() { + it('should throw errors when incorrect arguments provided', function () { + expect(function () { testLayout.layout({ parent: vis.element, type: undefined, @@ -111,24 +107,24 @@ dateHistogramArray.forEach(function(data, i) { }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ type: 'div', class: 'chart', }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ parent: 'histogram', type: 'div', }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ parent: vis.element, - type: function(d) { + type: function (d) { return d; }, class: 'chart', @@ -137,27 +133,25 @@ dateHistogramArray.forEach(function(data, i) { }); }); - describe('appendElem Method', function() { - beforeEach(function() { + describe('appendElem Method', function () { + beforeEach(function () { vis.handler.layout.appendElem(vis.element, 'svg', 'column'); vis.handler.layout.appendElem('.visChart', 'div', 'test'); }); - it('should append DOM element to el with a class name', function() { + it('should append DOM element to el with a class name', function () { expect(typeof $(vis.element).find('.column')).to.be('object'); expect(typeof $(vis.element).find('.test')).to.be('object'); }); }); - describe('removeAll Method', function() { - beforeEach(function() { - d3.select(vis.element) - .append('div') - .attr('class', 'visualize'); + describe('removeAll Method', function () { + beforeEach(function () { + d3.select(vis.element).append('div').attr('class', 'visualize'); vis.handler.layout.removeAll(vis.element); }); - it('should remove all DOM elements from the el', function() { + it('should remove all DOM elements from the el', function () { expect($(vis.element).children().length).to.be(0); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js index 67f29ee96a336..36decdc415ed8 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js @@ -31,8 +31,8 @@ import { getVis } from './_vis_fixture'; const dataArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dataArray.forEach(function(data, i) { - describe('Vislib Vis Test Suite for ' + names[i] + ' Data', function() { +dataArray.forEach(function (data, i) { + describe('Vislib Vis Test Suite for ' + names[i] + ' Data', function () { const beforeEvent = 'click'; const afterEvent = 'brush'; let vis; @@ -46,31 +46,31 @@ dataArray.forEach(function(data, i) { mockUiState = getMockUiState(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); secondVis.destroy(); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { vis.render(data, mockUiState); numberOfCharts = vis.handler.charts.length; }); - it('should bind data to this object', function() { + it('should bind data to this object', function () { expect(_.isObject(vis.data)).to.be(true); }); - it('should instantiate a handler object', function() { + it('should instantiate a handler object', function () { expect(_.isObject(vis.handler)).to.be(true); }); - it('should append a chart', function() { + it('should append a chart', function () { expect($('.chart').length).to.be(numberOfCharts); }); - it('should throw an error if no data is provided', function() { - expect(function() { + it('should throw an error if no data is provided', function () { + expect(function () { vis.render(null, mockUiState); }).to.throwError(); }); @@ -82,55 +82,55 @@ dataArray.forEach(function(data, i) { }); }); - describe('destroy Method', function() { - beforeEach(function() { + describe('destroy Method', function () { + beforeEach(function () { vis.render(data, mockUiState); secondVis.render(data, mockUiState); secondVis.destroy(); }); - it('should remove all DOM elements from el', function() { + it('should remove all DOM elements from el', function () { expect($(secondVis.el).find('.visWrapper').length).to.be(0); }); - it('should not remove visualizations that have not been destroyed', function() { + it('should not remove visualizations that have not been destroyed', function () { expect($(vis.element).find('.visWrapper').length).to.be(1); }); }); - describe('set Method', function() { - beforeEach(function() { + describe('set Method', function () { + beforeEach(function () { vis.render(data, mockUiState); vis.set('addLegend', false); vis.set('offset', 'wiggle'); }); - it('should set an attribute', function() { + it('should set an attribute', function () { expect(vis.get('addLegend')).to.be(false); expect(vis.get('offset')).to.be('wiggle'); }); }); - describe('get Method', function() { - beforeEach(function() { + describe('get Method', function () { + beforeEach(function () { vis.render(data, mockUiState); }); - it('should get attribute values', function() { + it('should get attribute values', function () { expect(vis.get('addLegend')).to.be(true); expect(vis.get('addTooltip')).to.be(true); expect(vis.get('type')).to.be('point_series'); }); }); - describe('on Method', function() { + describe('on Method', function () { let listeners; - beforeEach(function() { - listeners = [function() {}, function() {}]; + beforeEach(function () { + listeners = [function () {}, function () {}]; // Add event and listeners to chart - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(beforeEvent, listener); }); @@ -138,50 +138,50 @@ dataArray.forEach(function(data, i) { vis.render(data, mockUiState); // Add event after charts have rendered - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(afterEvent, listener); }); }); - afterEach(function() { + afterEach(function () { vis.removeAllListeners(beforeEvent); vis.removeAllListeners(afterEvent); }); - it('should add an event and its listeners', function() { - listeners.forEach(function(listener) { + it('should add an event and its listeners', function () { + listeners.forEach(function (listener) { expect(vis.listeners(beforeEvent)).to.contain(listener); }); - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { expect(vis.listeners(afterEvent)).to.contain(listener); }); }); - it('should cause a listener for each event to be attached to each chart', function() { + it('should cause a listener for each event to be attached to each chart', function () { const charts = vis.handler.charts; - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be.above(0); }); }); }); - describe('off Method', function() { + describe('off Method', function () { let listeners; let listener1; let listener2; - beforeEach(function() { + beforeEach(function () { listeners = []; - listener1 = function() {}; - listener2 = function() {}; + listener1 = function () {}; + listener2 = function () {}; listeners.push(listener1); listeners.push(listener2); // Add event and listeners to chart - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(beforeEvent, listener); }); @@ -192,7 +192,7 @@ dataArray.forEach(function(data, i) { vis.render(data, mockUiState); // Add event after charts have rendered - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(afterEvent, listener); }); @@ -200,12 +200,12 @@ dataArray.forEach(function(data, i) { vis.off(afterEvent, listener1); }); - afterEach(function() { + afterEach(function () { vis.removeAllListeners(beforeEvent); vis.removeAllListeners(afterEvent); }); - it('should remove a listener', function() { + it('should remove a listener', function () { const charts = vis.handler.charts; expect(vis.listeners(beforeEvent)).to.not.contain(listener1); @@ -215,13 +215,13 @@ dataArray.forEach(function(data, i) { expect(vis.listeners(afterEvent)).to.contain(listener2); // Events should still be attached to charts - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be.above(0); }); }); - it('should remove the event and all listeners when only event passed an argument', function() { + it('should remove the event and all listeners when only event passed an argument', function () { const charts = vis.handler.charts; vis.removeAllListeners(afterEvent); @@ -230,19 +230,19 @@ dataArray.forEach(function(data, i) { expect(vis.listeners(afterEvent)).to.not.contain(listener2); // should remove the event from the charts - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be(0); }); }); - it('should remove the event from the chart when the last listener is removed', function() { + it('should remove the event from the chart when the last listener is removed', function () { const charts = vis.handler.charts; vis.off(afterEvent, listener2); expect(vis.listenerCount(afterEvent)).to.be(0); - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(afterEvent)).to.be(0); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js index eb529c380cdda..fd2240c0c64c5 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js @@ -41,8 +41,8 @@ const visLibParams = { mode: 'stacked', }; -_.forOwn(dataTypesArray, function(dataType, dataTypeName) { - describe('Vislib Area Chart Test Suite for ' + dataTypeName + ' Data', function() { +_.forOwn(dataTypesArray, function (dataType, dataTypeName) { + describe('Vislib Area Chart Test Suite for ' + dataTypeName + ' Data', function () { let vis; let mockUiState; @@ -53,46 +53,46 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { vis.render(dataType, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('stackData method', function() { + describe('stackData method', function () { let stackedData; let isStacked; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { stackedData = chart.chartData; - isStacked = stackedData.series.every(function(arr) { - return arr.values.every(function(d) { + isStacked = stackedData.series.every(function (arr) { + return arr.values.every(function (d) { return _.isNumber(d.y0); }); }); }); }); - it('should append a d.y0 key to the data object', function() { + it('should append a d.y0 key to the data object', function () { expect(isStacked).to.be(true); }); }); - describe('addPath method', function() { - it('should append a area paths', function() { - vis.handler.charts.forEach(function(chart) { + describe('addPath method', function () { + it('should append a area paths', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); }); - describe('addPathEvents method', function() { + describe('addPathEvents method', function () { let path; let d3selectedPath; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { path = $(chart.chartEl).find('path')[0]; d3selectedPath = d3.select(path)[0][0]; @@ -101,14 +101,14 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircleEvents method', function() { + describe('addCircleEvents method', function () { let circle; let brush; let d3selectedCircle; @@ -117,7 +117,7 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { let onMouseOver; beforeEach(() => { - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { circle = $(chart.chartEl).find('circle')[0]; brush = $(chart.chartEl).find('.brush'); d3selectedCircle = d3.select(circle)[0][0]; @@ -134,40 +134,40 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { // listeners, however, I was not able to test for the listener // function being present. I will need to update this test // in the future. - it('should attach a brush g element', function() { - vis.handler.charts.forEach(function() { + it('should attach a brush g element', function () { + vis.handler.charts.forEach(function () { expect(onBrush).to.be(true); }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircles method', function() { - it('should append circles', function() { - vis.handler.charts.forEach(function(chart) { + describe('addCircles method', function () { + it('should append circles', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('circle').length).to.be.greaterThan(0); }); }); - it('should not draw circles where d.y === 0', function() { - vis.handler.charts.forEach(function(chart) { + it('should not draw circles where d.y === 0', function () { + vis.handler.charts.forEach(function (chart) { const series = chart.chartData.series; - const isZero = series.some(function(d) { + const isZero = series.some(function (d) { return d.y === 0; }); const circles = $.makeArray($(chart.chartEl).find('circle')); - const isNotDrawn = circles.some(function(d) { + const isNotDrawn = circles.some(function (d) { return d.__data__.y === 0; }); @@ -178,15 +178,15 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -195,8 +195,8 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -206,14 +206,14 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(dataType, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -223,16 +223,16 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(dataType, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js index 4c5e3db316243..2b41ce5d1a5c6 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js @@ -24,7 +24,7 @@ import { Chart } from '../../../../../../../plugins/vis_type_vislib/public/visli import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib _chart Test Suite', function() { +describe('Vislib _chart Test Suite', function () { let vis; let el; let myChart; @@ -96,10 +96,10 @@ describe('Vislib _chart Test Suite', function() { ], }, ], - tooltipFormatter: function(datapoint) { + tooltipFormatter: function (datapoint) { return datapoint; }, - xAxisFormatter: function(thing) { + xAxisFormatter: function (thing) { return thing; }, xAxisLabel: 'Date Histogram', @@ -107,10 +107,7 @@ describe('Vislib _chart Test Suite', function() { }; beforeEach(() => { - el = d3 - .select('body') - .append('div') - .attr('class', 'column-chart'); + el = d3.select('body').append('div').attr('class', 'column-chart'); config = { type: 'histogram', @@ -125,16 +122,16 @@ describe('Vislib _chart Test Suite', function() { myChart = vis.handler.charts[0]; }); - afterEach(function() { + afterEach(function () { el.remove(); vis.destroy(); }); - it('should be a constructor for visualization modules', function() { + it('should be a constructor for visualization modules', function () { expect(myChart instanceof Chart).to.be(true); }); - it('should have a render method', function() { + it('should have a render method', function () { expect(typeof myChart.render === 'function').to.be(true); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js index 5cbd5948bc477..f075dff466793 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js @@ -46,12 +46,12 @@ const dataTypesArray = [ ['stackedSeries', 'stacked', stackedSeries], ]; -dataTypesArray.forEach(function(dataType) { +dataTypesArray.forEach(function (dataType) { const name = dataType[0]; const mode = dataType[1]; const data = dataType[2]; - describe('Vislib Column Chart Test Suite for ' + name + ' Data', function() { + describe('Vislib Column Chart Test Suite for ' + name + ' Data', function () { let vis; let mockUiState; const visLibParams = { @@ -73,46 +73,46 @@ dataTypesArray.forEach(function(dataType) { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('stackData method', function() { + describe('stackData method', function () { let stackedData; let isStacked; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { stackedData = chart.chartData; - isStacked = stackedData.series.every(function(arr) { - return arr.values.every(function(d) { + isStacked = stackedData.series.every(function (arr) { + return arr.values.every(function (d) { return _.isNumber(d.y0); }); }); }); }); - it('should stack values when mode is stacked', function() { + it('should stack values when mode is stacked', function () { if (mode === 'stacked') { expect(isStacked).to.be(true); } }); - it('should stack values when mode is percentage', function() { + it('should stack values when mode is percentage', function () { if (mode === 'percentage') { expect(isStacked).to.be(true); } }); }); - describe('addBars method', function() { - it('should append rects', function() { + describe('addBars method', function () { + it('should append rects', function () { let numOfSeries; let numOfValues; let product; - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { numOfSeries = chart.chartData.series.length; numOfValues = chart.chartData.series[0].values.length; product = numOfSeries * numOfValues; @@ -121,11 +121,9 @@ dataTypesArray.forEach(function(dataType) { }); }); - describe('addBarEvents method', function() { + describe('addBarEvents method', function () { function checkChart(chart) { - const rect = $(chart.chartEl) - .find('.series rect') - .get(0); + const rect = $(chart.chartEl).find('.series rect').get(0); // check for existence of stuff and things return { @@ -140,8 +138,8 @@ dataTypesArray.forEach(function(dataType) { }; } - it('should attach the brush if data is a set is ordered', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach the brush if data is a set is ordered', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); const ordered = vis.handler.data.get('ordered'); const allowBrushing = Boolean(ordered); @@ -149,30 +147,30 @@ dataTypesArray.forEach(function(dataType) { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a click event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.click).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.mouseOver).to.be(true); }); }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -181,8 +179,8 @@ dataTypesArray.forEach(function(dataType) { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -192,14 +190,14 @@ dataTypesArray.forEach(function(dataType) { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -209,16 +207,16 @@ dataTypesArray.forEach(function(dataType) { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -240,7 +238,7 @@ dataTypesArray.forEach(function(dataType) { }); }); -describe('stackData method - data set with zeros in percentage mode', function() { +describe('stackData method - data set with zeros in percentage mode', function () { let vis; let mockUiState; const visLibParams = { @@ -257,11 +255,11 @@ describe('stackData method - data set with zeros in percentage mode', function() vis.on('brush', _.noop); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should not mutate the injected zeros', function() { + it('should not mutate the injected zeros', function () { vis.render(seriesMonthlyInterval, mockUiState); expect(vis.handler.charts).to.have.length(1); @@ -274,7 +272,7 @@ describe('stackData method - data set with zeros in percentage mode', function() expect(point.y).to.be(0); }); - it('should not mutate zeros that exist in the data', function() { + it('should not mutate zeros that exist in the data', function () { vis.render(rowsWithZeros, mockUiState); expect(vis.handler.charts).to.have.length(2); @@ -287,7 +285,7 @@ describe('stackData method - data set with zeros in percentage mode', function() }); }); -describe('datumWidth - split chart data set with holes', function() { +describe('datumWidth - split chart data set with holes', function () { let vis; let mockUiState; const visLibParams = { @@ -305,23 +303,23 @@ describe('datumWidth - split chart data set with holes', function() { vis.render(rowsSeriesWithHoles, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should not have bar widths that span multiple time bins', function() { + it('should not have bar widths that span multiple time bins', function () { expect(vis.handler.charts.length).to.equal(1); const chart = vis.handler.charts[0]; const rects = $(chart.chartEl).find('.series rect'); const MAX_WIDTH_IN_PIXELS = 27; - rects.each(function() { + rects.each(function () { const width = $(this).attr('width'); expect(width).to.be.lessThan(MAX_WIDTH_IN_PIXELS); }); }); }); -describe('datumWidth - monthly interval', function() { +describe('datumWidth - monthly interval', function () { let vis; let mockUiState; const visLibParams = { @@ -339,11 +337,11 @@ describe('datumWidth - monthly interval', function() { vis.render(seriesMonthlyInterval, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should vary bar width when date histogram intervals are not equal', function() { + it('should vary bar width when date histogram intervals are not equal', function () { expect(vis.handler.charts.length).to.equal(1); const chart = vis.handler.charts[0]; const rects = $(chart.chartEl).find('.series rect'); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js index d8ce8f1f5f44b..7c588800ae659 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js @@ -25,7 +25,7 @@ import data from '../../../../../../../plugins/vis_type_vislib/public/fixtures/m import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib Gauge Chart Test Suite', function() { +describe('Vislib Gauge Chart Test Suite', function () { let vis; let chartEl; const visLibParams = { @@ -86,21 +86,17 @@ describe('Vislib Gauge Chart Test Suite', function() { generateVis(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); $('.visChart').remove(); }); - it('creates meter gauge', function() { + it('creates meter gauge', function () { expect($(chartEl).find('svg').length).to.equal(5); - expect( - $(chartEl) - .find('svg > g > g > text') - .text() - ).to.equal('2820231918357341352'); + expect($(chartEl).find('svg > g > g > text').text()).to.equal('2820231918357341352'); }); - it('creates circle gauge', function() { + it('creates circle gauge', function () { generateVis({ gauge: { minAngle: 0, @@ -110,36 +106,28 @@ describe('Vislib Gauge Chart Test Suite', function() { expect($(chartEl).find('svg').length).to.equal(5); }); - it('creates gauge with automatic mode', function() { + it('creates gauge with automatic mode', function () { generateVis({ gauge: { alignment: 'automatic', }, }); - expect( - $(chartEl) - .find('svg') - .width() - ).to.equal(197); + expect($(chartEl).find('svg').width()).to.equal(197); }); - it('creates gauge with vertical mode', function() { + it('creates gauge with vertical mode', function () { generateVis({ gauge: { alignment: 'vertical', }, }); - expect( - $(chartEl) - .find('svg') - .width() - ).to.equal($(chartEl).width()); + expect($(chartEl).find('svg').width()).to.equal($(chartEl).width()); }); - it('applies range settings correctly', function() { + it('applies range settings correctly', function () { const paths = $(chartEl).find('svg > g > g:nth-child(1) > path:nth-child(2)'); const fills = []; - paths.each(function() { + paths.each(function () { fills.push(this.style.fill); }); expect(fills).to.eql([ @@ -151,7 +139,7 @@ describe('Vislib Gauge Chart Test Suite', function() { ]); }); - it('applies color schema correctly', function() { + it('applies color schema correctly', function () { generateVis({ gauge: { colorSchema: 'Blues', @@ -159,7 +147,7 @@ describe('Vislib Gauge Chart Test Suite', function() { }); const paths = $(chartEl).find('svg > g > g:nth-child(1) > path:nth-child(2)'); const fills = []; - paths.each(function() { + paths.each(function () { fills.push(this.style.fill); }); expect(fills).to.eql([ diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js index 765b9118e6844..9fa51fb59ed48 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js @@ -40,12 +40,12 @@ const dataTypesArray = [ ['stackedSeries', stackedSeries], ]; -describe('Vislib Heatmap Chart Test Suite', function() { - dataTypesArray.forEach(function(dataType) { +describe('Vislib Heatmap Chart Test Suite', function () { + dataTypesArray.forEach(function (dataType) { const name = dataType[0]; const data = dataType[1]; - describe('for ' + name + ' Data', function() { + describe('for ' + name + ' Data', function () { let vis; let mockUiState; const visLibParams = { @@ -72,12 +72,12 @@ describe('Vislib Heatmap Chart Test Suite', function() { generateVis(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); it('category axes should be rendered in reverse order', () => { - const renderedCategoryAxes = vis.handler.renderArray.filter(item => { + const renderedCategoryAxes = vis.handler.renderArray.filter((item) => { return ( item.constructor && item.constructor.name === 'Axis' && @@ -93,9 +93,9 @@ describe('Vislib Heatmap Chart Test Suite', function() { ); }); - describe('addSquares method', function() { - it('should append rects', function() { - vis.handler.charts.forEach(function(chart) { + describe('addSquares method', function () { + it('should append rects', function () { + vis.handler.charts.forEach(function (chart) { const numOfRects = chart.chartData.series.reduce((result, series) => { return result + series.values.length; }, 0); @@ -104,11 +104,9 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - describe('addBarEvents method', function() { + describe('addBarEvents method', function () { function checkChart(chart) { - const rect = $(chart.chartEl) - .find('.series rect') - .get(0); + const rect = $(chart.chartEl).find('.series rect').get(0); return { click: !!rect.__onclick, @@ -122,8 +120,8 @@ describe('Vislib Heatmap Chart Test Suite', function() { }; } - it('should attach the brush if data is a set of ordered dates', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach the brush if data is a set of ordered dates', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); const ordered = vis.handler.data.get('ordered'); const date = Boolean(ordered && ordered.date); @@ -131,30 +129,30 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a click event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.click).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.mouseOver).to.be(true); }); }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -164,11 +162,11 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - it('should define default colors', function() { + it('should define default colors', function () { expect(mockUiState.get('vis.defaultColors')).to.not.be(undefined); }); - it('should set custom range', function() { + it('should set custom range', function () { vis.destroy(); generateVis({ setColorRange: true, @@ -186,7 +184,7 @@ describe('Vislib Heatmap Chart Test Suite', function() { expect(labels[3]).to.be('500 - Infinity'); }); - it('should show correct Y axis title', function() { + it('should show correct Y axis title', function () { expect(vis.handler.categoryAxes[1].axisConfig.get('title.text')).to.equal(''); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js index 691417e968eed..dae92c831cd8d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js @@ -41,12 +41,12 @@ const dataTypes = [ ['term series', termSeries], ]; -describe('Vislib Line Chart', function() { - dataTypes.forEach(function(type) { +describe('Vislib Line Chart', function () { + dataTypes.forEach(function (type) { const name = type[0]; const data = type[1]; - describe(name + ' Data', function() { + describe(name + ' Data', function () { let vis; let mockUiState; @@ -64,11 +64,11 @@ describe('Vislib Line Chart', function() { vis.on('brush', _.noop); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('addCircleEvents method', function() { + describe('addCircleEvents method', function () { let circle; let brush; let d3selectedCircle; @@ -76,8 +76,8 @@ describe('Vislib Line Chart', function() { let onClick; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { circle = $(chart.chartEl).find('.circle')[0]; brush = $(chart.chartEl).find('.brush'); d3selectedCircle = d3.select(circle)[0][0]; @@ -94,36 +94,36 @@ describe('Vislib Line Chart', function() { // listeners, however, I was not able to test for the listener // function being present. I will need to update this test // in the future. - it('should attach a brush g element', function() { - vis.handler.charts.forEach(function() { + it('should attach a brush g element', function () { + vis.handler.charts.forEach(function () { expect(onBrush).to.be(true); }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircles method', function() { - it('should append circles', function() { - vis.handler.charts.forEach(function(chart) { + describe('addCircles method', function () { + it('should append circles', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('circle').length).to.be.greaterThan(0); }); }); }); - describe('addLines method', function() { - it('should append a paths', function() { - vis.handler.charts.forEach(function(chart) { + describe('addLines method', function () { + it('should append a paths', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); @@ -139,15 +139,15 @@ describe('Vislib Line Chart', function() { // }); //}); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(chart.draw()).to.be.a(Function); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); expect(domain[0]).to.not.be(undefined); @@ -155,8 +155,8 @@ describe('Vislib Line Chart', function() { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -166,14 +166,14 @@ describe('Vislib Line Chart', function() { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -183,16 +183,16 @@ describe('Vislib Line Chart', function() { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js index 506ad2af85c34..d245905729c7e 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js @@ -30,7 +30,7 @@ const names = ['rows', 'columns', 'slices']; const sizes = [0, 5, 15, 30, 60, 120]; -describe('No global chart settings', function() { +describe('No global chart settings', function () { const visLibParams1 = { el: '
', type: 'pie', @@ -49,15 +49,15 @@ describe('No global chart settings', function() { chart1.render(pieChartMockData.rowData, mockUiState); }); - afterEach(function() { + afterEach(function () { chart1.destroy(); }); - it('should render chart titles for all charts', function() { + it('should render chart titles for all charts', function () { expect($(chart1.element).find('.visAxis__splitTitles--y').length).to.be(1); }); - describe('_validatePieData method', function() { + describe('_validatePieData method', function () { const allZeros = [ { slices: { children: [] } }, { slices: { children: [] } }, @@ -76,26 +76,26 @@ describe('No global chart settings', function() { { slices: { children: [{}] } }, ]; - it('should throw an error when all charts contain zeros', function() { - expect(function() { + it('should throw an error when all charts contain zeros', function () { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(allZeros); }).to.throwError(); }); - it('should not throw an error when only some or no charts contain zeros', function() { - expect(function() { + it('should not throw an error when only some or no charts contain zeros', function () { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(someZeros); }).to.not.throwError(); - expect(function() { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(noZeros); }).to.not.throwError(); }); }); }); -describe('Vislib PieChart Class Test Suite', function() { - ['rowData', 'columnData', 'sliceData'].forEach(function(aggItem, i) { - describe('Vislib PieChart Class Test Suite for ' + names[i] + ' data', function() { +describe('Vislib PieChart Class Test Suite', function () { + ['rowData', 'columnData', 'sliceData'].forEach(function (aggItem, i) { + describe('Vislib PieChart Class Test Suite for ' + names[i] + ' data', function () { const mockPieData = pieChartMockData[aggItem]; const visLibParams = { @@ -111,18 +111,18 @@ describe('Vislib PieChart Class Test Suite', function() { vis.render(mockPieData, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('addPathEvents method', function() { + describe('addPathEvents method', function () { let path; let d3selectedPath; let onClick; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { path = $(chart.chartEl).find('path')[0]; d3selectedPath = d3.select(path)[0][0]; @@ -132,30 +132,28 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addPath method', function() { + describe('addPath method', function () { let width; let height; let svg; let slices; - it('should return an SVG object', function() { - vis.handler.charts.forEach(function(chart) { - $(chart.chartEl) - .find('svg') - .empty(); + it('should return an SVG object', function () { + vis.handler.charts.forEach(function (chart) { + $(chart.chartEl).find('svg').empty(); width = $(chart.chartEl).width(); height = $(chart.chartEl).height(); svg = d3.select($(chart.chartEl).find('svg')[0]); @@ -164,18 +162,16 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - it('should draw path elements', function() { - vis.handler.charts.forEach(function(chart) { + it('should draw path elements', function () { + vis.handler.charts.forEach(function (chart) { // test whether path elements are drawn expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); - it('should draw labels', function() { - vis.handler.charts.forEach(function(chart) { - $(chart.chartEl) - .find('svg') - .empty(); + it('should draw labels', function () { + vis.handler.charts.forEach(function (chart) { + $(chart.chartEl).find('svg').empty(); width = $(chart.chartEl).width(); height = $(chart.chartEl).height(); svg = d3.select($(chart.chartEl).find('svg')[0]); @@ -187,37 +183,37 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); }); - sizes.forEach(function(size) { - describe('containerTooSmall error', function() { - it('should throw an error', function() { + sizes.forEach(function (size) { + describe('containerTooSmall error', function () { + it('should throw an error', function () { // 20px is the minimum height and width - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { $(chart.chartEl).height(size); $(chart.chartEl).width(size); if (size < 20) { - expect(function() { + expect(function () { chart.render(); }).to.throwError(); } }); }); - it('should not throw an error', function() { - vis.handler.charts.forEach(function(chart) { + it('should not throw an error', function () { + vis.handler.charts.forEach(function (chart) { $(chart.chartEl).height(size); $(chart.chartEl).width(size); if (size > 20) { - expect(function() { + expect(function () { chart.render(); }).to.not.throwError(); } diff --git a/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts b/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts index 44a3507e57aa5..59e5238578d25 100644 --- a/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts +++ b/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts @@ -50,7 +50,7 @@ export class LocalApplicationService { * @param angularRouteManager The current `ui/routes` instance */ attachToAngular(angularRouteManager: UIRoutes) { - npStart.plugins.kibanaLegacy.getApps().forEach(app => { + npStart.plugins.kibanaLegacy.getApps().forEach((app) => { const wrapperElementId = this.idGenerator(); angularRouteManager.when(matchAllWithPrefix(app), { outerAngularWrapperRoute: true, @@ -87,7 +87,7 @@ export class LocalApplicationService { }); if (app.updater$) { - app.updater$.subscribe(updater => { + app.updater$.subscribe((updater) => { const updatedFields = updater(app); if (updatedFields && updatedFields.activeUrl) { npStart.core.chrome.navLinks.update(app.navLinkId || app.id, { @@ -98,7 +98,7 @@ export class LocalApplicationService { } }); - npStart.plugins.kibanaLegacy.getForwards().forEach(forwardDefinition => { + npStart.plugins.kibanaLegacy.getForwards().forEach((forwardDefinition) => { angularRouteManager.when(matchAllWithPrefix(forwardDefinition.legacyAppId), { outerAngularWrapperRoute: true, reloadOnSearch: false, diff --git a/src/legacy/core_plugins/kibana/public/management/index.js b/src/legacy/core_plugins/kibana/public/management/index.js index ff253629a4825..48f0e2517a486 100644 --- a/src/legacy/core_plugins/kibana/public/management/index.js +++ b/src/legacy/core_plugins/kibana/public/management/index.js @@ -117,12 +117,12 @@ export function updateSidebar(legacySections, id) { ); } -export const destroyReact = id => { +export const destroyReact = (id) => { const node = document.getElementById(id); node && unmountComponentAtNode(node); }; -uiModules.get('apps/management').directive('kbnManagementApp', function($location) { +uiModules.get('apps/management').directive('kbnManagementApp', function ($location) { return { restrict: 'E', template: appTemplate, @@ -133,14 +133,14 @@ uiModules.get('apps/management').directive('kbnManagementApp', function($locatio pageTitle: '=', }, - link: function($scope) { + link: function ($scope) { timefilter.disableAutoRefreshSelector(); timefilter.disableTimeRangeSelector(); $scope.sections = management.visibleItems; $scope.section = management.getSection($scope.sectionName) || management; if ($scope.section) { - $scope.section.items.forEach(item => { + $scope.section.items.forEach((item) => { item.active = `#${$location.path()}`.indexOf(item.url) > -1; }); } @@ -155,10 +155,10 @@ uiModules.get('apps/management').directive('kbnManagementApp', function($locatio }; }); -uiModules.get('apps/management').directive('kbnManagementLanding', function(kbnVersion) { +uiModules.get('apps/management').directive('kbnManagementLanding', function (kbnVersion) { return { restrict: 'E', - link: function($scope) { + link: function ($scope) { $scope.sections = management.visibleItems; $scope.kbnVersion = kbnVersion; }, diff --git a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts index 8aedc6f7332dc..d1be3d64fdb3f 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts +++ b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts @@ -103,13 +103,13 @@ const data: Array> = [ test('collects dashboard and all dependencies', async () => { const savedObjectClient = savedObjectsClientMock.create(); - savedObjectClient.bulkGet.mockImplementation(objects => { + savedObjectClient.bulkGet.mockImplementation((objects) => { if (!objects) { throw new Error('Invalid test data'); } return Promise.resolve({ saved_objects: objects.map( - (obj: any) => data.find(row => row.id === obj.id && row.type === obj.type)! + (obj: any) => data.find((row) => row.id === obj.id && row.type === obj.type)! ), }); }); diff --git a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts index 9d620b69bf2e3..e44db901a0cb8 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts +++ b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts @@ -40,7 +40,7 @@ export async function collectReferencesDeep( for (const reference of references) { const isDuplicate = queue .concat(result) - .some(obj => obj.type === reference.type && obj.id === reference.id); + .some((obj) => obj.type === reference.type && obj.id === reference.id); if (isDuplicate) { continue; } diff --git a/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js b/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js index 8df55aabb5554..913ebff588f84 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js +++ b/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js @@ -25,7 +25,7 @@ export async function exportDashboards(req) { const config = req.server.config(); const savedObjectsClient = req.getSavedObjectsClient(); - const objectsToExport = ids.map(id => ({ id, type: 'dashboard' })); + const objectsToExport = ids.map((id) => ({ id, type: 'dashboard' })); const objects = await collectReferencesDeep(savedObjectsClient, objectsToExport); return { diff --git a/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js b/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js index 4c68df7a1a960..7c28b184144f1 100644 --- a/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js +++ b/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js @@ -32,8 +32,8 @@ export async function importDashboards(req) { // need to set migrationVersion to something other than undefined, so that imported // docs are not seen as automatically up-to-date. const docs = payload.objects - .filter(item => !exclude.includes(item.type)) - .map(doc => ({ ...doc, migrationVersion: doc.migrationVersion || {} })); + .filter((item) => !exclude.includes(item.type)) + .map((doc) => ({ ...doc, migrationVersion: doc.migrationVersion || {} })); const results = await savedObjectsClient.bulkCreate(docs, { overwrite }); return { objects: results.saved_objects }; diff --git a/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js b/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js index 585d9ce938710..e0a6c574b7ad8 100644 --- a/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js +++ b/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js @@ -43,16 +43,16 @@ export async function findRelationships(type, id, options = {}) { return [].concat( referencedObjects.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) - .map(obj => ({ + .map((obj) => ({ ...obj, relationship: 'child', })), referencedResponse.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) - .map(obj => ({ + .map((obj) => ({ ...obj, relationship: 'parent', })) diff --git a/src/legacy/core_plugins/kibana/server/routes/api/export/index.js b/src/legacy/core_plugins/kibana/server/routes/api/export/index.js index b939e06b7bdb9..ef556ed53f4fc 100644 --- a/src/legacy/core_plugins/kibana/server/routes/api/export/index.js +++ b/src/legacy/core_plugins/kibana/server/routes/api/export/index.js @@ -38,7 +38,7 @@ export function exportApi(server) { method: ['GET'], handler: async (req, h) => { const currentDate = moment.utc(); - return exportDashboards(req).then(resp => { + return exportDashboards(req).then((resp) => { const json = JSON.stringify(resp, null, ' '); const filename = `kibana-dashboards.${currentDate.format('YYYY-MM-DD-HH-mm-ss')}.json`; return h diff --git a/src/legacy/core_plugins/kibana/server/routes/api/import/index.js b/src/legacy/core_plugins/kibana/server/routes/api/import/index.js index d0fa0bb4489cb..b7efb7da3c5a9 100644 --- a/src/legacy/core_plugins/kibana/server/routes/api/import/index.js +++ b/src/legacy/core_plugins/kibana/server/routes/api/import/index.js @@ -38,7 +38,7 @@ export function importApi(server) { tags: ['api'], }, - handler: async req => { + handler: async (req) => { return await importDashboards(req); }, }); diff --git a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js index 69ee2d80ea0a6..0d1b69778263c 100644 --- a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js +++ b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js @@ -32,7 +32,7 @@ export function getUiSettingDefaults() { // default fallback in case the locale is not found. const numeralLanguageIds = [ 'en', - ...numeralLanguages.map(function(numeralLanguage) { + ...numeralLanguages.map(function (numeralLanguage) { return numeralLanguage.id; }), ]; @@ -655,7 +655,7 @@ export function getUiSettingDefaults() { type: 'select', options: numeralLanguageIds, optionLabels: Object.fromEntries( - numeralLanguages.map(language => [language.id, language.name]) + numeralLanguages.map((language) => [language.id, language.name]) ), description: i18n.translate('kbn.advancedSettings.format.formattingLocaleText', { defaultMessage: `{numeralLanguageLink} locale`, diff --git a/src/legacy/core_plugins/status_page/index.js b/src/legacy/core_plugins/status_page/index.js index fc3bfc4c7c6c6..01991d8439a04 100644 --- a/src/legacy/core_plugins/status_page/index.js +++ b/src/legacy/core_plugins/status_page/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ uiExports: { app: { diff --git a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js b/src/legacy/core_plugins/status_page/public/components/metric_tiles.js index 8500bfea63aba..6cde975875ad1 100644 --- a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js +++ b/src/legacy/core_plugins/status_page/public/components/metric_tiles.js @@ -36,7 +36,7 @@ export class MetricTile extends Component { const metrics = [].concat(value); return metrics - .map(function(metric) { + .map(function (metric) { return formatNumber(metric, type); }) .join(', '); @@ -54,7 +54,7 @@ Wrapper component that simply maps each metric to MetricTile inside a FlexGroup */ const MetricTiles = ({ metrics }) => ( - {metrics.map(metric => ( + {metrics.map((metric) => ( diff --git a/src/legacy/core_plugins/status_page/public/components/status_app.js b/src/legacy/core_plugins/status_page/public/components/status_app.js index 353938e783a47..a6b0321e53a8f 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_app.js +++ b/src/legacy/core_plugins/status_page/public/components/status_app.js @@ -53,7 +53,7 @@ class StatusApp extends Component { }; } - componentDidMount = async function() { + componentDidMount = async function () { const data = await loadStatus(); if (data) { diff --git a/src/legacy/core_plugins/status_page/public/components/status_table.js b/src/legacy/core_plugins/status_page/public/components/status_table.js index 3eb04409f5f89..68b93153951cb 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_table.js +++ b/src/legacy/core_plugins/status_page/public/components/status_table.js @@ -37,7 +37,7 @@ class StatusTable extends Component { { field: 'state', name: '', - render: state => , + render: (state) => , width: '32px', }, { @@ -51,7 +51,7 @@ class StatusTable extends Component { name: i18n.translate('statusPage.statusTable.columns.statusHeader', { defaultMessage: 'Status', }), - render: state => {state.message}, + render: (state) => {state.message}, }, ]; diff --git a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js b/src/legacy/core_plugins/status_page/public/lib/load_status.test.js index 2a37b443b8653..a0f1930ca7667 100644 --- a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js +++ b/src/legacy/core_plugins/status_page/public/lib/load_status.test.js @@ -99,7 +99,7 @@ describe('response processing', () => { test('builds the metrics', async () => { const data = await loadStatus(mockFetch); - const names = data.metrics.map(m => m.name); + const names = data.metrics.map((m) => m.name); expect(names).toEqual([ 'Heap total', 'Heap used', @@ -109,7 +109,7 @@ describe('response processing', () => { 'Requests per second', ]); - const values = data.metrics.map(m => m.value); + const values = data.metrics.map((m) => m.value); expect(values).toEqual([1000000, 100, [4.1, 2.1, 0.1], 4000, 8000, 400]); }); }); diff --git a/src/legacy/core_plugins/status_page/public/status_page.js b/src/legacy/core_plugins/status_page/public/status_page.js index 82cd2aa5f395d..709164caa9e04 100644 --- a/src/legacy/core_plugins/status_page/public/status_page.js +++ b/src/legacy/core_plugins/status_page/public/status_page.js @@ -25,7 +25,7 @@ import template from 'plugins/status_page/status_page.html'; npStart.core.chrome.navLinks.enableForcedAppSwitcherNavigation(); -chrome.setRootTemplate(template).setRootController('ui', function($scope, buildNum, buildSha) { +chrome.setRootTemplate(template).setRootController('ui', function ($scope, buildNum, buildSha) { $scope.$$postDigest(() => { renderStatusPage(buildNum, buildSha.substr(0, 8)); $scope.$on('$destroy', destroyStatusPage); diff --git a/src/legacy/core_plugins/testbed/index.js b/src/legacy/core_plugins/testbed/index.js index 0cbd966100811..f0b61ea0c3de7 100644 --- a/src/legacy/core_plugins/testbed/index.js +++ b/src/legacy/core_plugins/testbed/index.js @@ -19,7 +19,7 @@ import { resolve } from 'path'; -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ id: 'testbed', publicDir: resolve(__dirname, 'public'), diff --git a/src/legacy/core_plugins/tests_bundle/find_source_files.js b/src/legacy/core_plugins/tests_bundle/find_source_files.js index a834072b258a3..eed88a5ecb8b0 100644 --- a/src/legacy/core_plugins/tests_bundle/find_source_files.js +++ b/src/legacy/core_plugins/tests_bundle/find_source_files.js @@ -27,7 +27,7 @@ import glob from 'glob-all'; const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { patterns = [].concat(patterns || []); - const matches = await fromNode(cb => { + const matches = await fromNode((cb) => { glob( patterns, { @@ -52,7 +52,7 @@ const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { return chain(matches) .flatten() .uniq() - .map(match => resolve(cwd, match)) + .map((match) => resolve(cwd, match)) .value(); }; diff --git a/src/legacy/core_plugins/tests_bundle/index.js b/src/legacy/core_plugins/tests_bundle/index.js index 3348096c0e2f1..431c161585fe0 100644 --- a/src/legacy/core_plugins/tests_bundle/index.js +++ b/src/legacy/core_plugins/tests_bundle/index.js @@ -30,9 +30,9 @@ import { replacePlaceholder } from '../../../optimize/public_path_placeholder'; import findSourceFiles from './find_source_files'; import { createTestEntryTemplate } from './tests_entry_template'; -export default kibana => { +export default (kibana) => { return new kibana.Plugin({ - config: Joi => { + config: (Joi) => { return Joi.object({ enabled: Joi.boolean().default(true), instrument: Joi.boolean().default(false), @@ -58,8 +58,8 @@ export default kibana => { const testingPluginIds = config.get('tests_bundle.pluginId'); if (testingPluginIds) { - testingPluginIds.split(',').forEach(pluginId => { - const plugin = plugins.find(plugin => plugin.id === pluginId); + testingPluginIds.split(',').forEach((pluginId) => { + const plugin = plugins.find((plugin) => plugin.id === pluginId); if (!plugin) { throw new Error('Invalid testingPluginId :: unknown plugin ' + pluginId); @@ -134,20 +134,17 @@ export default kibana => { async handler(_, h) { const cssFiles = await globby( testingPluginIds - ? testingPluginIds.split(',').map(id => `built_assets/css/plugins/${id}/**/*.css`) + ? testingPluginIds.split(',').map((id) => `built_assets/css/plugins/${id}/**/*.css`) : `built_assets/css/**/*.css`, { cwd: fromRoot('.'), absolute: true } ); const stream = replacePlaceholder( - new MultiStream(cssFiles.map(path => createReadStream(path))), + new MultiStream(cssFiles.map((path) => createReadStream(path))), '/built_assets/css/' ); - return h - .response(stream) - .code(200) - .type('text/css'); + return h.response(stream).code(200).type('text/css'); }, }); diff --git a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js index f075d8365c299..28c26f08621eb 100644 --- a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js +++ b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js @@ -19,7 +19,7 @@ import { Type } from '@kbn/config-schema'; import pkg from '../../../../package.json'; -export const createTestEntryTemplate = defaultUiSettings => bundle => ` +export const createTestEntryTemplate = (defaultUiSettings) => (bundle) => ` /** * Test entry file * diff --git a/src/legacy/core_plugins/timelion/public/app.js b/src/legacy/core_plugins/timelion/public/app.js index 6c1dc81dc341b..b5501982cec09 100644 --- a/src/legacy/core_plugins/timelion/public/app.js +++ b/src/legacy/core_plugins/timelion/public/app.js @@ -70,7 +70,7 @@ routes.when('/:id?', { reloadOnSearch: false, k7Breadcrumbs: ($injector, $route) => $injector.invoke($route.current.params.id ? getSavedSheetBreadcrumbs : getCreateBreadcrumbs), - badge: uiCapabilities => { + badge: (uiCapabilities) => { if (uiCapabilities.timelion.save) { return undefined; } @@ -86,10 +86,10 @@ routes.when('/:id?', { }; }, resolve: { - savedSheet: function(redirectWhenMissing, savedSheets, $route) { + savedSheet: function (redirectWhenMissing, savedSheets, $route) { return savedSheets .get($route.current.params.id) - .then(savedSheet => { + .then((savedSheet) => { if ($route.current.params.id) { npStart.core.chrome.recentlyAccessed.add( savedSheet.getFullPath(), @@ -110,7 +110,7 @@ routes.when('/:id?', { const location = 'Timelion'; -app.controller('timelion', function( +app.controller('timelion', function ( $http, $route, $routeParams, @@ -123,7 +123,7 @@ app.controller('timelion', function( // Keeping this at app scope allows us to keep the current page when the user // switches to say, the timepicker. $scope.page = config.get('timelion:showTutorial', true) ? 1 : 0; - $scope.setPage = page => ($scope.page = page); + $scope.setPage = (page) => ($scope.page = page); timefilter.enableAutoRefreshSelector(); timefilter.enableTimeRangeSelector(); @@ -136,7 +136,7 @@ app.controller('timelion', function( $scope.topNavMenu = getTopNavMenu(); - $timeout(function() { + $timeout(function () { if (config.get('timelion:showTutorial', true)) { $scope.toggleMenu('showHelp'); } @@ -163,7 +163,7 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.newSheetButtonAriaLabel', { defaultMessage: 'New Sheet', }), - run: function() { + run: function () { kbnUrl.change('/'); }, testId: 'timelionNewButton', @@ -177,7 +177,7 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.addChartButtonAriaLabel', { defaultMessage: 'Add a chart', }), - run: function() { + run: function () { $scope.$evalAsync(() => $scope.newCell()); }, testId: 'timelionAddChartButton', @@ -205,10 +205,10 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.deleteSheetButtonAriaLabel', { defaultMessage: 'Delete current sheet', }), - disableButton: function() { + disableButton: function () { return !savedSheet.id; }, - run: function() { + run: function () { const title = savedSheet.title; function doDelete() { savedSheet @@ -222,7 +222,7 @@ app.controller('timelion', function( ); kbnUrl.change('/'); }) - .catch(error => fatalError(error, location)); + .catch((error) => fatalError(error, location)); } const confirmModalOptions = { @@ -243,7 +243,7 @@ app.controller('timelion', function( }), confirmModalOptions ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { doDelete(); } @@ -310,12 +310,12 @@ app.controller('timelion', function( } let refresher; - const setRefreshData = function() { + const setRefreshData = function () { if (refresher) $timeout.cancel(refresher); const interval = timefilter.getRefreshInterval(); if (interval.value > 0 && !interval.pause) { function startRefresh() { - refresher = $timeout(function() { + refresher = $timeout(function () { if (!$scope.running) $scope.search(); startRefresh(); }, interval.value); @@ -324,7 +324,7 @@ app.controller('timelion', function( } }; - const init = function() { + const init = function () { $scope.running = false; $scope.search(); setRefreshData(); @@ -343,7 +343,7 @@ app.controller('timelion', function( savedSheet: savedSheet, state: $scope.state, search: $scope.search, - dontShowHelp: function() { + dontShowHelp: function () { config.set('timelion:showTutorial', false); $scope.setPage(0); $scope.closeMenus(); @@ -357,27 +357,27 @@ app.controller('timelion', function( showOptions: false, }; - $scope.toggleMenu = menuName => { + $scope.toggleMenu = (menuName) => { const curState = $scope.menus[menuName]; $scope.closeMenus(); $scope.menus[menuName] = !curState; }; $scope.closeMenus = () => { - _.forOwn($scope.menus, function(value, key) { + _.forOwn($scope.menus, function (value, key) { $scope.menus[key] = false; }); }; }; - $scope.onTimeUpdate = function({ dateRange }) { + $scope.onTimeUpdate = function ({ dateRange }) { $scope.model.timeRange = { ...dateRange, }; timefilter.setTime(dateRange); }; - $scope.onRefreshChange = function({ isPaused, refreshInterval }) { + $scope.onRefreshChange = function ({ isPaused, refreshInterval }) { $scope.model.refreshInterval = { pause: isPaused, value: refreshInterval, @@ -391,33 +391,33 @@ app.controller('timelion', function( }; $scope.$watch( - function() { + function () { return savedSheet.lastSavedTitle; }, - function(newTitle) { + function (newTitle) { docTitle.change(savedSheet.id ? newTitle : undefined); } ); - $scope.toggle = function(property) { + $scope.toggle = function (property) { $scope[property] = !$scope[property]; }; - $scope.newSheet = function() { + $scope.newSheet = function () { kbnUrl.change('/', {}); }; - $scope.newCell = function() { + $scope.newCell = function () { $scope.state.sheet.push(defaultExpression); $scope.state.selected = $scope.state.sheet.length - 1; $scope.safeSearch(); }; - $scope.setActiveCell = function(cell) { + $scope.setActiveCell = function (cell) { $scope.state.selected = cell; }; - $scope.search = function() { + $scope.search = function () { $scope.state.save(); $scope.running = true; @@ -438,23 +438,23 @@ app.controller('timelion', function( } ), }) - .then(resp => resp.data) - .catch(resp => { + .then((resp) => resp.data) + .catch((resp) => { throw resp.data; }); httpResult - .then(function(resp) { + .then(function (resp) { $scope.stats = resp.stats; $scope.sheet = resp.sheet; - _.each(resp.sheet, function(cell) { + _.each(resp.sheet, function (cell) { if (cell.exception) { $scope.state.selected = cell.plot; } }); $scope.running = false; }) - .catch(function(resp) { + .catch(function (resp) { $scope.sheet = []; $scope.running = false; @@ -475,7 +475,7 @@ app.controller('timelion', function( savedSheet.timelion_interval = $scope.state.interval; savedSheet.timelion_columns = $scope.state.columns; savedSheet.timelion_rows = $scope.state.rows; - savedSheet.save().then(function(id) { + savedSheet.save().then(function (id) { if (id) { toastNotifications.addSuccess({ title: i18n.translate('timelion.saveSheet.successNotificationText', { @@ -493,14 +493,14 @@ app.controller('timelion', function( } function saveExpression(title) { - savedVisualizations.get({ type: 'timelion' }).then(function(savedExpression) { + savedVisualizations.get({ type: 'timelion' }).then(function (savedExpression) { savedExpression.visState.params = { expression: $scope.state.sheet[$scope.state.selected], interval: $scope.state.interval, }; savedExpression.title = title; savedExpression.visState.title = title; - savedExpression.save().then(function(id) { + savedExpression.save().then(function (id) { if (id) { toastNotifications.addSuccess( i18n.translate('timelion.saveExpression.successNotificationText', { diff --git a/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js b/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js index 16d814a11cc7b..7e77027f750c6 100644 --- a/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js +++ b/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js @@ -25,6 +25,6 @@ const module = uiModules.get('apps/timelion', ['react']); import { TimelionHelpTabs } from './timelionhelp_tabs'; -module.directive('timelionHelpTabs', function(reactDirective) { +module.directive('timelionHelpTabs', function (reactDirective) { return reactDirective(wrapInI18nContext(TimelionHelpTabs), undefined, { restrict: 'E' }); }); diff --git a/src/legacy/core_plugins/timelion/public/directives/cells/cells.js b/src/legacy/core_plugins/timelion/public/directives/cells/cells.js index 3e59025e920b9..104af3b1043d6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/cells/cells.js +++ b/src/legacy/core_plugins/timelion/public/directives/cells/cells.js @@ -27,7 +27,7 @@ require('plugins/timelion/directives/timelion_grid'); const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); import html from './cells.html'; -app.directive('timelionCells', function() { +app.directive('timelionCells', function () { return { restrict: 'E', scope: { @@ -38,13 +38,13 @@ app.directive('timelionCells', function() { onSelect: '=', }, template: html, - link: function($scope) { - $scope.removeCell = function(index) { + link: function ($scope) { + $scope.removeCell = function (index) { _.pullAt($scope.state.sheet, index); $scope.onSearch(); }; - $scope.dropCell = function(item, partFrom, partTo, indexFrom, indexTo) { + $scope.dropCell = function (item, partFrom, partTo, indexFrom, indexTo) { $scope.onSelect(indexTo); move($scope.sheet, indexFrom, indexTo); }; diff --git a/src/legacy/core_plugins/timelion/public/directives/chart/chart.js b/src/legacy/core_plugins/timelion/public/directives/chart/chart.js index 332567c35b163..14bd3281a683e 100644 --- a/src/legacy/core_plugins/timelion/public/directives/chart/chart.js +++ b/src/legacy/core_plugins/timelion/public/directives/chart/chart.js @@ -28,7 +28,7 @@ export function Chart(timelionPanels) { interval: '=', // Required for formatting x-axis ticks rerenderTrigger: '=', }, - link: function($scope, $elem) { + link: function ($scope, $elem) { let panelScope = $scope.$new(true); function render() { diff --git a/src/legacy/core_plugins/timelion/public/directives/fixed_element.js b/src/legacy/core_plugins/timelion/public/directives/fixed_element.js index 71907c4014a29..e3a8b2184bb20 100644 --- a/src/legacy/core_plugins/timelion/public/directives/fixed_element.js +++ b/src/legacy/core_plugins/timelion/public/directives/fixed_element.js @@ -20,12 +20,12 @@ import $ from 'jquery'; const app = require('ui/modules').get('apps/timelion', []); -app.directive('fixedElementRoot', function() { +app.directive('fixedElementRoot', function () { return { restrict: 'A', - link: function($elem) { + link: function ($elem) { let fixedAt; - $(window).bind('scroll', function() { + $(window).bind('scroll', function () { const fixed = $('[fixed-element]', $elem); const body = $('[fixed-element-body]', $elem); const top = fixed.offset().top; diff --git a/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js b/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js index 325ed4d5c786e..5c4bd72ceb708 100644 --- a/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js +++ b/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js @@ -24,7 +24,7 @@ require('plugins/timelion/directives/timelion_grid'); const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); import html from './fullscreen.html'; -app.directive('timelionFullscreen', function() { +app.directive('timelionFullscreen', function () { return { restrict: 'E', scope: { diff --git a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js index ee729d2b427ad..08a347fbf7295 100644 --- a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js +++ b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js @@ -35,7 +35,7 @@ const module = uiModules.get('kibana'); module .directive('paginate', PaginateDirectiveProvider) .directive('paginateControls', PaginateControlsDirectiveProvider) - .directive('savedObjectFinder', function($location, kbnUrl, Private, config) { + .directive('savedObjectFinder', function ($location, kbnUrl, Private, config) { return { restrict: 'E', scope: { @@ -59,7 +59,7 @@ module }, template: savedObjectFinderTemplate, controllerAs: 'finder', - controller: function($scope, $element) { + controller: function ($scope, $element) { const self = this; // the text input element @@ -97,7 +97,7 @@ module * @param {Array} hits Array of saved finder object hits * @return {Array} Array sorted either ascending or descending */ - self.sortHits = function(hits) { + self.sortHits = function (hits) { self.isAscending = !self.isAscending; self.hits = self.isAscending ? _.sortBy(hits, 'title') @@ -109,7 +109,7 @@ module * hit should have a url in the UI, returns it if so * @return {string|null} - the url or nothing */ - self.makeUrl = function(hit) { + self.makeUrl = function (hit) { if ($scope.userMakeUrl) { return $scope.userMakeUrl(hit); } @@ -121,7 +121,7 @@ module return '#'; }; - self.preventClick = function($event) { + self.preventClick = function ($event) { $event.preventDefault(); }; @@ -129,7 +129,7 @@ module * Called when a hit object is clicked, can override the * url behavior if necessary. */ - self.onChoose = function(hit, $event) { + self.onChoose = function (hit, $event) { if ($scope.userOnChoose) { $scope.userOnChoose(hit, $event); } @@ -143,7 +143,7 @@ module kbnUrl.change(url.substr(1)); }; - $scope.$watch('filter', function(newFilter) { + $scope.$watch('filter', function (newFilter) { // ensure that the currentFilter changes from undefined to '' // which triggers currentFilter = newFilter || ''; @@ -152,7 +152,7 @@ module $scope.pageFirstItem = 0; $scope.pageLastItem = 0; - $scope.onPageChanged = page => { + $scope.onPageChanged = (page) => { $scope.pageFirstItem = page.firstItem; $scope.pageLastItem = page.lastItem; }; @@ -163,14 +163,12 @@ module index: -1, }; - self.getLabel = function() { - return _.words(self.properties.nouns) - .map(_.capitalize) - .join(' '); + self.getLabel = function () { + return _.words(self.properties.nouns).map(_.capitalize).join(' '); }; //key handler for the filter text box - self.filterKeyDown = function($event) { + self.filterKeyDown = function ($event) { switch (keyMap[$event.keyCode]) { case 'enter': if (self.hitCount !== 1) return; @@ -185,7 +183,7 @@ module }; //key handler for the list items - self.hitKeyDown = function($event, page, paginate) { + self.hitKeyDown = function ($event, page, paginate) { switch (keyMap[$event.keyCode]) { case 'tab': if (!self.selector.enabled) break; @@ -263,21 +261,21 @@ module } }; - self.hitBlur = function() { + self.hitBlur = function () { self.selector.index = -1; self.selector.enabled = false; }; - self.manageObjects = function(type) { + self.manageObjects = function (type) { $location.url('/management/kibana/objects?_a=' + rison.encode({ tab: type })); }; - self.hitCountNoun = function() { + self.hitCountNoun = function () { return (self.hitCount === 1 ? self.properties.noun : self.properties.nouns).toLowerCase(); }; function selectTopHit() { - setTimeout(function() { + setTimeout(function () { //triggering a focus event kicks off a new angular digest cycle. $list.find('a:first').focus(); }, 0); @@ -297,9 +295,9 @@ module prevSearch = filter; const isLabsEnabled = config.get('visualize:enableLabs'); - self.service.find(filter).then(function(hits) { + self.service.find(filter).then(function (hits) { hits.hits = hits.hits.filter( - hit => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' + (hit) => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' ); hits.total = hits.hits.length; diff --git a/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js b/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js index ac830092ce670..0671bc3e20123 100644 --- a/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js +++ b/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js @@ -20,7 +20,7 @@ import { uiModules } from 'ui/modules'; import saveObjectSaveAsCheckboxTemplate from './saved_object_save_as_checkbox.html'; -uiModules.get('kibana').directive('savedObjectSaveAsCheckBox', function() { +uiModules.get('kibana').directive('savedObjectSaveAsCheckBox', function () { return { restrict: 'E', template: saveObjectSaveAsCheckboxTemplate, diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js index 35ac883e5d99c..f3fd2fde8f2c5 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js @@ -67,7 +67,7 @@ export function TimelionExpInput($http, $timeout) { }, replace: true, template: timelionExpressionInputTemplate, - link: function(scope, elem) { + link: function (scope, elem) { const argValueSuggestions = npStart.plugins.visTypeTimelion.getArgValueSuggestions(); const expressionInput = elem.find('[data-expression-input]'); const functionReference = {}; @@ -76,7 +76,7 @@ export function TimelionExpInput($http, $timeout) { scope.suggestions = new Suggestions(); function init() { - $http.get('../api/timelion/functions').then(function(resp) { + $http.get('../api/timelion/functions').then(function (resp) { Object.assign(functionReference, { byName: _.indexBy(resp.data, 'name'), list: resp.data, @@ -193,7 +193,7 @@ export function TimelionExpInput($http, $timeout) { scope.suggestions.hide(); }; - scope.onKeyDownInput = e => { + scope.onKeyDownInput = (e) => { // If we've pressed any non-navigational keys, then the user has typed something and we // can exit early without doing any navigation. The keyup handler will pull up suggestions. if (!isNavigationalKey(e.keyCode)) { @@ -253,7 +253,7 @@ export function TimelionExpInput($http, $timeout) { } }; - scope.onKeyUpInput = e => { + scope.onKeyUpInput = (e) => { // If the user isn't navigating, then we should update the suggestions based on their input. if (!isNavigationalKey(e.keyCode)) { getSuggestions(); @@ -264,7 +264,7 @@ export function TimelionExpInput($http, $timeout) { getSuggestions(); }; - scope.onClickSuggestion = index => { + scope.onClickSuggestion = (index) => { insertSuggestionIntoExpression(index); }; diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js index 36577fcb00719..20edee82f9486 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js @@ -101,10 +101,10 @@ function getArgumentsHelp(functionHelp, functionArgs = []) { const argsHelp = functionHelp.chainable ? functionHelp.args.slice(1) : functionHelp.args.slice(0); // ignore arguments that are already provided in function declaration - const functionArgNames = functionArgs.map(arg => { + const functionArgNames = functionArgs.map((arg) => { return arg.name; }); - return argsHelp.filter(arg => { + return argsHelp.filter((arg) => { return !functionArgNames.includes(arg.name); }); } @@ -115,7 +115,7 @@ async function extractSuggestionsFromParsedResult( functionList, argValueSuggestions ) { - const activeFunc = result.functions.find(func => { + const activeFunc = result.functions.find((func) => { return cursorPosition >= func.location.min && cursorPosition < func.location.max; }); @@ -123,7 +123,7 @@ async function extractSuggestionsFromParsedResult( return; } - const functionHelp = functionList.find(func => { + const functionHelp = functionList.find((func) => { return func.name === activeFunc.function; }); @@ -135,7 +135,7 @@ async function extractSuggestionsFromParsedResult( } // return argument value suggestions when cursor is inside argument value - const activeArg = activeFunc.arguments.find(argument => { + const activeArg = activeFunc.arguments.find((argument) => { return inLocation(cursorPosition, argument.location); }); if ( @@ -159,7 +159,7 @@ async function extractSuggestionsFromParsedResult( partialInput ); } else { - const { suggestions: staticSuggestions } = functionHelp.args.find(arg => { + const { suggestions: staticSuggestions } = functionHelp.args.find((arg) => { return arg.name === activeArg.name; }); valueSuggestions = argValueSuggestions.getStaticSuggestionsForInput( @@ -176,7 +176,7 @@ async function extractSuggestionsFromParsedResult( // return argument suggestions const argsHelp = getArgumentsHelp(functionHelp, activeFunc.arguments); - const argumentSuggestions = argsHelp.filter(arg => { + const argumentSuggestions = argsHelp.filter((arg) => { if (_.get(activeArg, 'type') === 'namedArg') { return _.startsWith(arg.name, activeArg.name); } else if (activeArg) { @@ -222,7 +222,7 @@ export async function suggest( if (message.function) { // The user has start typing a function name, so we'll filter the list down to only // possible matches. - list = functionList.filter(func => _.startsWith(func.name, message.function)); + list = functionList.filter((func) => _.startsWith(func.name, message.function)); } else { // The user hasn't typed anything yet, so we'll just return the entire list. list = functionList; @@ -231,7 +231,7 @@ export async function suggest( } case 'incompleteArgument': { const { currentFunction: functionName, currentArgs: functionArgs } = message; - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); return { list: getArgumentsHelp(functionHelp, functionArgs), location: message.location, @@ -248,9 +248,9 @@ export async function suggest( functionArgs ); } else { - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); if (functionHelp) { - const argHelp = functionHelp.args.find(arg => arg.name === argName); + const argHelp = functionHelp.args.find((arg) => arg.name === argName); if (argHelp && argHelp.suggestions) { valueSuggestions = argHelp.suggestions; } diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js index a74cf19df29e3..8a35a72ed19e6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js @@ -21,34 +21,34 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../timelion_expression_suggestions'; -describe('Timelion expression suggestions directive', function() { +describe('Timelion expression suggestions directive', function () { let scope; let $compile; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $compile = $injector.get('$compile'); scope = $injector.get('$rootScope').$new(); }) ); - describe('attributes', function() { - describe('suggestions', function() { + describe('attributes', function () { + describe('suggestions', function () { let element = null; const template = ``; - beforeEach(function() { + beforeEach(function () { element = $compile(template)(scope); scope.$apply(() => { scope.list = [{ name: 'suggestion1' }, { name: 'suggestion2' }, { name: 'suggestion3' }]; }); }); - it('are rendered', function() { + it('are rendered', function () { expect(element.find('[data-test-subj="timelionSuggestionListItem"]').length).to.be( scope.list.length ); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js index c560b213731e3..5d8168a3197ca 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js @@ -31,9 +31,9 @@ export function TimelionExpressionSuggestions() { }, replace: true, template, - link: function(scope) { + link: function (scope) { // This will prevent the expression input from losing focus. - scope.onMouseDown = e => e.preventDefault(); + scope.onMouseDown = (e) => e.preventDefault(); }, }; } diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js b/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js index 3ef65f60d2ef4..256c35331d016 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js @@ -20,27 +20,27 @@ import $ from 'jquery'; const app = require('ui/modules').get('apps/timelion', []); -app.directive('timelionGrid', function() { +app.directive('timelionGrid', function () { return { restrict: 'A', scope: { timelionGridRows: '=', timelionGridColumns: '=', }, - link: function($scope, $elem) { + link: function ($scope, $elem) { function init() { setDimensions(); } - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { $(window).off('resize'); //remove the handler added earlier }); - $(window).resize(function() { + $(window).resize(function () { setDimensions(); }); - $scope.$watchMulti(['timelionGridColumns', 'timelionGridRows'], function() { + $scope.$watchMulti(['timelionGridColumns', 'timelionGridRows'], function () { setDimensions(); }); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js b/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js index e152ca165c810..25f3df13153ba 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js @@ -26,18 +26,18 @@ import '../../components/timelionhelp_tabs_directive'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionHelp', function($http) { +app.directive('timelionHelp', function ($http) { return { restrict: 'E', template, - controller: function($scope) { + controller: function ($scope) { $scope.functions = { list: [], details: null, }; $scope.activeTab = 'funcref'; - $scope.activateTab = function(tabName) { + $scope.activateTab = function (tabName) { $scope.activeTab = tabName; }; @@ -123,19 +123,19 @@ app.directive('timelionHelp', function($http) { } function getFunctions() { - return $http.get('../api/timelion/functions').then(function(resp) { + return $http.get('../api/timelion/functions').then(function (resp) { $scope.functions.list = resp.data; }); } - $scope.recheckElasticsearch = function() { + $scope.recheckElasticsearch = function () { $scope.es.valid = null; - checkElasticsearch().then(function(valid) { + checkElasticsearch().then(function (valid) { if (!valid) $scope.es.invalidCount++; }); }; function checkElasticsearch() { - return $http.get('../api/timelion/validate/es').then(function(resp) { + return $http.get('../api/timelion/validate/es').then(function (resp) { if (resp.data.ok) { $scope.es.valid = true; $scope.es.stats = { @@ -145,7 +145,7 @@ app.directive('timelionHelp', function($http) { }; } else { $scope.es.valid = false; - $scope.es.invalidReason = (function() { + $scope.es.invalidReason = (function () { try { const esResp = JSON.parse(resp.data.resp.response); return _.get(esResp, 'error.root_cause[0].reason'); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js b/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js index 4031916ce9708..577ee984e05c6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js @@ -29,7 +29,7 @@ export function TimelionInterval($timeout) { model: '=', }, template, - link: function($scope, $elem) { + link: function ($scope, $elem) { $scope.intervalOptions = ['auto', '1s', '1m', '1h', '1d', '1w', '1M', '1y', 'other']; $scope.intervalLabels = { auto: 'auto', @@ -43,7 +43,7 @@ export function TimelionInterval($timeout) { other: 'other', }; - $scope.$watch('model', function(newVal, oldVal) { + $scope.$watch('model', function (newVal, oldVal) { // Only run this on initialization if (newVal !== oldVal || oldVal == null) return; @@ -58,13 +58,13 @@ export function TimelionInterval($timeout) { } }); - $scope.$watch('interval', function(newVal, oldVal) { + $scope.$watch('interval', function (newVal, oldVal) { if (newVal === oldVal) return; if (newVal === 'other') { $scope.otherInterval = oldVal; $scope.model = $scope.otherInterval; - $timeout(function() { + $timeout(function () { $('input', $elem).select(); }, 0); } else { @@ -73,7 +73,7 @@ export function TimelionInterval($timeout) { } }); - $scope.$watch('otherInterval', function(newVal, oldVal) { + $scope.$watch('otherInterval', function (newVal, oldVal) { if (newVal === oldVal) return; $scope.model = newVal; }); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js index cf74026791ef1..d80770cbc2ae1 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import template from 'plugins/timelion/partials/load_sheet.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionLoad', function() { +app.directive('timelionLoad', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js index f41138fe5f382..067c831f09de5 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import template from 'plugins/timelion/partials/sheet_options.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionOptions', function() { +app.directive('timelionOptions', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js index 03d17d95b43d1..6dd44a10dc48c 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import saveTemplate from 'plugins/timelion/partials/save_sheet.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionSave', function() { +app.directive('timelionSave', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/lib/observe_resize.js b/src/legacy/core_plugins/timelion/public/lib/observe_resize.js index a75f2d7c6a713..62962e38c196e 100644 --- a/src/legacy/core_plugins/timelion/public/lib/observe_resize.js +++ b/src/legacy/core_plugins/timelion/public/lib/observe_resize.js @@ -17,7 +17,7 @@ * under the License. */ -export default function($elem, fn, frequency) { +export default function ($elem, fn, frequency) { frequency = frequency || 500; let currentHeight = $elem.height(); let currentWidth = $elem.width(); @@ -25,7 +25,7 @@ export default function($elem, fn, frequency) { let timeout; function checkLoop() { - timeout = setTimeout(function() { + timeout = setTimeout(function () { if (currentHeight !== $elem.height() || currentWidth !== $elem.width()) { currentHeight = $elem.height(); currentWidth = $elem.width(); @@ -38,7 +38,7 @@ export default function($elem, fn, frequency) { checkLoop(); - return function() { + return function () { clearTimeout(timeout); }; } diff --git a/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts b/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts index 34b389f5ff4ce..b1999eb4b483c 100644 --- a/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts +++ b/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts @@ -43,7 +43,7 @@ const DEBOUNCE_DELAY = 50; export function timechartFn(dependencies: TimelionVisualizationDependencies) { const { $rootScope, $compile, uiSettings } = dependencies; - return function() { + return function () { return { help: 'Draw a timeseries chart', render($scope: any, $elem: any) { @@ -157,7 +157,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { }); drawPlot($scope.chart); } - $scope.highlightSeries = _.debounce(function(id: any) { + $scope.highlightSeries = _.debounce(function (id: any) { if (highlightedSeries === id) { return; } @@ -172,50 +172,50 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { }); drawPlot($scope.chart); }, DEBOUNCE_DELAY); - $scope.focusSeries = function(id: any) { + $scope.focusSeries = function (id: any) { focusedSeries = id; $scope.highlightSeries(id); }; - $scope.toggleSeries = function(id: any) { + $scope.toggleSeries = function (id: any) { const series = $scope.chart[id]; series._hide = !series._hide; drawPlot($scope.chart); }; - const cancelResize = observeResize($elem, function() { + const cancelResize = observeResize($elem, function () { drawPlot($scope.chart); }); - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { cancelResize(); $elem.off('plothover'); $elem.off('plotselected'); $elem.off('mouseleave'); }); - $elem.on('plothover', function(event: any, pos: any, item: any) { + $elem.on('plothover', function (event: any, pos: any, item: any) { $rootScope.$broadcast('timelionPlotHover', event, pos, item); }); - $elem.on('plotselected', function(event: any, ranges: any) { + $elem.on('plotselected', function (event: any, ranges: any) { timefilter.setTime({ from: moment(ranges.xaxis.from), to: moment(ranges.xaxis.to), }); }); - $elem.on('mouseleave', function() { + $elem.on('mouseleave', function () { $rootScope.$broadcast('timelionPlotLeave'); }); - $scope.$on('timelionPlotHover', function(angularEvent: any, flotEvent: any, pos: any) { + $scope.$on('timelionPlotHover', function (angularEvent: any, flotEvent: any, pos: any) { if (!$scope.plot) return; $scope.plot.setCrosshair(pos); debouncedSetLegendNumbers(pos); }); - $scope.$on('timelionPlotLeave', function() { + $scope.$on('timelionPlotLeave', function () { if (!$scope.plot) return; $scope.plot.clearCrosshair(); clearLegendNumbers(); @@ -277,7 +277,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { if (legendCaption) { legendCaption.html(emptyCaption); } - _.each(legendValueNumbers, function(num) { + _.each(legendValueNumbers, function (num) { $(num).empty(); }); } @@ -293,10 +293,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { return; } - const title = _(plotConfig) - .map('_title') - .compact() - .last() as any; + const title = _(plotConfig).map('_title').compact().last() as any; $('.chart-top-title', $elem).text(title == null ? '' : title); const options = _.cloneDeep(defaultOptions) as any; @@ -313,7 +310,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { const format = getxAxisFormatter(interval); // Use moment to format ticks so we get timezone correction - options.xaxis.tickFormatter = function(val: any) { + options.xaxis.tickFormatter = function (val: any) { return moment(val).format(format); }; @@ -324,7 +321,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { $elem.width() / (format.length * tickLetterWidth + tickPadding) ); - const series = _.map(plotConfig, function(serie: any, index) { + const series = _.map(plotConfig, function (serie: any, index) { serie = _.cloneDeep( _.defaults(serie, { shadowSize: 0, @@ -349,7 +346,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { } if (serie._global) { - _.merge(options, serie._global, function(objVal, srcVal) { + _.merge(options, serie._global, function (objVal, srcVal) { // This is kind of gross, it means that you can't replace a global value with a null // best you can do is an empty string. Deal with it. if (objVal == null) return srcVal; @@ -383,7 +380,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { legendScope = $scope.$new(); // Used to toggle the series, and for displaying values on hover legendValueNumbers = canvasElem.find('.ngLegendValueNumber'); - _.each(canvasElem.find('.ngLegendValue'), function(elem) { + _.each(canvasElem.find('.ngLegendValue'), function (elem) { $compile(elem)(legendScope); }); diff --git a/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts b/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts index e7f431a178ea0..1fb29de83d3d7 100644 --- a/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts +++ b/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts @@ -40,7 +40,7 @@ export const savedSheetLoader = new SavedObjectLoader( savedObjectsClient, npStart.core.chrome ); -savedSheetLoader.urlFor = id => `#/${encodeURIComponent(id)}`; +savedSheetLoader.urlFor = (id) => `#/${encodeURIComponent(id)}`; // Customize loader properties since adding an 's' on type doesn't work for type 'timelion-sheet'. savedSheetLoader.loaderProperties = { name: 'timelion-sheet', diff --git a/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts b/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts index 8fadf223e1807..8122259f1c991 100644 --- a/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts +++ b/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts @@ -41,7 +41,7 @@ export const initTimelionLegacyModule = once((timelionPanels: Map uiModules .get('apps/timelion', []) - .controller('TimelionVisController', function($scope: any) { + .controller('TimelionVisController', function ($scope: any) { $scope.$on('timelionChartRendered', (event: any) => { event.stopPropagation(); $scope.renderComplete(); diff --git a/src/legacy/deprecation/__tests__/create_transform.js b/src/legacy/deprecation/__tests__/create_transform.js index 5e0616b729c06..d3838da5c3399 100644 --- a/src/legacy/deprecation/__tests__/create_transform.js +++ b/src/legacy/deprecation/__tests__/create_transform.js @@ -21,14 +21,14 @@ import { createTransform } from '../create_transform'; import expect from '@kbn/expect'; import sinon from 'sinon'; -describe('deprecation', function() { - describe('createTransform', function() { - it(`doesn't modify settings parameter`, function() { +describe('deprecation', function () { + describe('createTransform', function () { + it(`doesn't modify settings parameter`, function () { const settings = { original: true, }; const deprecations = [ - settings => { + (settings) => { settings.original = false; }, ]; @@ -36,22 +36,22 @@ describe('deprecation', function() { expect(settings.original).to.be(true); }); - it('calls single deprecation in array', function() { + it('calls single deprecation in array', function () { const deprecations = [sinon.spy()]; createTransform(deprecations)({}); expect(deprecations[0].calledOnce).to.be(true); }); - it('calls multiple deprecations in array', function() { + it('calls multiple deprecations in array', function () { const deprecations = [sinon.spy(), sinon.spy()]; createTransform(deprecations)({}); expect(deprecations[0].calledOnce).to.be(true); expect(deprecations[1].calledOnce).to.be(true); }); - it('passes log function to deprecation', function() { + it('passes log function to deprecation', function () { const deprecation = sinon.spy(); - const log = function() {}; + const log = function () {}; createTransform([deprecation])({}, log); expect(deprecation.args[0][1]).to.be(log); }); diff --git a/src/legacy/deprecation/create_transform.js b/src/legacy/deprecation/create_transform.js index 58418e3f50def..72e8e153ed819 100644 --- a/src/legacy/deprecation/create_transform.js +++ b/src/legacy/deprecation/create_transform.js @@ -24,7 +24,7 @@ export function createTransform(deprecations) { return (settings, log = noop) => { const result = clone(settings); - forEach(deprecations, deprecation => { + forEach(deprecations, (deprecation) => { deprecation(result, log); }); diff --git a/src/legacy/deprecation/deprecations/__tests__/rename.js b/src/legacy/deprecation/deprecations/__tests__/rename.js index 56b1c16d1607b..47c6b3257ff69 100644 --- a/src/legacy/deprecation/deprecations/__tests__/rename.js +++ b/src/legacy/deprecation/deprecations/__tests__/rename.js @@ -21,9 +21,9 @@ import expect from '@kbn/expect'; import { rename } from '../rename'; import sinon from 'sinon'; -describe('deprecation/deprecations', function() { - describe('rename', function() { - it('should rename simple property', function() { +describe('deprecation/deprecations', function () { + describe('rename', function () { + it('should rename simple property', function () { const value = 'value'; const settings = { before: value, @@ -34,7 +34,7 @@ describe('deprecation/deprecations', function() { expect(settings.after).to.be(value); }); - it('should rename nested property', function() { + it('should rename nested property', function () { const value = 'value'; const settings = { someObject: { @@ -47,7 +47,7 @@ describe('deprecation/deprecations', function() { expect(settings.someObject.after).to.be(value); }); - it('should rename property, even when the value is null', function() { + it('should rename property, even when the value is null', function () { const value = null; const settings = { before: value, @@ -58,7 +58,7 @@ describe('deprecation/deprecations', function() { expect(settings.after).to.be(null); }); - it(`shouldn't log when a rename doesn't occur`, function() { + it(`shouldn't log when a rename doesn't occur`, function () { const settings = { exists: true, }; @@ -68,7 +68,7 @@ describe('deprecation/deprecations', function() { expect(log.called).to.be(false); }); - it('should log when a rename does occur', function() { + it('should log when a rename does occur', function () { const settings = { exists: true, }; diff --git a/src/legacy/deprecation/deprecations/__tests__/unused.js b/src/legacy/deprecation/deprecations/__tests__/unused.js index 3f049a4ff678c..4907c2b166989 100644 --- a/src/legacy/deprecation/deprecations/__tests__/unused.js +++ b/src/legacy/deprecation/deprecations/__tests__/unused.js @@ -21,9 +21,9 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { unused } from '../unused'; -describe('deprecation/deprecations', function() { - describe('unused', function() { - it('should remove unused setting', function() { +describe('deprecation/deprecations', function () { + describe('unused', function () { + it('should remove unused setting', function () { const settings = { old: true, }; @@ -32,7 +32,7 @@ describe('deprecation/deprecations', function() { expect(settings.old).to.be(undefined); }); - it(`shouldn't remove used setting`, function() { + it(`shouldn't remove used setting`, function () { const value = 'value'; const settings = { new: value, @@ -42,7 +42,7 @@ describe('deprecation/deprecations', function() { expect(settings.new).to.be(value); }); - it('should remove unused setting, even when null', function() { + it('should remove unused setting, even when null', function () { const settings = { old: null, }; @@ -51,7 +51,7 @@ describe('deprecation/deprecations', function() { expect(settings.old).to.be(undefined); }); - it('should log when removing unused setting', function() { + it('should log when removing unused setting', function () { const settings = { old: true, }; @@ -63,7 +63,7 @@ describe('deprecation/deprecations', function() { expect(log.args[0][0]).to.match(/old.+deprecated/); }); - it(`shouldn't log when no setting is unused`, function() { + it(`shouldn't log when no setting is unused`, function () { const settings = { new: true, }; diff --git a/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js b/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js index 5544c0b483aa9..e6af23d69c549 100644 --- a/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js +++ b/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js @@ -29,7 +29,7 @@ const PLUGIN_FIXTURES = resolve(__dirname, 'fixtures/plugins'); const CONFLICT_FIXTURES = resolve(__dirname, 'fixtures/conflicts'); describe('plugin discovery', () => { - describe('findPluginSpecs()', function() { + describe('findPluginSpecs()', function () { this.timeout(10000); describe('spec$', () => { @@ -46,10 +46,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); it('finds all specs in scanDirs', async () => { @@ -64,10 +64,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); it('does not find disabled plugins', async () => { @@ -87,10 +87,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(2); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:two', 'foo']); }); it('dedupes duplicate packs', async () => { @@ -110,10 +110,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); describe('conflicting plugin spec ids', () => { @@ -137,9 +137,9 @@ describe('plugin discovery', () => { }); describe('packageJson$', () => { - const checkPackageJsons = packageJsons => { + const checkPackageJsons = (packageJsons) => { expect(packageJsons).to.have.length(2); - const package1 = packageJsons.find(packageJson => + const package1 = packageJsons.find((packageJson) => isEqual( { directoryPath: resolve(PLUGIN_FIXTURES, 'foo'), @@ -152,7 +152,7 @@ describe('plugin discovery', () => { ) ); expect(package1).to.be.an(Object); - const package2 = packageJsons.find(packageJson => + const package2 = packageJsons.find((packageJson) => isEqual( { directoryPath: resolve(PLUGIN_FIXTURES, 'bar'), diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js index 1ad8b1a277b84..fcbe3487463b7 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return [ // two plugins exported without ids will both inherit // the id of the pack and conflict diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js index bcc9619a517cf..0eef126f2255a 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return [ new kibana.Plugin({ id: 'bar:one', diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js index 2ccd8f438eec7..e43a1dcedb372 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/find_plugin_specs.js b/src/legacy/plugin_discovery/find_plugin_specs.js index efb9bf47ab71c..b97476bb456a5 100644 --- a/src/legacy/plugin_discovery/find_plugin_specs.js +++ b/src/legacy/plugin_discovery/find_plugin_specs.js @@ -52,7 +52,7 @@ function bufferAllResults(observable) { // buffer all results into a single array toArray(), // merge the array back into the stream when complete - mergeMap(array => array) + mergeMap((array) => array) ); } @@ -110,7 +110,7 @@ export function findPluginSpecs(settings, configToMutate) { // find plugin packs in configured paths/dirs const packageJson$ = config$.pipe( - mergeMap(config => + mergeMap((config) => Rx.merge( ...config.get('plugins.paths').map(createPackageJsonAtPath$), ...config.get('plugins.scanDirs').map(createPackageJsonsInDirectory$) @@ -123,19 +123,19 @@ export function findPluginSpecs(settings, configToMutate) { const pack$ = createPack$(packageJson$).pipe(share()); const extendConfig$ = config$.pipe( - mergeMap(config => + mergeMap((config) => pack$.pipe( // get the specs for each found plugin pack mergeMap(({ pack }) => (pack ? pack.getPluginSpecs() : [])), // make sure that none of the plugin specs have conflicting ids, fail // early if conflicts detected or merge the specs back into the stream toArray(), - mergeMap(allSpecs => { + mergeMap((allSpecs) => { for (const [id, specs] of groupSpecsById(allSpecs)) { if (specs.length > 1) { throw new Error( `Multiple plugins found with the id "${id}":\n${specs - .map(spec => ` - ${id} at ${spec.getPath()}`) + .map((spec) => ` - ${id} at ${spec.getPath()}`) .join('\n')}` ); } @@ -143,12 +143,12 @@ export function findPluginSpecs(settings, configToMutate) { return allSpecs; }), - mergeMap(async spec => { + mergeMap(async (spec) => { // extend the config service with this plugin spec and // collect its deprecations messages if some of its // settings are outdated const deprecations = []; - await extendConfigService(spec, config, settings, message => { + await extendConfigService(spec, config, settings, (message) => { deprecations.push({ spec, message }); }); @@ -173,7 +173,7 @@ export function findPluginSpecs(settings, configToMutate) { }), // determine which plugins are disabled before actually removing things from the config bufferAllResults, - tap(result => { + tap((result) => { for (const spec of result.disabledSpecs) { disableConfigExtension(spec, config); } @@ -186,46 +186,46 @@ export function findPluginSpecs(settings, configToMutate) { return { // package JSONs found when searching configure paths packageJson$: packageJson$.pipe( - mergeMap(result => (result.packageJson ? [result.packageJson] : [])) + mergeMap((result) => (result.packageJson ? [result.packageJson] : [])) ), // plugin packs found when searching configured paths - pack$: pack$.pipe(mergeMap(result => (result.pack ? [result.pack] : []))), + pack$: pack$.pipe(mergeMap((result) => (result.pack ? [result.pack] : []))), // errors caused by invalid directories of plugin directories invalidDirectoryError$: pack$.pipe( - mergeMap(result => (isInvalidDirectoryError(result.error) ? [result.error] : [])) + mergeMap((result) => (isInvalidDirectoryError(result.error) ? [result.error] : [])) ), // errors caused by directories that we expected to be plugin but were invalid invalidPackError$: pack$.pipe( - mergeMap(result => (isInvalidPackError(result.error) ? [result.error] : [])) + mergeMap((result) => (isInvalidPackError(result.error) ? [result.error] : [])) ), otherError$: pack$.pipe( - mergeMap(result => (isUnhandledError(result.error) ? [result.error] : [])) + mergeMap((result) => (isUnhandledError(result.error) ? [result.error] : [])) ), // { spec, message } objects produced when transforming deprecated // settings for a plugin spec - deprecation$: extendConfig$.pipe(mergeMap(result => result.deprecations)), + deprecation$: extendConfig$.pipe(mergeMap((result) => result.deprecations)), // the config service we extended with all of the plugin specs, // only emitted once it is fully extended by all extendedConfig$: extendConfig$.pipe( - mergeMap(result => result.config), + mergeMap((result) => result.config), filter(Boolean), last() ), // all enabled PluginSpec objects - spec$: extendConfig$.pipe(mergeMap(result => result.enabledSpecs)), + spec$: extendConfig$.pipe(mergeMap((result) => result.enabledSpecs)), // all disabled PluginSpec objects - disabledSpec$: extendConfig$.pipe(mergeMap(result => result.disabledSpecs)), + disabledSpec$: extendConfig$.pipe(mergeMap((result) => result.disabledSpecs)), // all PluginSpec objects that were disabled because their version was incompatible - invalidVersionSpec$: extendConfig$.pipe(mergeMap(result => result.invalidVersionSpecs)), + invalidVersionSpec$: extendConfig$.pipe(mergeMap((result) => result.invalidVersionSpecs)), }; } diff --git a/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js b/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js index 21f427a545b25..a74bfb872e99c 100644 --- a/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js +++ b/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js @@ -40,7 +40,7 @@ describe('plugin discovery/extend config service', () => { new Plugin({ configPrefix: 'foo.bar.baz', - config: Joi => + config: (Joi) => Joi.object({ enabled: Joi.boolean().default(true), test: Joi.string().default('bonk'), diff --git a/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js b/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js index e359b20be491d..78adb1e680e20 100644 --- a/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js +++ b/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js @@ -54,9 +54,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when no config provider', async () => { const schema = await getSchema(createPluginSpec()); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -65,9 +63,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when config returns falsy value', async () => { const schema = await getSchema(createPluginSpec(() => null)); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -76,9 +72,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when config promise resolves to falsy value', async () => { const schema = await getSchema(createPluginSpec(() => Promise.resolve(null))); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -89,9 +83,7 @@ describe('plugin discovery/schema', () => { it('returns schema with enabled: false', async () => { const schema = await getStubSchema(); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: false, }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js index d724b9add190c..b17bd69479ffa 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js @@ -39,9 +39,7 @@ describe('plugin discovery/create pack', () => { }, }, ]); - const results = await createPack$(packageJson$) - .pipe(toArray()) - .toPromise(); + const results = await createPack$(packageJson$).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['pack']); const { pack } = results[0]; @@ -58,31 +56,29 @@ describe('plugin discovery/create pack', () => { }, ]); - const results = await createPack$(packageJson$) - .pipe(toArray()) - .toPromise(); + const results = await createPack$(packageJson$).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['error']); const { error } = results[0]; await check(error); } it('default export is an object', () => - checkError(resolve(PLUGINS_DIR, 'exports_object'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_object'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('default export is an number', () => - checkError(resolve(PLUGINS_DIR, 'exports_number'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_number'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('default export is an string', () => - checkError(resolve(PLUGINS_DIR, 'exports_string'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_string'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('directory with code that fails when required', () => - checkError(resolve(PLUGINS_DIR, 'broken_code'), error => { + checkError(resolve(PLUGINS_DIR, 'broken_code'), (error) => { expect(error.message).to.contain("Cannot find module 'does-not-exist'"); })); }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js index 29bfa89e20399..bdb26504d6b6e 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js @@ -1,6 +1,6 @@ const brokenRequire = require('does-not-exist'); // eslint-disable-line -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js index 2ccd8f438eec7..e43a1dcedb372 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js index a8913c0be531b..fa1033180954e 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js @@ -28,9 +28,7 @@ import { PLUGINS_DIR, assertInvalidPackError, assertInvalidDirectoryError } from describe('plugin discovery/plugin_pack', () => { describe('createPackageJsonAtPath$()', () => { it('returns an observable', () => { - expect(createPackageJsonAtPath$()) - .to.have.property('subscribe') - .a('function'); + expect(createPackageJsonAtPath$()).to.have.property('subscribe').a('function'); }); it('gets the default provider from prebuilt babel modules', async () => { const results = await createPackageJsonAtPath$(resolve(PLUGINS_DIR, 'prebuilt')) @@ -44,46 +42,44 @@ describe('plugin discovery/plugin_pack', () => { }); describe('errors emitted as { error } results', () => { async function checkError(path, check) { - const results = await createPackageJsonAtPath$(path) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonAtPath$(path).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['error']); const { error } = results[0]; await check(error); } it('undefined path', () => - checkError(undefined, error => { + checkError(undefined, (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be a string'); })); it('relative path', () => - checkError('plugins/foo', error => { + checkError('plugins/foo', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('./relative path', () => - checkError('./plugins/foo', error => { + checkError('./plugins/foo', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('non-existent path', () => - checkError(resolve(PLUGINS_DIR, 'baz'), error => { + checkError(resolve(PLUGINS_DIR, 'baz'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must be a directory'); })); it('path to a file', () => - checkError(resolve(PLUGINS_DIR, 'index.js'), error => { + checkError(resolve(PLUGINS_DIR, 'index.js'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must be a directory'); })); it('directory without a package.json', () => - checkError(resolve(PLUGINS_DIR, 'lib'), error => { + checkError(resolve(PLUGINS_DIR, 'lib'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must have a package.json file'); })); it('directory with an invalid package.json', () => - checkError(resolve(PLUGINS_DIR, 'broken'), error => { + checkError(resolve(PLUGINS_DIR, 'broken'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must have a valid package.json file'); })); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js index ea42d4d876bb9..37cb4cc064da7 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js @@ -30,9 +30,7 @@ describe('plugin discovery/packs in directory', () => { describe('createPackageJsonsInDirectory$()', () => { describe('errors emitted as { error } results', () => { async function checkError(path, check) { - const results = await createPackageJsonsInDirectory$(path) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonsInDirectory$(path).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys('error'); const { error } = results[0]; @@ -40,42 +38,40 @@ describe('plugin discovery/packs in directory', () => { } it('undefined path', () => - checkError(undefined, error => { + checkError(undefined, (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be a string'); })); it('relative path', () => - checkError('my/plugins', error => { + checkError('my/plugins', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('./relative path', () => - checkError('./my/pluginsd', error => { + checkError('./my/pluginsd', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('non-existent path', () => - checkError(resolve(PLUGINS_DIR, 'notreal'), error => { + checkError(resolve(PLUGINS_DIR, 'notreal'), (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('no such file or directory'); })); it('path to a file', () => - checkError(resolve(PLUGINS_DIR, 'index.js'), error => { + checkError(resolve(PLUGINS_DIR, 'index.js'), (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('not a directory'); })); }); it('includes child errors for invalid packageJsons within a valid directory', async () => { - const results = await createPackageJsonsInDirectory$(PLUGINS_DIR) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonsInDirectory$(PLUGINS_DIR).pipe(toArray()).toPromise(); - const errors = results.map(result => result.error).filter(Boolean); + const errors = results.map((result) => result.error).filter(Boolean); - const packageJsons = results.map(result => result.packageJson).filter(Boolean); + const packageJsons = results.map((result) => result.packageJson).filter(Boolean); - packageJsons.forEach(pack => expect(pack).to.be.an(Object)); + packageJsons.forEach((pack) => expect(pack).to.be.an(Object)); // there should be one result for each item in PLUGINS_DIR expect(results).to.have.length(8); // three of the fixtures are errors of some sort diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js index 3ab08f138b184..769fcd74ce6fb 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js @@ -53,7 +53,7 @@ describe('plugin discovery/plugin pack', () => { pack.getPluginSpecs(); sinon.assert.calledOnce(provider); sinon.assert.calledWithExactly(provider, { - Plugin: sinon.match(Class => { + Plugin: sinon.match((Class) => { return Class.prototype instanceof PluginSpec; }, 'Subclass of PluginSpec'), }); @@ -96,7 +96,7 @@ describe('plugin discovery/plugin pack', () => { const otherPack = new PluginPack({ path: '/dev/null', pkg: { name: 'foo', version: 'kibana' }, - provider: api => { + provider: (api) => { OtherPluginSpecClass = api.Plugin; }, }); @@ -112,12 +112,12 @@ describe('plugin discovery/plugin pack', () => { new PluginPack({ provider: () => true }), new PluginPack({ provider: () => new Date() }), new PluginPack({ provider: () => /foo.*bar/ }), - new PluginPack({ provider: () => function() {} }), + new PluginPack({ provider: () => function () {} }), new PluginPack({ provider: () => new OtherPluginSpecClass({}) }), ]; for (const pack of badPacks) { - expect(() => pack.getPluginSpecs()).to.throwError(error => { + expect(() => pack.getPluginSpecs()).to.throwError((error) => { expect(error.message).to.contain('unexpected plugin export'); }); } diff --git a/src/legacy/plugin_discovery/plugin_pack/create_pack.js b/src/legacy/plugin_discovery/plugin_pack/create_pack.js index 62e7d9f1914bf..189c2ea324103 100644 --- a/src/legacy/plugin_discovery/plugin_pack/create_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/create_pack.js @@ -33,7 +33,7 @@ function createPack(packageJson) { return new PluginPack({ path: packageJson.directoryPath, pkg: packageJson.contents, provider }); } -export const createPack$ = packageJson$ => +export const createPack$ = (packageJson$) => packageJson$.pipe( map(({ error, packageJson }) => { if (error) { @@ -50,5 +50,5 @@ export const createPack$ = packageJson$ => }), // createPack can throw errors, and we want them to be represented // like the errors we consume from createPackageJsonAtPath/Directory - catchError(error => [{ error }]) + catchError((error) => [{ error }]) ); diff --git a/src/legacy/plugin_discovery/plugin_pack/lib/fs.js b/src/legacy/plugin_discovery/plugin_pack/lib/fs.js index e2af5fd7e5b10..2b531e314df52 100644 --- a/src/legacy/plugin_discovery/plugin_pack/lib/fs.js +++ b/src/legacy/plugin_discovery/plugin_pack/lib/fs.js @@ -38,7 +38,7 @@ function assertAbsolutePath(path) { async function statTest(path, test) { try { - const stats = await fcb(cb => stat(path, cb)); + const stats = await fcb((cb) => stat(path, cb)); return Boolean(test(stats)); } catch (error) { if (error.code !== 'ENOENT') { @@ -55,7 +55,7 @@ async function statTest(path, test) { */ export async function isDirectory(path) { assertAbsolutePath(path); - return await statTest(path, stat => stat.isDirectory()); + return await statTest(path, (stat) => stat.isDirectory()); } /** @@ -63,18 +63,18 @@ export async function isDirectory(path) { * @param {string} path * @return {Promise>} */ -export const createChildDirectory$ = path => +export const createChildDirectory$ = (path) => Rx.defer(() => { assertAbsolutePath(path); - return fcb(cb => readdir(path, cb)); + return fcb((cb) => readdir(path, cb)); }).pipe( - catchError(error => { + catchError((error) => { throw createInvalidDirectoryError(error, path); }), mergeAll(), - filter(name => !name.startsWith('.')), - map(name => resolve(path, name)), - mergeMap(async absolute => { + filter((name) => !name.startsWith('.')), + map((name) => resolve(path, name)), + mergeMap(async (absolute) => { if (await isDirectory(absolute)) { return [absolute]; } else { diff --git a/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js b/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js index aa21d8242f3fa..18629ef3ea802 100644 --- a/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js +++ b/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js @@ -52,11 +52,11 @@ async function createPackageJsonAtPath(path) { }; } -export const createPackageJsonAtPath$ = path => +export const createPackageJsonAtPath$ = (path) => // If plugin directory contains manifest file, we should skip it since it // should have been handled by the core plugin system already. Rx.defer(() => isNewPlatformPlugin(path)).pipe( - mergeMap(isNewPlatformPlugin => (isNewPlatformPlugin ? [] : createPackageJsonAtPath(path))), - map(packageJson => ({ packageJson })), - catchError(error => [{ error }]) + mergeMap((isNewPlatformPlugin) => (isNewPlatformPlugin ? [] : createPackageJsonAtPath(path))), + map((packageJson) => ({ packageJson })), + catchError((error) => [{ error }]) ); diff --git a/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js b/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js index 2873f01d90c16..5f0977f4829b8 100644 --- a/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js +++ b/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js @@ -36,10 +36,10 @@ import { createPackageJsonAtPath$ } from './package_json_at_path'; * @param {String} path * @return {Array<{pack}|{error}>} */ -export const createPackageJsonsInDirectory$ = path => +export const createPackageJsonsInDirectory$ = (path) => createChildDirectory$(path).pipe( mergeMap(createPackageJsonAtPath$), - catchError(error => { + catchError((error) => { // this error is produced by createChildDirectory$() when the path // is invalid, we return them as an error result similar to how // createPackAtPath$ works when it finds invalid packs in a directory diff --git a/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js b/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js index 0734a85d587a9..1baf3d104ca84 100644 --- a/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js @@ -63,7 +63,7 @@ export class PluginPack { const specs = [].concat(result === undefined ? [] : result); // verify that all specs are instances of passed "Plugin" class - specs.forEach(spec => { + specs.forEach((spec) => { if (!(spec instanceof api.Plugin)) { throw new TypeError('unexpected plugin export ' + inspect(spec)); } diff --git a/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js b/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js index 3649de165f0aa..02675f0bd60f8 100644 --- a/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js +++ b/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js @@ -36,21 +36,21 @@ describe('plugin discovery/plugin spec', () => { describe('validation', () => { it('throws if missing spec.id AND Pack has no name', () => { const pack = new PluginPack({ pkg: {} }); - expect(() => new PluginSpec(pack, {})).to.throwError(error => { + expect(() => new PluginSpec(pack, {})).to.throwError((error) => { expect(error.message).to.contain('Unable to determine plugin id'); }); }); it('throws if missing spec.kibanaVersion AND Pack has no version', () => { const pack = new PluginPack({ pkg: { name: 'foo' } }); - expect(() => new PluginSpec(pack, {})).to.throwError(error => { + expect(() => new PluginSpec(pack, {})).to.throwError((error) => { expect(error.message).to.contain('Unable to determine plugin version'); }); }); it('throws if spec.require is defined, but not an array', () => { function assert(require) { - expect(() => new PluginSpec(fooPack, { require })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { require })).to.throwError((error) => { expect(error.message).to.contain('"plugin.require" must be an array of plugin ids'); }); } @@ -65,7 +65,7 @@ describe('plugin discovery/plugin spec', () => { it('throws if spec.publicDir is truthy and not a string', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain( `The "path" argument must be of type string. Received type ${typeof publicDir}` ); @@ -73,14 +73,14 @@ describe('plugin discovery/plugin spec', () => { } assert(1); - assert(function() {}); + assert(function () {}); assert([]); assert(/a.*b/); }); it('throws if spec.publicDir is not an absolute path', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain('plugin.publicDir must be an absolute path'); }); } @@ -91,7 +91,7 @@ describe('plugin discovery/plugin spec', () => { it('throws if spec.publicDir basename is not `public`', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain('must end with a "public" directory'); }); } @@ -171,13 +171,13 @@ describe('plugin discovery/plugin spec', () => { it('throws if not passed a config service', () => { const { spec } = setup('a.b.c', () => true); - expect(() => spec.isEnabled()).to.throwError(error => { + expect(() => spec.isEnabled()).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled(null)).to.throwError(error => { + expect(() => spec.isEnabled(null)).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled({ get: () => {} })).to.throwError(error => { + expect(() => spec.isEnabled({ get: () => {} })).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); }); @@ -214,13 +214,13 @@ describe('plugin discovery/plugin spec', () => { it('throws if not passed a config service', () => { const { spec } = setup(() => true); - expect(() => spec.isEnabled()).to.throwError(error => { + expect(() => spec.isEnabled()).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled(null)).to.throwError(error => { + expect(() => spec.isEnabled(null)).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled({ get: () => {} })).to.throwError(error => { + expect(() => spec.isEnabled({ get: () => {} })).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); }); diff --git a/src/legacy/server/capabilities/capabilities_mixin.ts b/src/legacy/server/capabilities/capabilities_mixin.ts index 23a0c35414ae6..1f8c869f17f66 100644 --- a/src/legacy/server/capabilities/capabilities_mixin.ts +++ b/src/legacy/server/capabilities/capabilities_mixin.ts @@ -24,12 +24,12 @@ export async function capabilitiesMixin(kbnServer: KbnServer, server: Server) { const registerLegacyCapabilities = async () => { const capabilitiesList = await Promise.all( kbnServer.pluginSpecs - .map(spec => spec.getUiCapabilitiesProvider()) - .filter(provider => !!provider) - .map(provider => provider(server)) + .map((spec) => spec.getUiCapabilitiesProvider()) + .filter((provider) => !!provider) + .map((provider) => provider(server)) ); - capabilitiesList.forEach(capabilities => { + capabilitiesList.forEach((capabilities) => { kbnServer.newPlatform.setup.core.capabilities.registerProvider(() => capabilities); }); }; diff --git a/src/legacy/server/config/complete.js b/src/legacy/server/config/complete.js index 2cdd8c32bcbeb..7dbb3a722e38f 100644 --- a/src/legacy/server/config/complete.js +++ b/src/legacy/server/config/complete.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(kbnServer, server) { - server.decorate('server', 'config', function() { +export default function (kbnServer, server) { + server.decorate('server', 'config', function () { return kbnServer.config; }); } diff --git a/src/legacy/server/config/complete.test.js b/src/legacy/server/config/complete.test.js index 122c60e103b50..e5484693ae55f 100644 --- a/src/legacy/server/config/complete.test.js +++ b/src/legacy/server/config/complete.test.js @@ -20,7 +20,7 @@ import completeMixin from './complete'; import sinon from 'sinon'; -describe('server/config completeMixin()', function() { +describe('server/config completeMixin()', function () { const sandbox = sinon.createSandbox(); afterEach(() => sandbox.restore()); diff --git a/src/legacy/server/config/config.js b/src/legacy/server/config/config.js index b186071edeaf7..d32ec29e6d701 100644 --- a/src/legacy/server/config/config.js +++ b/src/legacy/server/config/config.js @@ -47,7 +47,7 @@ export class Config { } if (!key) { - return _.each(extension._inner.children, child => { + return _.each(extension._inner.children, (child) => { this.extendSchema(child.schema, _.get(settings, child.key), child.key); }); } @@ -193,9 +193,7 @@ export class Config { getSchema() { if (!this[schema]) { this[schema] = (function convertToSchema(children) { - let schema = Joi.object() - .keys({}) - .default(); + let schema = Joi.object().keys({}).default(); for (const key of Object.keys(children)) { const child = children[key]; diff --git a/src/legacy/server/config/config.test.js b/src/legacy/server/config/config.test.js index e71cd9f0e6ac9..d7dec19b7ca6e 100644 --- a/src/legacy/server/config/config.test.js +++ b/src/legacy/server/config/config.test.js @@ -56,55 +56,55 @@ const schema = Joi.object({ }).default(), }).default(); -describe('lib/config/config', function() { - describe('class Config()', function() { - describe('constructor', function() { - it('should not allow any config if the schema is not passed', function() { +describe('lib/config/config', function () { + describe('class Config()', function () { + describe('constructor', function () { + it('should not allow any config if the schema is not passed', function () { const config = new Config(); - const run = function() { + const run = function () { config.set('something.enable', true); }; expect(run).toThrow(); }); - it('should allow keys in the schema', function() { + it('should allow keys in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('test.client.host', 'http://localhost'); }; expect(run).not.toThrow(); }); - it('should not allow keys not in the schema', function() { + it('should not allow keys not in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('paramNotDefinedInTheSchema', true); }; expect(run).toThrow(); }); - it('should not allow child keys not in the schema', function() { + it('should not allow child keys not in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('test.client.paramNotDefinedInTheSchema', true); }; expect(run).toThrow(); }); - it('should set defaults', function() { + it('should set defaults', function () { const config = new Config(schema); expect(config.get('test.enable')).toBe(true); expect(config.get('test.client.type')).toBe('datastore'); }); }); - describe('#resetTo(object)', function() { + describe('#resetTo(object)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should reset the config object with new values', function() { + it('should reset the config object with new values', function () { config.set(data); const newData = config.get(); newData.test.enable = false; @@ -113,52 +113,52 @@ describe('lib/config/config', function() { }); }); - describe('#has(key)', function() { + describe('#has(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should return true for fields that exist in the schema', function() { + it('should return true for fields that exist in the schema', function () { expect(config.has('test.undefValue')).toBe(true); }); - it('should return true for partial objects that exist in the schema', function() { + it('should return true for partial objects that exist in the schema', function () { expect(config.has('test.client')).toBe(true); }); - it('should return false for fields that do not exist in the schema', function() { + it('should return false for fields that do not exist in the schema', function () { expect(config.has('test.client.pool')).toBe(false); }); }); - describe('#set(key, value)', function() { + describe('#set(key, value)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should use a key and value to set a config value', function() { + it('should use a key and value to set a config value', function () { config.set('test.enable', false); expect(config.get('test.enable')).toBe(false); }); - it('should use an object to set config values', function() { + it('should use an object to set config values', function () { const hosts = ['host-01', 'host-02']; config.set({ test: { enable: false, hosts: hosts } }); expect(config.get('test.enable')).toBe(false); expect(config.get('test.hosts')).toEqual(hosts); }); - it('should use a flatten object to set config values', function() { + it('should use a flatten object to set config values', function () { const hosts = ['host-01', 'host-02']; config.set({ 'test.enable': false, 'test.hosts': hosts }); expect(config.get('test.enable')).toBe(false); expect(config.get('test.hosts')).toEqual(hosts); }); - it('should override values with just the values present', function() { + it('should override values with just the values present', function () { const newData = _.cloneDeep(data); config.set(data); newData.test.enable = false; @@ -166,10 +166,10 @@ describe('lib/config/config', function() { expect(config.get()).toEqual(newData); }); - it('should thow an exception when setting a value with the wrong type', function(done) { + it('should thow an exception when setting a value with the wrong type', function (done) { expect.assertions(4); - const run = function() { + const run = function () { config.set('test.enable', 'something'); }; @@ -189,37 +189,37 @@ describe('lib/config/config', function() { }); }); - describe('#get(key)', function() { + describe('#get(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); config.set(data); }); - it('should return the whole config object when called without a key', function() { + it('should return the whole config object when called without a key', function () { const newData = _.cloneDeep(data); newData.test.enable = true; expect(config.get()).toEqual(newData); }); - it('should return the value using dot notation', function() { + it('should return the value using dot notation', function () { expect(config.get('test.enable')).toBe(true); }); - it('should return the clone of partial object using dot notation', function() { + it('should return the clone of partial object using dot notation', function () { expect(config.get('test.client')).not.toBe(data.test.client); expect(config.get('test.client')).toEqual(data.test.client); }); - it('should throw exception for unknown config values', function() { - const run = function() { + it('should throw exception for unknown config values', function () { + const run = function () { config.get('test.does.not.exist'); }; expect(run).toThrowError(/Unknown config key: test.does.not.exist/); }); - it('should not throw exception for undefined known config values', function() { + it('should not throw exception for undefined known config values', function () { const run = function getUndefValue() { config.get('test.undefValue'); }; @@ -227,56 +227,54 @@ describe('lib/config/config', function() { }); }); - describe('#getDefault(key)', function() { + describe('#getDefault(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); config.set(data); }); - describe('dot notation key', function() { - it('should return undefined if there is no default', function() { + describe('dot notation key', function () { + it('should return undefined if there is no default', function () { const hostDefault = config.getDefault('test.client.host'); expect(hostDefault).toBeUndefined(); }); - it('should return default if specified', function() { + it('should return default if specified', function () { const typeDefault = config.getDefault('test.client.type'); expect(typeDefault).toBe('datastore'); }); - it('should throw exception for unknown key', function() { + it('should throw exception for unknown key', function () { expect(() => { config.getDefault('foo.bar'); }).toThrowErrorMatchingSnapshot(); }); }); - describe('array key', function() { - it('should return undefined if there is no default', function() { + describe('array key', function () { + it('should return undefined if there is no default', function () { const hostDefault = config.getDefault(['test', 'client', 'host']); expect(hostDefault).toBeUndefined(); }); - it('should return default if specified', function() { + it('should return default if specified', function () { const typeDefault = config.getDefault(['test', 'client', 'type']); expect(typeDefault).toBe('datastore'); }); - it('should throw exception for unknown key', function() { + it('should throw exception for unknown key', function () { expect(() => { config.getDefault(['foo', 'bar']); }).toThrowErrorMatchingSnapshot(); }); }); - it('object schema with no default should return default value for property', function() { + it('object schema with no default should return default value for property', function () { const noDefaultSchema = Joi.object() .keys({ - foo: Joi.array() - .items(Joi.string().min(1)) - .default(['bar']), + foo: Joi.array().items(Joi.string().min(1)).default(['bar']), }) .required(); @@ -289,12 +287,10 @@ describe('lib/config/config', function() { expect(fooDefault).toEqual(['bar']); }); - it('should return clone of the default', function() { + it('should return clone of the default', function () { const schemaWithArrayDefault = Joi.object() .keys({ - foo: Joi.array() - .items(Joi.string().min(1)) - .default(['bar']), + foo: Joi.array().items(Joi.string().min(1)).default(['bar']), }) .default(); @@ -308,19 +304,19 @@ describe('lib/config/config', function() { }); }); - describe('#extendSchema(key, schema)', function() { + describe('#extendSchema(key, schema)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should allow you to extend the schema at the top level', function() { + it('should allow you to extend the schema at the top level', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema(newSchema, {}, 'myTest'); expect(config.get('myTest.test')).toBe(true); }); - it('should allow you to extend the schema with a prefix', function() { + it('should allow you to extend the schema with a prefix', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema(newSchema, {}, 'prefix.myTest'); expect(config.get('prefix')).toEqual({ myTest: { test: true } }); @@ -328,17 +324,17 @@ describe('lib/config/config', function() { expect(config.get('prefix.myTest.test')).toBe(true); }); - it('should NOT allow you to extend the schema if something else is there', function() { + it('should NOT allow you to extend the schema if something else is there', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); - const run = function() { + const run = function () { config.extendSchema('test', newSchema); }; expect(run).toThrow(); }); }); - describe('#removeSchema(key)', function() { - it('should completely remove the key', function() { + describe('#removeSchema(key)', function () { + it('should completely remove the key', function () { const config = new Config( Joi.object().keys({ a: Joi.number().default(1), @@ -350,7 +346,7 @@ describe('lib/config/config', function() { expect(() => config.get('a')).toThrowError('Unknown config key'); }); - it('only removes existing keys', function() { + it('only removes existing keys', function () { const config = new Config(Joi.object()); expect(() => config.removeSchema('b')).toThrowError('Unknown schema'); diff --git a/src/legacy/server/config/override.test.ts b/src/legacy/server/config/override.test.ts index 4e21a88e79e61..31b01004f72ad 100644 --- a/src/legacy/server/config/override.test.ts +++ b/src/legacy/server/config/override.test.ts @@ -19,8 +19,8 @@ import { override } from './override'; -describe('override(target, source)', function() { - it('should override the values form source to target', function() { +describe('override(target, source)', function () { + it('should override the values form source to target', function () { const target = { test: { enable: true, diff --git a/src/legacy/server/config/schema.js b/src/legacy/server/config/schema.js index 87db8c184ad36..53f5185442688 100644 --- a/src/legacy/server/config/schema.js +++ b/src/legacy/server/config/schema.js @@ -77,9 +77,7 @@ export default () => .default('') .allow('') .regex(/(^$|^\/.*[^\/]$)/, `start with a slash, don't end with one`), - host: Joi.string() - .hostname() - .default('localhost'), + host: Joi.string().hostname().default('localhost'), port: Joi.number().default(5601), rewriteBasePath: Joi.boolean().when('basePath', { is: '', @@ -139,14 +137,8 @@ export default () => .less(1073741825) // 10MB .default(10485760), - keepFiles: Joi.number() - .greater(2) - .less(1024) - .default(7), - pollingInterval: Joi.number() - .greater(5000) - .less(3600000) - .default(10000), + keepFiles: Joi.number().greater(2).less(1024).default(7), + pollingInterval: Joi.number().greater(5000).less(3600000).default(10000), usePolling: Joi.boolean().default(false), }) .default(), @@ -158,12 +150,8 @@ export default () => }).default(), plugins: Joi.object({ - paths: Joi.array() - .items(Joi.string()) - .default([]), - scanDirs: Joi.array() - .items(Joi.string()) - .default([]), + paths: Joi.array().items(Joi.string()).default([]), + scanDirs: Joi.array().items(Joi.string()).default([]), initialize: Joi.boolean().default(true), }).default(), @@ -180,9 +168,7 @@ export default () => viewCaching: Joi.boolean().default(Joi.ref('$prod')), watch: Joi.boolean().default(false), watchPort: Joi.number().default(5602), - watchHost: Joi.string() - .hostname() - .default('localhost'), + watchHost: Joi.string().hostname().default('localhost'), watchPrebuild: Joi.boolean().default(false), watchProxyTimeout: Joi.number().default(10 * 60000), useBundleCache: Joi.boolean().default(!!process.env.CODE_COVERAGE ? true : Joi.ref('$prod')), @@ -207,25 +193,14 @@ export default () => url: Joi.string(), options: Joi.object({ attribution: Joi.string(), - minZoom: Joi.number() - .min(0, 'Must be 0 or higher') - .default(0), + minZoom: Joi.number().min(0, 'Must be 0 or higher').default(0), maxZoom: Joi.number().default(10), tileSize: Joi.number(), - subdomains: Joi.array() - .items(Joi.string()) - .single(), + subdomains: Joi.array().items(Joi.string()).single(), errorTileUrl: Joi.string().uri(), tms: Joi.boolean(), reuseTiles: Joi.boolean(), - bounds: Joi.array() - .items( - Joi.array() - .items(Joi.number()) - .min(2) - .required() - ) - .min(2), + bounds: Joi.array().items(Joi.array().items(Joi.number()).min(2).required()).min(2), default: Joi.boolean(), }).default({ default: true, @@ -259,9 +234,7 @@ export default () => ) .default([]), }).default(), - manifestServiceUrl: Joi.string() - .default('') - .allow(''), + manifestServiceUrl: Joi.string().default('').allow(''), emsFileApiUrl: Joi.string().default('https://vector.maps.elastic.co'), emsTileApiUrl: Joi.string().default('https://tiles.maps.elastic.co'), emsLandingPageUrl: Joi.string().default('https://maps.elastic.co/v7.8'), diff --git a/src/legacy/server/config/schema.test.js b/src/legacy/server/config/schema.test.js index 03d2fe53c2ce7..aa09c15e9324d 100644 --- a/src/legacy/server/config/schema.test.js +++ b/src/legacy/server/config/schema.test.js @@ -20,7 +20,7 @@ import schemaProvider from './schema'; import Joi from 'joi'; -describe('Config schema', function() { +describe('Config schema', function () { let schema; beforeEach(async () => (schema = await schemaProvider())); @@ -28,38 +28,38 @@ describe('Config schema', function() { return Joi.validate(data, schema, options); } - describe('server', function() { - it('everything is optional', function() { + describe('server', function () { + it('everything is optional', function () { const { error } = validate({}); expect(error).toBe(null); }); - describe('basePath', function() { - it('accepts empty strings', function() { + describe('basePath', function () { + it('accepts empty strings', function () { const { error, value } = validate({ server: { basePath: '' } }); expect(error).toBe(null); expect(value.server.basePath).toBe(''); }); - it('accepts strings with leading slashes', function() { + it('accepts strings with leading slashes', function () { const { error, value } = validate({ server: { basePath: '/path' } }); expect(error).toBe(null); expect(value.server.basePath).toBe('/path'); }); - it('rejects strings with trailing slashes', function() { + it('rejects strings with trailing slashes', function () { const { error } = validate({ server: { basePath: '/path/' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'basePath']); }); - it('rejects strings without leading slashes', function() { + it('rejects strings without leading slashes', function () { const { error } = validate({ server: { basePath: 'path' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'basePath']); }); - it('rejects things that are not strings', function() { + it('rejects things that are not strings', function () { for (const value of [1, true, {}, [], /foo/]) { const { error } = validate({ server: { basePath: value } }); expect(error).toHaveProperty('details'); @@ -68,32 +68,32 @@ describe('Config schema', function() { }); }); - describe('rewriteBasePath', function() { + describe('rewriteBasePath', function () { it('defaults to false', () => { const { error, value } = validate({}); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(false); }); - it('accepts false', function() { + it('accepts false', function () { const { error, value } = validate({ server: { rewriteBasePath: false } }); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(false); }); - it('accepts true if basePath set', function() { + it('accepts true if basePath set', function () { const { error, value } = validate({ server: { basePath: '/foo', rewriteBasePath: true } }); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(true); }); - it('rejects true if basePath not set', function() { + it('rejects true if basePath not set', function () { const { error } = validate({ server: { rewriteBasePath: true } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'rewriteBasePath']); }); - it('rejects strings', function() { + it('rejects strings', function () { const { error } = validate({ server: { rewriteBasePath: 'foo' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'rewriteBasePath']); diff --git a/src/legacy/server/http/index.js b/src/legacy/server/http/index.js index 3649987d89b9a..2d62d12dfd9f3 100644 --- a/src/legacy/server/http/index.js +++ b/src/legacy/server/http/index.js @@ -24,7 +24,7 @@ import Boom from 'boom'; import { registerHapiPlugins } from './register_hapi_plugins'; import { setupBasePathProvider } from './setup_base_path_provider'; -export default async function(kbnServer, server, config) { +export default async function (kbnServer, server, config) { server = kbnServer.server; setupBasePathProvider(kbnServer); @@ -32,7 +32,7 @@ export default async function(kbnServer, server, config) { await registerHapiPlugins(server); // helper for creating view managers for servers - server.decorate('server', 'setupViews', function(path, engines) { + server.decorate('server', 'setupViews', function (path, engines) { this.views({ path: path, isCached: config.get('optimize.viewCaching'), @@ -43,7 +43,7 @@ export default async function(kbnServer, server, config) { server.route({ method: 'GET', path: '/{p*}', - handler: function(req, h) { + handler: function (req, h) { const path = req.path; if (path === '/' || path.charAt(path.length - 1) !== '/') { throw Boom.notFound(); diff --git a/src/legacy/server/http/integration_tests/max_payload_size.test.js b/src/legacy/server/http/integration_tests/max_payload_size.test.js index 7f22f83c78f0e..a019220ca7a2a 100644 --- a/src/legacy/server/http/integration_tests/max_payload_size.test.js +++ b/src/legacy/server/http/integration_tests/max_payload_size.test.js @@ -30,7 +30,7 @@ beforeAll(async () => { path: '/payload_size_check/test/route', method: 'POST', config: { payload: { maxBytes: 200 } }, - handler: req => req.payload.data.slice(0, 5), + handler: (req) => req.payload.data.slice(0, 5), }); }, 30000); @@ -40,9 +40,7 @@ test('accepts payload with a size larger than default but smaller than route con await kbnTestServer.request .post(root, '/payload_size_check/test/route') .send({ - data: Array(150) - .fill('+') - .join(''), + data: Array(150).fill('+').join(''), }) .expect(200, '+++++'); }); @@ -51,9 +49,7 @@ test('fails with 413 if payload size is larger than default and route config all await kbnTestServer.request .post(root, '/payload_size_check/test/route') .send({ - data: Array(250) - .fill('+') - .join(''), + data: Array(250).fill('+').join(''), }) .expect(413, { statusCode: 413, diff --git a/src/legacy/server/http/setup_base_path_provider.js b/src/legacy/server/http/setup_base_path_provider.js index 07917ebd63895..6949d7e2eebd0 100644 --- a/src/legacy/server/http/setup_base_path_provider.js +++ b/src/legacy/server/http/setup_base_path_provider.js @@ -18,7 +18,7 @@ */ export function setupBasePathProvider(kbnServer) { - kbnServer.server.decorate('request', 'getBasePath', function() { + kbnServer.server.decorate('request', 'getBasePath', function () { const request = this; return kbnServer.newPlatform.setup.core.http.basePath.get(request); }); diff --git a/src/legacy/server/i18n/get_translations_path.ts b/src/legacy/server/i18n/get_translations_path.ts index ac7c61dcf8543..a2a292e2278be 100644 --- a/src/legacy/server/i18n/get_translations_path.ts +++ b/src/legacy/server/i18n/get_translations_path.ts @@ -39,7 +39,7 @@ export async function getTranslationPaths({ cwd, glob }: { cwd: string; glob: st const content = await readFileAsync(entryFullPath, 'utf8'); const { translations } = JSON.parse(content) as I18NRCFileStructure; if (translations && translations.length) { - translations.forEach(translation => { + translations.forEach((translation) => { const translationFullPath = resolve(pluginBasePath, translation); translationPaths.push(translationFullPath); }); diff --git a/src/legacy/server/i18n/index.ts b/src/legacy/server/i18n/index.ts index 9902aaa1e8914..09f7022436049 100644 --- a/src/legacy/server/i18n/index.ts +++ b/src/legacy/server/i18n/index.ts @@ -35,10 +35,10 @@ export async function i18nMixin(kbnServer: KbnServer, server: Server, config: Ki cwd: fromRoot('.'), glob: I18N_RC, }), - ...(config.get('plugins.paths') as string[]).map(cwd => + ...(config.get('plugins.paths') as string[]).map((cwd) => getTranslationPaths({ cwd, glob: I18N_RC }) ), - ...(config.get('plugins.scanDirs') as string[]).map(cwd => + ...(config.get('plugins.scanDirs') as string[]).map((cwd) => getTranslationPaths({ cwd, glob: `*/${I18N_RC}` }) ), getTranslationPaths({ @@ -49,7 +49,7 @@ export async function i18nMixin(kbnServer: KbnServer, server: Server, config: Ki const currentTranslationPaths = ([] as string[]) .concat(...translationPaths) - .filter(translationPath => basename(translationPath, '.json') === locale); + .filter((translationPath) => basename(translationPath, '.json') === locale); i18nLoader.registerTranslationFiles(currentTranslationPaths); const translations = await i18nLoader.getTranslationsByLocale(locale); diff --git a/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts b/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts index cb77ce581eff2..9495098ede1a8 100644 --- a/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts +++ b/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts @@ -28,7 +28,7 @@ jest.doMock('fs', () => ({ const streamData = filepath.split(''); let cursor = 0; - readableStream._read = function(size) { + readableStream._read = function (size) { const current = streamData[cursor++]; if (typeof current === 'undefined') { return this.push(null); diff --git a/src/legacy/server/keystore/keystore.test.js b/src/legacy/server/keystore/keystore.test.js index db5276958c41c..0897ce55d086b 100644 --- a/src/legacy/server/keystore/keystore.test.js +++ b/src/legacy/server/keystore/keystore.test.js @@ -28,7 +28,7 @@ const mockUnprotectedKeystoreData = 'I4lzJ9MRy21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (path.includes('data/unprotected')) { return JSON.stringify(mockUnprotectedKeystoreData); } @@ -43,7 +43,7 @@ jest.mock('fs', () => ({ throw { code: 'EACCES' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return ( path.includes('data/unprotected') || path.includes('data/protected') || diff --git a/src/legacy/server/logging/apply_filters_to_keys.js b/src/legacy/server/logging/apply_filters_to_keys.js index 62e287ec9a286..63e5ab4c62f29 100644 --- a/src/legacy/server/logging/apply_filters_to_keys.js +++ b/src/legacy/server/logging/apply_filters_to_keys.js @@ -51,7 +51,7 @@ function apply(obj, key, action) { return obj; } -export default function(obj, actionsByKey) { +export default function (obj, actionsByKey) { return Object.keys(actionsByKey).reduce((output, key) => { return apply(output, key, actionsByKey[key]); }, toPojo(obj)); diff --git a/src/legacy/server/logging/apply_filters_to_keys.test.js b/src/legacy/server/logging/apply_filters_to_keys.test.js index 7ca26ed0f3bd6..e007157e9488b 100644 --- a/src/legacy/server/logging/apply_filters_to_keys.test.js +++ b/src/legacy/server/logging/apply_filters_to_keys.test.js @@ -19,8 +19,8 @@ import applyFiltersToKeys from './apply_filters_to_keys'; -describe('applyFiltersToKeys(obj, actionsByKey)', function() { - it('applies for each key+prop in actionsByKey', function() { +describe('applyFiltersToKeys(obj, actionsByKey)', function () { + it('applies for each key+prop in actionsByKey', function () { const data = applyFiltersToKeys( { a: { diff --git a/src/legacy/server/logging/configuration.js b/src/legacy/server/logging/configuration.js index 45a17d96a77cf..267dc9a334de8 100644 --- a/src/legacy/server/logging/configuration.js +++ b/src/legacy/server/logging/configuration.js @@ -64,7 +64,7 @@ export default function loggingConfiguration(config) { }, events: _.transform( events, - function(filtered, val, key) { + function (filtered, val, key) { // provide a string compatible way to remove events if (val !== '!') filtered[key] = val; }, diff --git a/src/legacy/server/logging/log_format.js b/src/legacy/server/logging/log_format.js index ca1d756704dd0..9bc1d67dd5857 100644 --- a/src/legacy/server/logging/log_format.js +++ b/src/legacy/server/logging/log_format.js @@ -38,7 +38,7 @@ function serializeError(err = {}) { }; } -const levelColor = function(code) { +const levelColor = function (code) { if (code < 299) return chalk.green(code); if (code < 399) return chalk.yellow(code); if (code < 499) return chalk.magentaBright(code); @@ -128,7 +128,7 @@ export default class TransformObjStream extends Stream.Transform { data.message += ' '; data.message += chalk.gray('load: ['); data.message += get(data, 'os.load', []) - .map(function(val) { + .map(function (val) { return numeral(val).format('0.00'); }) .join(' '); diff --git a/src/legacy/server/logging/log_format_json.js b/src/legacy/server/logging/log_format_json.js index bc9c9e6746f8a..bfceb78b24504 100644 --- a/src/legacy/server/logging/log_format_json.js +++ b/src/legacy/server/logging/log_format_json.js @@ -20,7 +20,7 @@ import LogFormat from './log_format'; import stringify from 'json-stringify-safe'; -const stripColors = function(string) { +const stripColors = function (string) { return string.replace(/\u001b[^m]+m/g, ''); }; diff --git a/src/legacy/server/logging/log_format_json.test.js b/src/legacy/server/logging/log_format_json.test.js index b39891440a75e..31e622ecae611 100644 --- a/src/legacy/server/logging/log_format_json.test.js +++ b/src/legacy/server/logging/log_format_json.test.js @@ -27,7 +27,7 @@ import KbnLoggerJsonFormat from './log_format_json'; const time = +moment('2010-01-01T05:15:59Z', moment.ISO_8601); -const makeEvent = eventType => ({ +const makeEvent = (eventType) => ({ event: eventType, timestamp: time, }); diff --git a/src/legacy/server/logging/log_format_string.js b/src/legacy/server/logging/log_format_string.js index 9cbbbbee33d91..3c18aab2e3d09 100644 --- a/src/legacy/server/logging/log_format_string.js +++ b/src/legacy/server/logging/log_format_string.js @@ -47,11 +47,11 @@ const typeColors = { scss: 'magentaBright', }; -const color = _.memoize(function(name) { +const color = _.memoize(function (name) { return chalk[typeColors[name]] || _.identity; }); -const type = _.memoize(function(t) { +const type = _.memoize(function (t) { return color(t)(_.pad(t, 7).slice(0, 7)); }); @@ -63,12 +63,12 @@ export default class KbnLoggerStringFormat extends LogFormat { const msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); const tags = _(data.tags) - .sortBy(function(tag) { + .sortBy(function (tag) { if (color(tag) === _.identity) return `2${tag}`; if (_.includes(statuses, tag)) return `0${tag}`; return `1${tag}`; }) - .reduce(function(s, t) { + .reduce(function (s, t) { return s + `[${color(t)(t)}]`; }, ''); diff --git a/src/legacy/server/logging/log_reporter.js b/src/legacy/server/logging/log_reporter.js index b784d03a5b86e..4afb00b568844 100644 --- a/src/legacy/server/logging/log_reporter.js +++ b/src/legacy/server/logging/log_reporter.js @@ -51,10 +51,7 @@ export function getLoggerStream({ events, config }) { }); } - logInterceptor - .pipe(squeeze) - .pipe(format) - .pipe(dest); + logInterceptor.pipe(squeeze).pipe(format).pipe(dest); return logInterceptor; } diff --git a/src/legacy/server/logging/rotate/log_rotator.ts b/src/legacy/server/logging/rotate/log_rotator.ts index eeb91fd0f2636..22183b2f0777a 100644 --- a/src/legacy/server/logging/rotate/log_rotator.ts +++ b/src/legacy/server/logging/rotate/log_rotator.ts @@ -115,7 +115,7 @@ export class LogRotator { // await writeFileAsync(tempFile, 'test'); - const usePollingTest$ = new Observable(observer => { + const usePollingTest$ = new Observable((observer) => { // observable complete function const completeFn = (completeStatus: boolean) => { if (this.stalkerUsePollingPolicyTestTimeout) { @@ -297,10 +297,10 @@ export class LogRotator { return ( foundLogFiles - .filter(file => new RegExp(`${logFileBaseName}\\.\\d`).test(file)) + .filter((file) => new RegExp(`${logFileBaseName}\\.\\d`).test(file)) // we use .slice(-1) here in order to retrieve the last number match in the read filenames .sort((a, b) => Number(a.match(/(\d+)/g)!.slice(-1)) - Number(b.match(/(\d+)/g)!.slice(-1))) - .map(filename => `${logFilesFolder}${sep}${filename}`) + .map((filename) => `${logFilesFolder}${sep}${filename}`) ); } diff --git a/src/legacy/server/pid/index.js b/src/legacy/server/pid/index.js index c4402b0542eaa..d7b9da1292252 100644 --- a/src/legacy/server/pid/index.js +++ b/src/legacy/server/pid/index.js @@ -23,14 +23,14 @@ import Bluebird from 'bluebird'; import { unlinkSync as unlink } from 'fs'; const writeFile = Bluebird.promisify(require('fs').writeFile); -export default Bluebird.method(function(kbnServer, server, config) { +export default Bluebird.method(function (kbnServer, server, config) { const path = config.get('pid.file'); if (!path) return; const pid = String(process.pid); return writeFile(path, pid, { flag: 'wx' }) - .catch(function(err) { + .catch(function (err) { if (err.code !== 'EEXIST') throw err; const message = `pid file already exists at ${path}`; @@ -47,18 +47,18 @@ export default Bluebird.method(function(kbnServer, server, config) { return writeFile(path, pid); }) - .then(function() { + .then(function () { server.logWithMetadata(['pid', 'debug'], `wrote pid file to ${path}`, { path: path, pid: pid, }); - const clean = _.once(function() { + const clean = _.once(function () { unlink(path); }); process.once('exit', clean); // for "natural" exits - process.once('SIGINT', function() { + process.once('SIGINT', function () { // for Ctrl-C exits clean(); @@ -66,7 +66,7 @@ export default Bluebird.method(function(kbnServer, server, config) { process.kill(process.pid, 'SIGINT'); }); - process.on('unhandledRejection', function(reason) { + process.on('unhandledRejection', function (reason) { server.log(['warning'], `Detected an unhandled Promise rejection.\n${reason}`); }); }); diff --git a/src/legacy/server/plugins/initialize_mixin.js b/src/legacy/server/plugins/initialize_mixin.js index 9cc317f002c5a..ccf4cd1c1a404 100644 --- a/src/legacy/server/plugins/initialize_mixin.js +++ b/src/legacy/server/plugins/initialize_mixin.js @@ -34,7 +34,7 @@ export async function initializeMixin(kbnServer, server, config) { async function callHookOnPlugins(hookName) { const { plugins } = kbnServer; - const ids = plugins.map(p => p.id); + const ids = plugins.map((p) => p.id); for (const id of ids) { await callPluginHook(hookName, plugins, id, []); diff --git a/src/legacy/server/plugins/lib/call_plugin_hook.js b/src/legacy/server/plugins/lib/call_plugin_hook.js index c62a3460fa3e2..b665869f5d25f 100644 --- a/src/legacy/server/plugins/lib/call_plugin_hook.js +++ b/src/legacy/server/plugins/lib/call_plugin_hook.js @@ -20,7 +20,7 @@ import { last } from 'lodash'; export async function callPluginHook(hookName, plugins, id, history) { - const plugin = plugins.find(plugin => plugin.id === id); + const plugin = plugins.find((plugin) => plugin.id === id); // make sure this is a valid plugin id if (!plugin) { diff --git a/src/legacy/server/plugins/scan_mixin.js b/src/legacy/server/plugins/scan_mixin.js index c66ce8da3a07a..89ebaf920d9d1 100644 --- a/src/legacy/server/plugins/scan_mixin.js +++ b/src/legacy/server/plugins/scan_mixin.js @@ -19,5 +19,5 @@ import { Plugin } from './lib'; export async function scanMixin(kbnServer) { - kbnServer.plugins = kbnServer.pluginSpecs.map(spec => new Plugin(kbnServer, spec)); + kbnServer.plugins = kbnServer.pluginSpecs.map((spec) => new Plugin(kbnServer, spec)); } diff --git a/src/legacy/server/plugins/wait_for_plugins_init.js b/src/legacy/server/plugins/wait_for_plugins_init.js index 1625ee127f56c..144eb5ef803cc 100644 --- a/src/legacy/server/plugins/wait_for_plugins_init.js +++ b/src/legacy/server/plugins/wait_for_plugins_init.js @@ -27,7 +27,7 @@ const queues = new WeakMap(); export function waitForInitSetupMixin(kbnServer) { queues.set(kbnServer, []); - kbnServer.afterPluginsInit = function(callback) { + kbnServer.afterPluginsInit = function (callback) { const queue = queues.get(kbnServer); if (!queue) { diff --git a/src/legacy/server/sass/build.js b/src/legacy/server/sass/build.js index 1ec656786ccc5..2c0a2d84be2c0 100644 --- a/src/legacy/server/sass/build.js +++ b/src/legacy/server/sass/build.js @@ -35,7 +35,7 @@ const copyFile = promisify(fs.copyFile); const mkdirAsync = promisify(fs.mkdir); const UI_ASSETS_DIR = resolve(__dirname, '../../../core/server/core_app/assets'); -const DARK_THEME_IMPORTER = url => { +const DARK_THEME_IMPORTER = (url) => { if (url.includes('eui_colors_light')) { return { file: url.replace('eui_colors_light', 'eui_colors_dark') }; } @@ -101,7 +101,7 @@ export class Build { if (this.urlImports) { processor.use( postcssUrl({ - url: request => { + url: (request) => { if (!request.pathname) { return request.url; } @@ -144,7 +144,7 @@ export class Build { // verify that asset sources exist and import is valid before writing anything await Promise.all( - urlAssets.map(async asset => { + urlAssets.map(async (asset) => { try { await access(asset.path); } catch (e) { @@ -171,7 +171,7 @@ export class Build { // copy non-shared urlAssets await Promise.all( - urlAssets.map(async asset => { + urlAssets.map(async (asset) => { if (!asset.copyTo) { return; } diff --git a/src/legacy/server/sass/build_all.js b/src/legacy/server/sass/build_all.js index 1d3d76d1cb01a..dac6ac87a40d3 100644 --- a/src/legacy/server/sass/build_all.js +++ b/src/legacy/server/sass/build_all.js @@ -23,7 +23,7 @@ import { Build } from './build'; export async function buildAll({ styleSheets, log, buildDir }) { const bundles = await Promise.all( - styleSheets.map(async styleSheet => { + styleSheets.map(async (styleSheet) => { if (!styleSheet.localPath.endsWith('.scss')) { return; } @@ -41,5 +41,5 @@ export async function buildAll({ styleSheets, log, buildDir }) { }) ); - return bundles.filter(v => v); + return bundles.filter((v) => v); } diff --git a/src/legacy/server/sass/index.js b/src/legacy/server/sass/index.js index 9109e1b1dcea7..001457d110276 100644 --- a/src/legacy/server/sass/index.js +++ b/src/legacy/server/sass/index.js @@ -41,9 +41,9 @@ export async function sassMixin(kbnServer, server, config) { let trackedFiles = new Set(); const log = { - info: msg => server.log(['info', 'scss'], msg), - warn: msg => server.log(['warn', 'scss'], msg), - error: msg => server.log(['error', 'scss'], msg), + info: (msg) => server.log(['info', 'scss'], msg), + warn: (msg) => server.log(['warn', 'scss'], msg), + error: (msg) => server.log(['error', 'scss'], msg), }; try { @@ -53,8 +53,8 @@ export async function sassMixin(kbnServer, server, config) { buildDir: fromRoot('built_assets/css'), }); - scssBundles.forEach(bundle => { - bundle.includedFiles.forEach(file => trackedFiles.add(file)); + scssBundles.forEach((bundle) => { + bundle.includedFiles.forEach((file) => trackedFiles.add(file)); server.log(['info', 'scss'], `Compiled CSS: ${bundle.sourcePath} (theme=${bundle.theme})`); }); } catch (error) { @@ -89,13 +89,13 @@ export async function sassMixin(kbnServer, server, config) { // build bundles containing the changed file await Promise.all( - scssBundles.map(async bundle => { + scssBundles.map(async (bundle) => { try { if (await bundle.buildIfIncluded(path)) { server.log(['info', 'scss'], `Compiled ${bundle.sourcePath} due to change in ${path}`); } // if the bundle rebuilt, includedFiles is the new set; otherwise includedFiles is unchanged and remains tracked - bundle.includedFiles.forEach(file => currentlyTrackedFiles.add(file)); + bundle.includedFiles.forEach((file) => currentlyTrackedFiles.add(file)); } catch (error) { const { message, line, file } = error; if (!file) { @@ -113,7 +113,7 @@ export async function sassMixin(kbnServer, server, config) { */ // un-watch files no longer included in any bundle - trackedFiles.forEach(file => { + trackedFiles.forEach((file) => { if (currentlyTrackedFiles.has(file)) { return; } @@ -123,7 +123,7 @@ export async function sassMixin(kbnServer, server, config) { }); // watch files not previously included in any bundle - currentlyTrackedFiles.forEach(file => { + currentlyTrackedFiles.forEach((file) => { if (trackedFiles.has(file)) { return; } diff --git a/src/legacy/server/saved_objects/saved_objects_mixin.js b/src/legacy/server/saved_objects/saved_objects_mixin.js index 26fecc68fda4b..7d84c27bd1ef0 100644 --- a/src/legacy/server/saved_objects/saved_objects_mixin.js +++ b/src/legacy/server/saved_objects/saved_objects_mixin.js @@ -36,14 +36,14 @@ export function savedObjectsMixin(kbnServer, server) { const mappings = migrator.getActiveMappings(); const allTypes = Object.keys(getRootPropertiesObjects(mappings)); const schema = new SavedObjectsSchema(convertTypesToLegacySchema(typeRegistry.getAllTypes())); - const visibleTypes = allTypes.filter(type => !schema.isHiddenType(type)); + const visibleTypes = allTypes.filter((type) => !schema.isHiddenType(type)); server.decorate('server', 'kibanaMigrator', migrator); - const warn = message => server.log(['warning', 'saved-objects'], message); + const warn = (message) => server.log(['warning', 'saved-objects'], message); // we use kibana.index which is technically defined in the kibana plugin, so if // we don't have the plugin (mainly tests) we can't initialize the saved objects - if (!kbnServer.pluginSpecs.some(p => p.getId() === 'kibana')) { + if (!kbnServer.pluginSpecs.some((p) => p.getId() === 'kibana')) { warn('Saved Objects uninitialized because the Kibana plugin is disabled.'); return; } @@ -55,7 +55,7 @@ export function savedObjectsMixin(kbnServer, server) { throw new TypeError('Repository requires a "callCluster" function to be provided.'); } // throw an exception if an extraType is not defined. - includedHiddenTypes.forEach(type => { + includedHiddenTypes.forEach((type) => { if (!allTypes.includes(type)) { throw new Error(`Missing mappings for saved objects type '${type}'`); } @@ -98,7 +98,7 @@ export function savedObjectsMixin(kbnServer, server) { server.decorate('server', 'savedObjects', service); const savedObjectsClientCache = new WeakMap(); - server.decorate('request', 'getSavedObjectsClient', function(options) { + server.decorate('request', 'getSavedObjectsClient', function (options) { const request = this; if (savedObjectsClientCache.has(request)) { diff --git a/src/legacy/server/saved_objects/saved_objects_mixin.test.js b/src/legacy/server/saved_objects/saved_objects_mixin.test.js index d49b18ee2ce6c..5b40cc4b5aa35 100644 --- a/src/legacy/server/saved_objects/saved_objects_mixin.test.js +++ b/src/legacy/server/saved_objects/saved_objects_mixin.test.js @@ -88,7 +88,7 @@ const savedObjectTypes = convertLegacyTypes( ); const typeRegistry = new SavedObjectTypeRegistry(); -savedObjectTypes.forEach(type => typeRegistry.registerType(type)); +savedObjectTypes.forEach((type) => typeRegistry.registerType(type)); const migrator = mockKibanaMigrator.create({ types: savedObjectTypes, @@ -103,7 +103,7 @@ describe('Saved Objects Mixin', () => { 'kibana.index': 'kibana.index', 'savedObjects.maxImportExportSize': 10000, }; - const stubConfig = jest.fn(key => { + const stubConfig = jest.fn((key) => { return config[key]; }); diff --git a/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js b/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js index cbae6450ea405..48bd082468061 100644 --- a/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js +++ b/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js @@ -104,7 +104,7 @@ describe('server.addMemoizedFactoryToRequest()', () => { expect(() => server.addMemoizedFactoryToRequest('name', () => {})).not.toThrowError( 'more than one argument' ); - expect(() => server.addMemoizedFactoryToRequest('name', a => {})).not.toThrowError( + expect(() => server.addMemoizedFactoryToRequest('name', (a) => {})).not.toThrowError( 'more than one argument' ); expect(() => server.addMemoizedFactoryToRequest('name', (a, b) => {})).toThrowError( diff --git a/src/legacy/server/server_extensions/server_extensions_mixin.js b/src/legacy/server/server_extensions/server_extensions_mixin.js index fac8eda4adfb1..19c0b24ae15a1 100644 --- a/src/legacy/server/server_extensions/server_extensions_mixin.js +++ b/src/legacy/server/server_extensions/server_extensions_mixin.js @@ -51,7 +51,7 @@ export function serverExtensionsMixin(kbnServer, server) { } const requestCache = new WeakMap(); - server.decorate('request', methodName, function() { + server.decorate('request', methodName, function () { const request = this; if (!requestCache.has(request)) { diff --git a/src/legacy/server/status/index.js b/src/legacy/server/status/index.js index 5bd1efa99eb2c..377a5d74610a9 100644 --- a/src/legacy/server/status/index.js +++ b/src/legacy/server/status/index.js @@ -31,7 +31,7 @@ export function statusMixin(kbnServer, server, config) { const metrics = new Metrics(config, server); const oppsy = new Oppsy(server); - oppsy.on('ops', event => { + oppsy.on('ops', (event) => { // Oppsy has a bad race condition that will modify this data before // we ship it off to the buffer. Let's create our copy first. event = cloneDeep(event); @@ -41,7 +41,7 @@ export function statusMixin(kbnServer, server, config) { // captures (performs transforms on) the latest event data and stashes // the metrics for status/stats API payload - metrics.capture(event).then(data => { + metrics.capture(event).then((data) => { kbnServer.metrics = data; }); }); diff --git a/src/legacy/server/status/lib/__mocks__/_fs_stubs.js b/src/legacy/server/status/lib/__mocks__/_fs_stubs.js index a22822776f461..2be6402baa5fe 100644 --- a/src/legacy/server/status/lib/__mocks__/_fs_stubs.js +++ b/src/legacy/server/status/lib/__mocks__/_fs_stubs.js @@ -19,9 +19,7 @@ export function cGroups(hierarchy) { if (!hierarchy) { - hierarchy = Math.random() - .toString(36) - .substring(7); + hierarchy = Math.random().toString(36).substring(7); } const cpuAcctDir = `/sys/fs/cgroup/cpuacct/${hierarchy}`; @@ -68,7 +66,7 @@ class FSError extends Error { let _mockFiles = Object.create({}); -export const setMockFiles = mockFiles => { +export const setMockFiles = (mockFiles) => { _mockFiles = Object.create({}); if (mockFiles) { const files = Object.keys(mockFiles); diff --git a/src/legacy/server/status/lib/cgroup.js b/src/legacy/server/status/lib/cgroup.js index 8f59ce6d84d0e..4d21cafbedcaa 100644 --- a/src/legacy/server/status/lib/cgroup.js +++ b/src/legacy/server/status/lib/cgroup.js @@ -41,13 +41,13 @@ const CPU_STATS_FILE = 'cpu.stat'; const readFile = promisify(fs.readFile); export function readControlGroups() { - return readFile(PROC_SELF_CGROUP_FILE).then(data => { + return readFile(PROC_SELF_CGROUP_FILE).then((data) => { const response = {}; data .toString() .split(/\n/) - .forEach(line => { + .forEach((line) => { const matches = line.match(CONTROL_GROUP_RE); if (matches === null) { @@ -55,7 +55,7 @@ export function readControlGroups() { } const controllers = matches[1].split(CONTROLLER_SEPARATOR_RE); - controllers.forEach(controller => { + controllers.forEach((controller) => { response[controller] = matches[2]; }); }); @@ -65,7 +65,7 @@ export function readControlGroups() { } function fileContentsToInteger(path) { - return readFile(path).then(data => { + return readFile(path).then((data) => { return parseInt(data.toString(), 10); }); } @@ -91,11 +91,11 @@ export function readCPUStat(controlGroup) { }; readFile(joinPath(PROC_CGROUP_CPU_DIR, controlGroup, CPU_STATS_FILE)) - .then(data => { + .then((data) => { data .toString() .split(/\n/) - .forEach(line => { + .forEach((line) => { const fields = line.split(/\s+/); switch (fields[0]) { @@ -115,7 +115,7 @@ export function readCPUStat(controlGroup) { resolve(stat); }) - .catch(err => { + .catch((err) => { if (err.code === 'ENOENT') { return resolve(stat); } @@ -128,7 +128,7 @@ export function readCPUStat(controlGroup) { export function getAllStats(options = {}) { return new Promise((resolve, reject) => { readControlGroups() - .then(groups => { + .then((groups) => { const cpuPath = options.cpuPath || groups[GROUP_CPU]; const cpuAcctPath = options.cpuAcctPath || groups[GROUP_CPUACCT]; diff --git a/src/legacy/server/status/lib/cgroup.test.js b/src/legacy/server/status/lib/cgroup.test.js index 1134dd89f752e..62feba45d1b3c 100644 --- a/src/legacy/server/status/lib/cgroup.test.js +++ b/src/legacy/server/status/lib/cgroup.test.js @@ -25,7 +25,7 @@ import fs from 'fs'; import { cGroups as cGroupsFsStub, setMockFiles, readFileMock } from './__mocks__/_fs_stubs'; import { getAllStats, readControlGroups, readCPUStat } from './cgroup'; -describe('Control Group', function() { +describe('Control Group', function () { const fsStub = cGroupsFsStub(); beforeAll(() => { diff --git a/src/legacy/server/status/lib/get_os_info.test.js b/src/legacy/server/status/lib/get_os_info.test.js index eaa310f603fa2..11af7e1588090 100644 --- a/src/legacy/server/status/lib/get_os_info.test.js +++ b/src/legacy/server/status/lib/get_os_info.test.js @@ -46,7 +46,7 @@ describe('getOSInfo', () => { os.release.mockImplementation(() => '4.9.93-linuxkit-aufs'); // Mock getos response - getos.mockImplementation(cb => + getos.mockImplementation((cb) => cb(null, { os: 'linux', dist: 'Ubuntu Linux', diff --git a/src/legacy/server/status/lib/metrics.test.js b/src/legacy/server/status/lib/metrics.test.js index 4798ae7c5c888..6a734941eb70c 100644 --- a/src/legacy/server/status/lib/metrics.test.js +++ b/src/legacy/server/status/lib/metrics.test.js @@ -40,7 +40,7 @@ import sinon from 'sinon'; import { cGroups as cGroupsFsStub, setMockFiles, readFileMock } from './__mocks__/_fs_stubs'; import { Metrics } from './metrics'; -describe('Metrics', function() { +describe('Metrics', function () { fs.readFile.mockImplementation(readFileMock); const sampleConfig = { @@ -51,7 +51,7 @@ describe('Metrics', function() { port: 5603, }, }; - const config = { get: path => _.get(sampleConfig, path) }; + const config = { get: (path) => _.get(sampleConfig, path) }; let metrics; diff --git a/src/legacy/server/status/routes/api/register_stats.js b/src/legacy/server/status/routes/api/register_stats.js index 2dd66cb8caff7..09957e61f74d3 100644 --- a/src/legacy/server/status/routes/api/register_stats.js +++ b/src/legacy/server/status/routes/api/register_stats.js @@ -40,12 +40,12 @@ const STATS_NOT_READY_MESSAGE = i18n.translate('server.stats.notReadyMessage', { export function registerStatsApi(usageCollection, server, config, kbnServer) { const wrapAuth = wrapAuthConfig(config.get('status.allowAnonymous')); - const getClusterUuid = async callCluster => { + const getClusterUuid = async (callCluster) => { const { cluster_uuid: uuid } = await callCluster('info', { filterPath: 'cluster_uuid' }); return uuid; }; - const getUsage = async callCluster => { + const getUsage = async (callCluster) => { const usage = await usageCollection.bulkFetchUsage(callCluster); return usageCollection.toObject(usage); }; @@ -54,7 +54,7 @@ export function registerStatsApi(usageCollection, server, config, kbnServer) { /* kibana_stats gets singled out from the collector set as it is used * for health-checking Kibana and fetch does not rely on fetching data * from ES */ - server.newPlatform.setup.core.metrics.getOpsMetrics$().subscribe(metrics => { + server.newPlatform.setup.core.metrics.getOpsMetrics$().subscribe((metrics) => { lastMetrics = { ...metrics, timestamp: new Date().toISOString(), diff --git a/src/legacy/server/status/routes/page/register_status.js b/src/legacy/server/status/routes/page/register_status.js index 08d266e6dbf84..47bd3c34eba59 100644 --- a/src/legacy/server/status/routes/page/register_status.js +++ b/src/legacy/server/status/routes/page/register_status.js @@ -23,7 +23,7 @@ export function registerStatusPage(kbnServer, server, config) { const allowAnonymous = config.get('status.allowAnonymous'); const wrapAuth = wrapAuthConfig(allowAnonymous); - server.decorate('toolkit', 'renderStatusPage', async function() { + server.decorate('toolkit', 'renderStatusPage', async function () { const app = server.getHiddenUiAppById('status_page'); const h = this; diff --git a/src/legacy/server/status/samples.js b/src/legacy/server/status/samples.js index 69f25125e2666..9c41e29945a77 100644 --- a/src/legacy/server/status/samples.js +++ b/src/legacy/server/status/samples.js @@ -25,11 +25,11 @@ function Samples(max) { this.length = 0; } -Samples.prototype.add = function(sample) { +Samples.prototype.add = function (sample) { const vals = this.vals; const length = (this.length = Math.min(this.length + 1, this.max)); - _.forOwn(sample, function(val, name) { + _.forOwn(sample, function (val, name) { if (val == null) val = null; if (!vals[name]) vals[name] = new Array(length); @@ -38,7 +38,7 @@ Samples.prototype.add = function(sample) { }); }; -Samples.prototype.toJSON = function() { +Samples.prototype.toJSON = function () { return this.vals; }; diff --git a/src/legacy/server/status/server_status.js b/src/legacy/server/status/server_status.js index 3be1c17110711..3ee4d37d0b823 100644 --- a/src/legacy/server/status/server_status.js +++ b/src/legacy/server/status/server_status.js @@ -45,7 +45,7 @@ export default class ServerStatus { each(fn) { const self = this; - _.forOwn(self._created, function(status, i, list) { + _.forOwn(self._created, function (status, i, list) { if (status.state !== 'disabled') { fn.call(self, status, i, list); } @@ -57,7 +57,7 @@ export default class ServerStatus { } getForPluginId(pluginId) { - return _.find(this._created, s => s.plugin && s.plugin.id === pluginId); + return _.find(this._created, (s) => s.plugin && s.plugin.id === pluginId); } getState(id) { @@ -77,7 +77,7 @@ export default class ServerStatus { // take all created status objects .values(this._created) // get the state descriptor for each status - .map(status => states.get(status.state)) + .map((status) => states.get(status.state)) // reduce to the state with the highest severity, defaulting to green .reduce((a, b) => (a.severity > b.severity ? a : b), states.get('green')); diff --git a/src/legacy/server/status/server_status.test.js b/src/legacy/server/status/server_status.test.js index 7155e3df69a4f..bf94d693b1310 100644 --- a/src/legacy/server/status/server_status.test.js +++ b/src/legacy/server/status/server_status.test.js @@ -24,13 +24,13 @@ import * as states from './states'; import Status from './status'; import ServerStatus from './server_status'; -describe('ServerStatus class', function() { +describe('ServerStatus class', function () { const plugin = { id: 'name', version: '1.2.3' }; let server; let serverStatus; - beforeEach(function() { + beforeEach(function () { server = { expose: sinon.stub(), logWithMetadata: sinon.stub() }; serverStatus = new ServerStatus(server); }); @@ -42,8 +42,8 @@ describe('ServerStatus class', function() { }); }); - describe('#createForPlugin(plugin)', function() { - it('should create a new status by plugin', function() { + describe('#createForPlugin(plugin)', function () { + it('should create a new status by plugin', function () { const status = serverStatus.createForPlugin(plugin); expect(status).toBeInstanceOf(Status); }); @@ -61,41 +61,41 @@ describe('ServerStatus class', function() { }); }); - describe('#getForPluginId(plugin)', function() { - it('exposes plugin status for the plugin', function() { + describe('#getForPluginId(plugin)', function () { + it('exposes plugin status for the plugin', function () { const status = serverStatus.createForPlugin(plugin); expect(serverStatus.getForPluginId(plugin.id)).toBe(status); }); - it('does not get plain statuses by their id', function() { + it('does not get plain statuses by their id', function () { serverStatus.create('someid'); expect(serverStatus.getForPluginId('someid')).toBe(undefined); }); }); - describe('#getState(id)', function() { - it('should expose the state of a status by id', function() { + describe('#getState(id)', function () { + it('should expose the state of a status by id', function () { const status = serverStatus.create('someid'); status.green(); expect(serverStatus.getState('someid')).toBe('green'); }); }); - describe('#getStateForPluginId(plugin)', function() { - it('should expose the state of a plugin by id', function() { + describe('#getStateForPluginId(plugin)', function () { + it('should expose the state of a plugin by id', function () { const status = serverStatus.createForPlugin(plugin); status.green(); expect(serverStatus.getStateForPluginId(plugin.id)).toBe('green'); }); }); - describe('#overall()', function() { - it('considers each status to produce a summary', function() { + describe('#overall()', function () { + it('considers each status to produce a summary', function () { const status = serverStatus.createForPlugin(plugin); expect(serverStatus.overall().state).toBe('uninitialized'); - const match = function(overall, state) { + const match = function (overall, state) { expect(overall).toHaveProperty('state', state.id); expect(overall).toHaveProperty('title', state.title); expect(overall).toHaveProperty('icon', state.icon); @@ -114,8 +114,8 @@ describe('ServerStatus class', function() { }); }); - describe('#toJSON()', function() { - it('serializes to overall status and individuals', function() { + describe('#toJSON()', function () { + it('serializes to overall status and individuals', function () { const pluginOne = { id: 'one', version: '1.0.0' }; const pluginTwo = { id: 'two', version: '2.0.0' }; const pluginThree = { id: 'three', version: 'kibana' }; @@ -134,7 +134,7 @@ describe('ServerStatus class', function() { expect(json.overall.state).toEqual(serverStatus.overall().state); expect(json.statuses).toHaveLength(4); - const out = status => find(json.statuses, { id: status.id }); + const out = (status) => find(json.statuses, { id: status.id }); expect(out(service)).toHaveProperty('state', 'green'); expect(out(p1)).toHaveProperty('state', 'yellow'); expect(out(p2)).toHaveProperty('state', 'red'); diff --git a/src/legacy/server/status/status.js b/src/legacy/server/status/status.js index 373f3b316b993..10e94da3ac352 100644 --- a/src/legacy/server/status/status.js +++ b/src/legacy/server/status/status.js @@ -33,7 +33,7 @@ export default class Status extends EventEmitter { this.state = 'uninitialized'; this.message = 'uninitialized'; - this.on('change', function(previous, previousMsg) { + this.on('change', function (previous, previousMsg) { this.since = new Date(); const tags = ['status', this.id, this.state === 'red' ? 'error' : 'info']; @@ -81,8 +81,8 @@ export default class Status extends EventEmitter { } } -states.getAll().forEach(function(state) { - Status.prototype[state.id] = function(message) { +states.getAll().forEach(function (state) { + Status.prototype[state.id] = function (message) { if (this.state === 'disabled') return; const previous = this.state; diff --git a/src/legacy/server/status/status.test.js b/src/legacy/server/status/status.test.js index 89c0da74febe9..def7b5a2182e1 100644 --- a/src/legacy/server/status/status.test.js +++ b/src/legacy/server/status/status.test.js @@ -20,13 +20,13 @@ import sinon from 'sinon'; import ServerStatus from './server_status'; -describe('Status class', function() { +describe('Status class', function () { const plugin = { id: 'test', version: '1.2.3' }; let server; let serverStatus; - beforeEach(function() { + beforeEach(function () { server = { expose: sinon.stub(), logWithMetadata: sinon.stub() }; serverStatus = new ServerStatus(server); }); @@ -35,15 +35,15 @@ describe('Status class', function() { expect(serverStatus.createForPlugin(plugin)).toHaveProperty('state', 'uninitialized'); }); - it('emits change when the status is set', function(done) { + it('emits change when the status is set', function (done) { const status = serverStatus.createForPlugin(plugin); - status.once('change', function(prevState, prevMsg, newState, newMsg) { + status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).toBe('green'); expect(newMsg).toBe('GREEN'); expect(prevState).toBe('uninitialized'); - status.once('change', function(prevState, prevMsg, newState, newMsg) { + status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).toBe('red'); expect(newMsg).toBe('RED'); expect(prevState).toBe('green'); @@ -58,7 +58,7 @@ describe('Status class', function() { status.green('GREEN'); }); - it('should only trigger the change listener when something changes', function() { + it('should only trigger the change listener when something changes', function () { const status = serverStatus.createForPlugin(plugin); const stub = sinon.stub(); status.on('change', stub); @@ -68,7 +68,7 @@ describe('Status class', function() { sinon.assert.calledTwice(stub); }); - it('should create a JSON representation of the status', function() { + it('should create a JSON representation of the status', function () { const status = serverStatus.createForPlugin(plugin); status.green('Ready'); @@ -78,12 +78,12 @@ describe('Status class', function() { expect(json.message).toEqual('Ready'); }); - it('should call on handler if status is already matched', function(done) { + it('should call on handler if status is already matched', function (done) { const status = serverStatus.createForPlugin(plugin); const msg = 'Test Ready'; status.green(msg); - status.on('green', function(prev, prevMsg) { + status.on('green', function (prev, prevMsg) { expect(arguments.length).toBe(2); expect(prev).toBe('green'); expect(prevMsg).toBe(msg); @@ -92,12 +92,12 @@ describe('Status class', function() { }); }); - it('should call once handler if status is already matched', function(done) { + it('should call once handler if status is already matched', function (done) { const status = serverStatus.createForPlugin(plugin); const msg = 'Test Ready'; status.green(msg); - status.once('green', function(prev, prevMsg) { + status.once('green', function (prev, prevMsg) { expect(arguments.length).toBe(2); expect(prev).toBe('green'); expect(prevMsg).toBe(msg); @@ -107,7 +107,7 @@ describe('Status class', function() { }); function testState(color) { - it(`should change the state to ${color} when #${color}() is called`, function() { + it(`should change the state to ${color} when #${color}() is called`, function () { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; status[color](message); @@ -115,10 +115,10 @@ describe('Status class', function() { expect(status).toHaveProperty('message', message); }); - it(`should trigger the "change" listener when #${color}() is called`, function(done) { + it(`should trigger the "change" listener when #${color}() is called`, function (done) { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; - status.on('change', function(prev, prevMsg) { + status.on('change', function (prev, prevMsg) { expect(status.state).toBe(color); expect(status.message).toBe(message); @@ -129,10 +129,10 @@ describe('Status class', function() { status[color](message); }); - it(`should trigger the "${color}" listener when #${color}() is called`, function(done) { + it(`should trigger the "${color}" listener when #${color}() is called`, function (done) { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; - status.on(color, function() { + status.on(color, function () { expect(status.state).toBe(color); expect(status.message).toBe(message); done(); diff --git a/src/legacy/server/status/wrap_auth_config.js b/src/legacy/server/status/wrap_auth_config.js index a55318ee49582..04e71a02d30de 100644 --- a/src/legacy/server/status/wrap_auth_config.js +++ b/src/legacy/server/status/wrap_auth_config.js @@ -19,9 +19,9 @@ import { assign, identity } from 'lodash'; -export const wrapAuthConfig = allowAnonymous => { +export const wrapAuthConfig = (allowAnonymous) => { if (allowAnonymous) { - return options => assign(options, { config: { auth: false } }); + return (options) => assign(options, { config: { auth: false } }); } return identity; }; diff --git a/src/legacy/server/status/wrap_auth_config.test.js b/src/legacy/server/status/wrap_auth_config.test.js index 9b2a1c33d4ff1..fa0230a96a587 100644 --- a/src/legacy/server/status/wrap_auth_config.test.js +++ b/src/legacy/server/status/wrap_auth_config.test.js @@ -26,7 +26,7 @@ describe('Status wrapAuthConfig', () => { options = { method: 'GET', path: '/status', - handler: function(request, h) { + handler: function (request, h) { return h.response(); }, }; diff --git a/src/legacy/server/utils/prompt.js b/src/legacy/server/utils/prompt.js index 3fdac1b685808..2e53558213140 100644 --- a/src/legacy/server/utils/prompt.js +++ b/src/legacy/server/utils/prompt.js @@ -33,11 +33,11 @@ export function confirm(question, options = {}) { output: options.output || process.stdout, }); - return new Promise(resolve => { + return new Promise((resolve) => { const defaultValue = options.default ? true : false; const defaultPrompt = defaultValue ? 'Y/n' : 'y/N'; - rl.question(`${question} [${defaultPrompt}] `, input => { + rl.question(`${question} [${defaultPrompt}] `, (input) => { let value = defaultValue; if (input != null && input !== '') { @@ -65,8 +65,8 @@ export function question(question, options = {}) { const questionPrompt = `${question}: `; const rl = createInterface({ input, output }); - return new Promise(resolve => { - input.on('data', char => { + return new Promise((resolve) => { + input.on('data', (char) => { char = char + ''; switch (char) { @@ -85,7 +85,7 @@ export function question(question, options = {}) { } }); - rl.question(questionPrompt, value => { + rl.question(questionPrompt, (value) => { resolve(value); }); }); diff --git a/src/legacy/server/warnings/index.js b/src/legacy/server/warnings/index.js index 6fa29d0f407c6..e96366893076a 100644 --- a/src/legacy/server/warnings/index.js +++ b/src/legacy/server/warnings/index.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(kbnServer, server) { - process.on('warning', warning => { +export default function (kbnServer, server) { + process.on('warning', (warning) => { // deprecation warnings do no reflect a current problem for // the user and therefor should be filtered out. if (warning.name === 'DeprecationWarning') { diff --git a/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js b/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js index 1c2d08c968dc0..afe618c6d3d9c 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js @@ -19,7 +19,7 @@ import Bluebird from 'bluebird'; -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js b/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js index 8c11a2ee160c0..975a1dc7c92e7 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js b/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js index 8c11a2ee160c0..975a1dc7c92e7 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/test_app/index.js b/src/legacy/ui/__tests__/fixtures/test_app/index.js index 1491e6135c096..3eddefd618ce0 100644 --- a/src/legacy/ui/__tests__/fixtures/test_app/index.js +++ b/src/legacy/ui/__tests__/fixtures/test_app/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ uiExports: { app: { diff --git a/src/legacy/ui/public/__tests__/events.js b/src/legacy/ui/public/__tests__/events.js index aff756cd1807d..c225c2a8ac1c0 100644 --- a/src/legacy/ui/public/__tests__/events.js +++ b/src/legacy/ui/public/__tests__/events.js @@ -26,7 +26,7 @@ import '../private'; import { createDefer } from 'ui/promises'; import { createLegacyClass } from '../utils/legacy_class'; -describe('Events', function() { +describe('Events', function () { require('test_utils/no_digest_promises').activateForSuite(); let Events; @@ -35,16 +35,16 @@ describe('Events', function() { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector, Private) { + ngMock.inject(function ($injector, Private) { Promise = $injector.get('Promise'); Events = Private(EventsProvider); eventsInstance = new Events(); }) ); - it('should handle on events', function() { + it('should handle on events', function () { const obj = new Events(); - const prom = obj.on('test', function(message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -53,14 +53,14 @@ describe('Events', function() { return prom; }); - it('should work with inherited objects', function() { + it('should work with inherited objects', function () { createLegacyClass(MyEventedObject).inherits(Events); function MyEventedObject() { MyEventedObject.Super.call(this); } const obj = new MyEventedObject(); - const prom = obj.on('test', function(message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -69,7 +69,7 @@ describe('Events', function() { return prom; }); - it('should clear events when off is called', function() { + it('should clear events when off is called', function () { const obj = new Events(); obj.on('test', _.noop); expect(obj._listeners).to.have.property('test'); @@ -78,7 +78,7 @@ describe('Events', function() { expect(obj._listeners).to.not.have.property('test'); }); - it('should clear a specific handler when off is called for an event', function() { + it('should clear a specific handler when off is called for an event', function () { const obj = new Events(); const handler1 = sinon.stub(); const handler2 = sinon.stub(); @@ -87,13 +87,13 @@ describe('Events', function() { expect(obj._listeners).to.have.property('test'); obj.off('test', handler1); - return obj.emit('test', 'Hello World').then(function() { + return obj.emit('test', 'Hello World').then(function () { sinon.assert.calledOnce(handler2); sinon.assert.notCalled(handler1); }); }); - it('should clear a all handlers when off is called for an event', function() { + it('should clear a all handlers when off is called for an event', function () { const obj = new Events(); const handler1 = sinon.stub(); obj.on('test', handler1); @@ -101,19 +101,19 @@ describe('Events', function() { obj.off('test'); expect(obj._listeners).to.not.have.property('test'); - return obj.emit('test', 'Hello World').then(function() { + return obj.emit('test', 'Hello World').then(function () { sinon.assert.notCalled(handler1); }); }); - it('should handle multiple identical emits in the same tick', function() { + it('should handle multiple identical emits in the same tick', function () { const obj = new Events(); const handler1 = sinon.stub(); obj.on('test', handler1); const emits = [obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three')]; - return Promise.all(emits).then(function() { + return Promise.all(emits).then(function () { expect(handler1.callCount).to.be(emits.length); expect(handler1.getCall(0).calledWith('one')).to.be(true); expect(handler1.getCall(1).calledWith('two')).to.be(true); @@ -121,11 +121,11 @@ describe('Events', function() { }); }); - it('should handle emits from the handler', function() { + it('should handle emits from the handler', function () { const obj = new Events(); const secondEmit = createDefer(Promise); - const handler1 = sinon.spy(function() { + const handler1 = sinon.spy(function () { if (handler1.calledTwice) { return; } @@ -134,12 +134,12 @@ describe('Events', function() { obj.on('test', handler1); - return Promise.all([obj.emit('test'), secondEmit.promise]).then(function() { + return Promise.all([obj.emit('test'), secondEmit.promise]).then(function () { expect(handler1.callCount).to.be(2); }); }); - it('should only emit to handlers registered before emit is called', function() { + it('should only emit to handlers registered before emit is called', function () { const obj = new Events(); const handler1 = sinon.stub(); const handler2 = sinon.stub(); @@ -147,34 +147,34 @@ describe('Events', function() { obj.on('test', handler1); const emits = [obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three')]; - return Promise.all(emits).then(function() { + return Promise.all(emits).then(function () { expect(handler1.callCount).to.be(emits.length); obj.on('test', handler2); const emits2 = [obj.emit('test', 'four'), obj.emit('test', 'five'), obj.emit('test', 'six')]; - return Promise.all(emits2).then(function() { + return Promise.all(emits2).then(function () { expect(handler1.callCount).to.be(emits.length + emits2.length); expect(handler2.callCount).to.be(emits2.length); }); }); }); - it('should pass multiple arguments from the emitter', function() { + it('should pass multiple arguments from the emitter', function () { const obj = new Events(); const handler = sinon.stub(); const payload = ['one', { hello: 'tests' }, null]; obj.on('test', handler); - return obj.emit('test', payload[0], payload[1], payload[2]).then(function() { + return obj.emit('test', payload[0], payload[1], payload[2]).then(function () { expect(handler.callCount).to.be(1); expect(handler.calledWithExactly(payload[0], payload[1], payload[2])).to.be(true); }); }); - it('should preserve the scope of the handler', function() { + it('should preserve the scope of the handler', function () { const obj = new Events(); const expected = 'some value'; let testValue; @@ -185,12 +185,12 @@ describe('Events', function() { handler.getVal = _.constant(expected); obj.on('test', handler); - return obj.emit('test').then(function() { + return obj.emit('test').then(function () { expect(testValue).to.equal(expected); }); }); - it('should always emit in the same order', function() { + it('should always emit in the same order', function () { const handler = sinon.stub(); const obj = new Events(); @@ -208,15 +208,15 @@ describe('Events', function() { obj.emit('block'), obj.emit('block'), obj.emit('last'), - ]).then(function() { + ]).then(function () { expect(handler.callCount).to.be(10); - handler.args.forEach(function(args, i) { + handler.args.forEach(function (args, i) { expect(args[0]).to.be(i < 9 ? 'block' : 'last'); }); }); }); - it('calls emitted handlers asynchronously', done => { + it('calls emitted handlers asynchronously', (done) => { const listenerStub = sinon.stub(); eventsInstance.on('test', listenerStub); eventsInstance.emit('test'); @@ -228,7 +228,7 @@ describe('Events', function() { }, 100); }); - it('calling off after an emit that has not yet triggered the handler, will not call the handler', done => { + it('calling off after an emit that has not yet triggered the handler, will not call the handler', (done) => { const listenerStub = sinon.stub(); eventsInstance.on('test', listenerStub); eventsInstance.emit('test'); diff --git a/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js b/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js index 381b8655ac374..5466e7d43f566 100644 --- a/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js +++ b/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js @@ -31,7 +31,7 @@ describe('kbnAccessibleClick directive', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$compile_, _$rootScope_) { + ngMock.inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; }) @@ -103,7 +103,7 @@ describe('kbnAccessibleClick directive', () => { let scope; let element; - beforeEach(function() { + beforeEach(function () { scope = $rootScope.$new(); scope.handleClick = sinon.stub(); const html = `
`; diff --git a/src/legacy/ui/public/accessibility/angular_aria.js b/src/legacy/ui/public/accessibility/angular_aria.js index 00e773619aa50..4335eddf0d8cd 100644 --- a/src/legacy/ui/public/accessibility/angular_aria.js +++ b/src/legacy/ui/public/accessibility/angular_aria.js @@ -30,7 +30,7 @@ import { uiModules } from '../modules'; * handling keyboard events for `ngClick` directives. Kibana uses `kbnAccessibleClick` to handle * those cases where you need an `ngClick` non button element to have keyboard access. */ -uiModules.get('kibana', ['ngAria']).config($ariaProvider => { +uiModules.get('kibana', ['ngAria']).config(($ariaProvider) => { $ariaProvider.config({ bindKeydown: false, bindRoleForClick: false, diff --git a/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js b/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js index b18464b9ab90f..9ffcbc426e49c 100644 --- a/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js +++ b/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js @@ -71,7 +71,7 @@ uiModules hint.removeClass('kbnUiAceKeyboardHint-isInactive'); } - hint.keydown(ev => { + hint.keydown((ev) => { if (ev.keyCode === keyCodes.ENTER) { ev.preventDefault(); startEditing(); @@ -102,7 +102,7 @@ uiModules { capture: true } ); - uiAceTextbox.keydown(ev => { + uiAceTextbox.keydown((ev) => { if (ev.keyCode === keyCodes.ESCAPE) { // If the autocompletion context menu is open then we want to let ESC close it but // **not** exit out of editing mode. @@ -121,7 +121,7 @@ uiModules element.prepend(hint); }, })) - .directive('kbnUiAceKeyboardMode', kbnUiAceKeyboardModeService => ({ + .directive('kbnUiAceKeyboardMode', (kbnUiAceKeyboardModeService) => ({ restrict: 'A', link(scope, element) { kbnUiAceKeyboardModeService.initialize(scope, element); diff --git a/src/legacy/ui/public/accessibility/scrollto_activedescendant.js b/src/legacy/ui/public/accessibility/scrollto_activedescendant.js index d8883bd5d427b..1034cb1df3dda 100644 --- a/src/legacy/ui/public/accessibility/scrollto_activedescendant.js +++ b/src/legacy/ui/public/accessibility/scrollto_activedescendant.js @@ -30,7 +30,7 @@ uiModules.get('kibana').directive('scrolltoActivedescendant', () => ({ link(scope, element, attrs) { scope.$watch( () => attrs.ariaActivedescendant, - val => { + (val) => { if (val) { const activeDescendant = element.find(`#${val}`); if (activeDescendant.length) { diff --git a/src/legacy/ui/public/binder/__tests__/binder.js b/src/legacy/ui/public/binder/__tests__/binder.js index f30442c86d6ab..de30df36f6b2b 100644 --- a/src/legacy/ui/public/binder/__tests__/binder.js +++ b/src/legacy/ui/public/binder/__tests__/binder.js @@ -24,25 +24,25 @@ import ngMock from 'ng_mock'; import { Binder } from '..'; import $ from 'jquery'; -describe('Binder class', function() { +describe('Binder class', function () { let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($rootScope) { + ngMock.inject(function ($rootScope) { $scope = $rootScope.$new(); }) ); - describe('Constructing with a $scope', function() { - it('accepts a $scope and listens for $destroy', function() { + describe('Constructing with a $scope', function () { + it('accepts a $scope and listens for $destroy', function () { sinon.stub($scope, '$on'); 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() { + it('unbinds when the $scope is destroyed', function () { const binder = new Binder($scope); sinon.stub(binder, 'destroy'); $scope.$destroy(); @@ -50,8 +50,8 @@ describe('Binder class', function() { }); }); - describe('Binder#on', function() { - it('binds to normal event emitters', function() { + describe('Binder#on', function () { + it('binds to normal event emitters', function () { const binder = new Binder(); const emitter = { on: sinon.stub(), @@ -71,8 +71,8 @@ describe('Binder class', function() { }); }); - describe('Binder#jqOn', function() { - it('binds jquery event handlers', function() { + describe('Binder#jqOn', function () { + it('binds jquery event handlers', function () { const binder = new Binder(); const el = document.createElement('div'); const handler = sinon.stub(); diff --git a/src/legacy/ui/public/binder/binder.js b/src/legacy/ui/public/binder/binder.js index 8b0f95ab87fef..0d535d3bdcb0e 100644 --- a/src/legacy/ui/public/binder/binder.js +++ b/src/legacy/ui/public/binder/binder.js @@ -39,7 +39,7 @@ export class Binder extends BinderBase { } fakeD3Bind(el, event, handler) { - this.jqOn(el, event, e => { + this.jqOn(el, event, (e) => { // mimic https://github.com/mbostock/d3/blob/3abb00113662463e5c19eb87cd33f6d0ddc23bc0/src/selection/on.js#L87-L94 const o = d3.event; // Events can be reentrant (e.g., focus). d3.event = e; diff --git a/src/legacy/ui/public/bound_to_config_obj.js b/src/legacy/ui/public/bound_to_config_obj.js index 1bf13b4da951c..dc1eedebe2b77 100644 --- a/src/legacy/ui/public/bound_to_config_obj.js +++ b/src/legacy/ui/public/bound_to_config_obj.js @@ -37,7 +37,7 @@ export function BoundToConfigObjProvider(config) { function BoundToConfigObj(input) { const self = this; - _.forOwn(input, function(value, prop) { + _.forOwn(input, function (value, prop) { if (!_.isString(value) || value.charAt(0) !== '=') { self[prop] = value; return; diff --git a/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx b/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx index b6ffca350239c..90da657cc93e0 100644 --- a/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx +++ b/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx @@ -21,7 +21,7 @@ import React from 'react'; import { UICapabilitiesContext } from './ui_capabilities_context'; import { capabilities } from '..'; -export const UICapabilitiesProvider: React.FC = props => ( +export const UICapabilitiesProvider: React.FC = (props) => ( {props.children} diff --git a/src/legacy/ui/public/chrome/__mocks__/index.js b/src/legacy/ui/public/chrome/__mocks__/index.js index 8f88cf5c65ecf..d6f0df83a0e3d 100644 --- a/src/legacy/ui/public/chrome/__mocks__/index.js +++ b/src/legacy/ui/public/chrome/__mocks__/index.js @@ -27,7 +27,7 @@ const uiSettingsClient = { }; const chrome = { - addBasePath: path => (path ? path : 'test/base/path'), + addBasePath: (path) => (path ? path : 'test/base/path'), breadcrumbs: { set: () => ({}), }, @@ -58,8 +58,8 @@ const internals = _.defaults(_.cloneDeep(metadata), { applicationClasses: [], }); -const waitForBootstrap = new Promise(resolve => { - chrome.bootstrap = function(targetDomElement) { +const waitForBootstrap = new Promise((resolve) => { + chrome.bootstrap = function (targetDomElement) { // import chrome nav controls and hacks now so that they are executed after // everything else, can safely import the chrome, and interact with services // and such setup by all other modules @@ -79,7 +79,7 @@ const waitForBootstrap = new Promise(resolve => { }); chrome.dangerouslyGetActiveInjector = () => { - return waitForBootstrap.then(targetDomElement => { + return waitForBootstrap.then((targetDomElement) => { const $injector = angular.element(targetDomElement).injector(); if (!$injector) { return Promise.reject('targetDomElement had no angular context after bootstrapping'); diff --git a/src/legacy/ui/public/chrome/api/__tests__/apps.js b/src/legacy/ui/public/chrome/api/__tests__/apps.js index 7158b7ef22263..98da8db52bad1 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/apps.js +++ b/src/legacy/ui/public/chrome/api/__tests__/apps.js @@ -21,43 +21,43 @@ import expect from '@kbn/expect'; import setup from '../apps'; -describe('Chrome API :: apps', function() { - describe('#get/setShowAppsLink()', function() { - describe('defaults to false if there are less than two apps', function() { - it('appCount = 0', function() { +describe('Chrome API :: apps', function () { + describe('#get/setShowAppsLink()', function () { + describe('defaults to false if there are less than two apps', function () { + it('appCount = 0', function () { const chrome = {}; setup(chrome, { nav: [] }); expect(chrome.getShowAppsLink()).to.equal(false); }); - it('appCount = 1', function() { + it('appCount = 1', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); expect(chrome.getShowAppsLink()).to.equal(false); }); }); - describe('defaults to true if there are two or more apps', function() { - it('appCount = 2', function() { + describe('defaults to true if there are two or more apps', function () { + it('appCount = 2', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }, { url: '/2' }] }); expect(chrome.getShowAppsLink()).to.equal(true); }); - it('appCount = 3', function() { + it('appCount = 3', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }, { url: '/2' }, { url: '/3' }] }); expect(chrome.getShowAppsLink()).to.equal(true); }); }); - it('is chainable', function() { + it('is chainable', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); expect(chrome.setShowAppsLink(true)).to.equal(chrome); }); - it('can be changed', function() { + it('can be changed', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); @@ -69,8 +69,8 @@ describe('Chrome API :: apps', function() { }); }); - describe('#getApp()', function() { - it('returns a clone of the current app', function() { + describe('#getApp()', function () { + it('returns a clone of the current app', function () { const chrome = {}; const app = { url: '/' }; setup(chrome, { app }); @@ -79,30 +79,30 @@ describe('Chrome API :: apps', function() { expect(chrome.getApp()).to.not.equal(app); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getApp()).to.equal(undefined); }); }); - describe('#getAppTitle()', function() { - it('returns the title property of the current app', function() { + describe('#getAppTitle()', function () { + it('returns the title property of the current app', function () { const chrome = {}; const app = { url: '/', title: 'foo' }; setup(chrome, { app }); expect(chrome.getAppTitle()).to.eql('foo'); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getAppTitle()).to.equal(undefined); }); }); - describe('#getAppUrl()', function() { - it('returns the resolved url of the current app', function() { + describe('#getAppUrl()', function () { + it('returns the resolved url of the current app', function () { const chrome = {}; const app = { navLink: { url: '/foo' } }; setup(chrome, { app }); @@ -112,7 +112,7 @@ describe('Chrome API :: apps', function() { expect(chrome.getAppUrl()).to.equal(a.href); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getAppUrl()).to.equal(undefined); diff --git a/src/legacy/ui/public/chrome/api/__tests__/nav.js b/src/legacy/ui/public/chrome/api/__tests__/nav.js index 877da3539828f..accb56dd42aa3 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/nav.js +++ b/src/legacy/ui/public/chrome/api/__tests__/nav.js @@ -29,7 +29,7 @@ const basePath = '/someBasePath'; function init(customInternals = { basePath }) { const chrome = { - addBasePath: path => path, + addBasePath: (path) => path, getBasePath: () => customInternals.basePath || '', }; const internals = { @@ -40,11 +40,11 @@ function init(customInternals = { basePath }) { return { chrome, internals }; } -describe('chrome nav apis', function() { +describe('chrome nav apis', function () { let coreNavLinks; let fakedLinks = []; - const baseUrl = (function() { + const baseUrl = (function () { const a = document.createElement('a'); a.setAttribute('href', '/'); return a.href.slice(0, a.href.length - 1); @@ -60,7 +60,9 @@ describe('chrome nav apis', function() { return link; }); sinon.stub(coreNavLinks, 'getAll').callsFake(() => fakedLinks); - sinon.stub(coreNavLinks, 'get').callsFake(linkId => fakedLinks.find(({ id }) => id === linkId)); + sinon + .stub(coreNavLinks, 'get') + .callsFake((linkId) => fakedLinks.find(({ id }) => id === linkId)); }); afterEach(() => { @@ -69,12 +71,12 @@ describe('chrome nav apis', function() { coreNavLinks.get.restore(); }); - describe('#untrackNavLinksForDeletedSavedObjects', function() { + describe('#untrackNavLinksForDeletedSavedObjects', function () { const appId = 'appId'; const appUrl = `${baseUrl}/app/kibana#test`; const deletedId = 'IAMDELETED'; - it('should clear last url when last url contains link to deleted saved object', function() { + it('should clear last url when last url contains link to deleted saved object', function () { const appUrlStore = new StubBrowserStorage(); fakedLinks = [ { @@ -92,7 +94,7 @@ describe('chrome nav apis', function() { expect(coreNavLinks.update.calledWith(appId, { url: appUrl })).to.be(true); }); - it('should not clear last url when last url does not contains link to deleted saved object', function() { + it('should not clear last url when last url does not contains link to deleted saved object', function () { const lastUrl = `${appUrl}?id=anotherSavedObjectId`; const appUrlStore = new StubBrowserStorage(); fakedLinks = [ @@ -112,8 +114,8 @@ describe('chrome nav apis', function() { }); }); - describe('chrome.trackSubUrlForApp()', function() { - it('injects a manual app url', function() { + describe('chrome.trackSubUrlForApp()', function () { + it('injects a manual app url', function () { const appUrlStore = new StubBrowserStorage(); fakedLinks = [ { diff --git a/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js b/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js index 0fc4d9c1cdccd..901fbd1d0edf6 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js +++ b/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js @@ -26,14 +26,14 @@ describe('kbn-chrome subUrlRouteFilter()', () => { describe('no ngRoute', () => { beforeEach(ngMock.module('kibana/private')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { expect($injector.has('$route')).to.be(false); }) ); it( 'always returns true when there is no $route service', - ngMock.inject(Private => { + ngMock.inject((Private) => { const subUrlRouteFilter = Private(SubUrlRouteFilterProvider); expect(subUrlRouteFilter()).to.be(true); }) @@ -42,7 +42,7 @@ describe('kbn-chrome subUrlRouteFilter()', () => { describe('with ngRoute', () => { beforeEach( - ngMock.module('kibana/private', 'ngRoute', $routeProvider => { + ngMock.module('kibana/private', 'ngRoute', ($routeProvider) => { $routeProvider.when('/foo', { redirectTo: '/bar', }); diff --git a/src/legacy/ui/public/chrome/api/__tests__/xsrf.js b/src/legacy/ui/public/chrome/api/__tests__/xsrf.js index 54ecd4ee2ca1c..3197b79f407da 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/xsrf.js +++ b/src/legacy/ui/public/chrome/api/__tests__/xsrf.js @@ -24,15 +24,15 @@ import { initChromeXsrfApi } from '../xsrf'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { version } from '../../../../../../core/server/utils/package_json'; -describe('chrome xsrf apis', function() { +describe('chrome xsrf apis', function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe('#getXsrfToken()', function() { - it('exposes the token', function() { + describe('#getXsrfToken()', function () { + it('exposes the token', function () { const chrome = {}; initChromeXsrfApi(chrome, { version }); expect(chrome.getXsrfToken()).to.be(version); diff --git a/src/legacy/ui/public/chrome/api/angular.js b/src/legacy/ui/public/chrome/api/angular.js index bad6e5f12f0d7..a9113b2df2ed7 100644 --- a/src/legacy/ui/public/chrome/api/angular.js +++ b/src/legacy/ui/public/chrome/api/angular.js @@ -25,7 +25,7 @@ import { configureAppAngularModule } from 'ui/legacy_compat'; import { npStart } from '../../new_platform/new_platform'; export function initAngularApi(chrome, internals) { - chrome.setupAngular = function() { + chrome.setupAngular = function () { const kibana = uiModules.get('kibana'); configureAppAngularModule(kibana, npStart.core, false); diff --git a/src/legacy/ui/public/chrome/api/apps.js b/src/legacy/ui/public/chrome/api/apps.js index 23eb84fda97a3..c4cbe7be6f1c3 100644 --- a/src/legacy/ui/public/chrome/api/apps.js +++ b/src/legacy/ui/public/chrome/api/apps.js @@ -21,7 +21,7 @@ import { clone, get } from 'lodash'; import { resolve } from 'url'; // eslint-disable-next-line import/no-default-export -export default function(chrome, internals) { +export default function (chrome, internals) { if (get(internals, 'app.navLink.url')) { internals.app.navLink.url = resolve(window.location.href, internals.app.navLink.url); } @@ -48,36 +48,36 @@ export default function(chrome, internals) { * than one app installed. */ - chrome.setShowAppsLink = function(val) { + chrome.setShowAppsLink = function (val) { internals.showAppsLink = !!val; return chrome; }; - chrome.getShowAppsLink = function() { + chrome.getShowAppsLink = function () { return internals.showAppsLink == null ? internals.nav.length > 1 : internals.showAppsLink; }; - chrome.getKibanaVersion = function() { + chrome.getKibanaVersion = function () { return internals.version; }; - chrome.getApp = function() { + chrome.getApp = function () { return clone(internals.app); }; - chrome.getAppTitle = function() { + chrome.getAppTitle = function () { return get(internals, ['app', 'title']); }; - chrome.getAppUrl = function() { + chrome.getAppUrl = function () { return get(internals, ['app', 'navLink', 'url']); }; - chrome.getLastUrlFor = function(appId) { + chrome.getLastUrlFor = function (appId) { return internals.appUrlStore.getItem(`appLastUrl:${appId}`); }; - chrome.setLastUrlFor = function(appId, url) { + chrome.setLastUrlFor = function (appId, url) { internals.appUrlStore.setItem(`appLastUrl:${appId}`, url); }; } diff --git a/src/legacy/ui/public/chrome/api/nav.ts b/src/legacy/ui/public/chrome/api/nav.ts index ae32473e451b7..2b655419d98aa 100644 --- a/src/legacy/ui/public/chrome/api/nav.ts +++ b/src/legacy/ui/public/chrome/api/nav.ts @@ -41,13 +41,13 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { */ chrome.untrackNavLinksForDeletedSavedObjects = (deletedIds: string[]) => { function urlContainsDeletedId(url: string) { - const includedId = deletedIds.find(deletedId => { + const includedId = deletedIds.find((deletedId) => { return url.includes(deletedId); }); return includedId !== undefined; } - coreNavLinks.getAll().forEach(link => { + coreNavLinks.getAll().forEach((link) => { if (link.linkToLastSubUrl && urlContainsDeletedId(link.url!)) { setLastUrl(link, link.baseUrl); } @@ -72,14 +72,14 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { } }; - internals.trackPossibleSubUrl = async function(url: string) { + internals.trackPossibleSubUrl = async function (url: string) { const kibanaParsedUrl = absoluteToParsedUrl(url, chrome.getBasePath()); coreNavLinks .getAll() // Filter only legacy links - .filter(link => link.legacy && !link.disableSubUrlTracking) - .forEach(link => { + .filter((link) => link.legacy && !link.disableSubUrlTracking) + .forEach((link) => { const active = url.startsWith(link.subUrlBase!); link = coreNavLinks.update(link.id, { active })!; @@ -146,8 +146,8 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { // link.active and link.lastUrl properties coreNavLinks .getAll() - .filter(link => link.subUrlBase && !link.disableSubUrlTracking) - .forEach(link => { + .filter((link) => link.subUrlBase && !link.disableSubUrlTracking) + .forEach((link) => { coreNavLinks.update(link.id, { subUrlBase: relativeToAbsolute(chrome.addBasePath(link.subUrlBase)), }); diff --git a/src/legacy/ui/public/chrome/api/saved_object_client.ts b/src/legacy/ui/public/chrome/api/saved_object_client.ts index b42e74e5a5865..76d4e301e3c77 100644 --- a/src/legacy/ui/public/chrome/api/saved_object_client.ts +++ b/src/legacy/ui/public/chrome/api/saved_object_client.ts @@ -23,7 +23,7 @@ import { Chrome } from '..'; const savedObjectsClient = npStart.core.savedObjects.client; export function initSavedObjectClient(chrome: Chrome) { - chrome.getSavedObjectsClient = function() { + chrome.getSavedObjectsClient = function () { return savedObjectsClient; }; } diff --git a/src/legacy/ui/public/chrome/api/template.js b/src/legacy/ui/public/chrome/api/template.js index 8c3100ab87a27..d29a7eba7316f 100644 --- a/src/legacy/ui/public/chrome/api/template.js +++ b/src/legacy/ui/public/chrome/api/template.js @@ -18,7 +18,7 @@ */ // eslint-disable-next-line import/no-default-export -export default function(chrome, internals) { +export default function (chrome, internals) { /** * ui/chrome Template API * @@ -48,7 +48,7 @@ export default function(chrome, internals) { * @param {string} template * @return {chrome} */ - chrome.setRootTemplate = function(template) { + chrome.setRootTemplate = function (template) { internals.rootTemplate = template; return chrome; }; @@ -58,7 +58,7 @@ export default function(chrome, internals) { * @param {Function} controller - the controller initializer function * @return {chrome} */ - chrome.setRootController = function(as, controllerName) { + chrome.setRootController = function (as, controllerName) { if (controllerName === undefined) { controllerName = as; as = null; diff --git a/src/legacy/ui/public/chrome/api/ui_settings.js b/src/legacy/ui/public/chrome/api/ui_settings.js index bd5c7a39b17ed..dbdd6a9c12653 100644 --- a/src/legacy/ui/public/chrome/api/ui_settings.js +++ b/src/legacy/ui/public/chrome/api/ui_settings.js @@ -22,7 +22,7 @@ import { npSetup } from 'ui/new_platform'; const newPlatformUiSettingsClient = npSetup.core.uiSettings; export function initUiSettingsApi(chrome) { - chrome.getUiSettingsClient = function() { + chrome.getUiSettingsClient = function () { return newPlatformUiSettingsClient; }; } diff --git a/src/legacy/ui/public/chrome/api/xsrf.js b/src/legacy/ui/public/chrome/api/xsrf.js index 56a69696a3464..5086903604667 100644 --- a/src/legacy/ui/public/chrome/api/xsrf.js +++ b/src/legacy/ui/public/chrome/api/xsrf.js @@ -18,7 +18,7 @@ */ export function initChromeXsrfApi(chrome, internals) { - chrome.getXsrfToken = function() { + chrome.getXsrfToken = function () { return internals.version; }; } diff --git a/src/legacy/ui/public/chrome/chrome.js b/src/legacy/ui/public/chrome/chrome.js index 7a75ad906a870..0640017f7806a 100644 --- a/src/legacy/ui/public/chrome/chrome.js +++ b/src/legacy/ui/public/chrome/chrome.js @@ -79,8 +79,8 @@ initChromeThemeApi(chrome); npStart.core.chrome.setAppTitle(chrome.getAppTitle()); -const waitForBootstrap = new Promise(resolve => { - chrome.bootstrap = function(targetDomElement) { +const waitForBootstrap = new Promise((resolve) => { + chrome.bootstrap = function (targetDomElement) { // import chrome nav controls and hacks now so that they are executed after // everything else, can safely import the chrome, and interact with services // and such setup by all other modules @@ -114,7 +114,7 @@ const waitForBootstrap = new Promise(resolve => { * tests. Look into 'src/test_utils/public/stub_get_active_injector' for more information. */ chrome.dangerouslyGetActiveInjector = () => { - return waitForBootstrap.then(targetDomElement => { + return waitForBootstrap.then((targetDomElement) => { const $injector = angular.element(targetDomElement).injector(); if (!$injector) { return Promise.reject('targetDomElement had no angular context after bootstrapping'); diff --git a/src/legacy/ui/public/chrome/directives/kbn_chrome.js b/src/legacy/ui/public/chrome/directives/kbn_chrome.js index 45da4ab6b7472..5ba34e553201e 100644 --- a/src/legacy/ui/public/chrome/directives/kbn_chrome.js +++ b/src/legacy/ui/public/chrome/directives/kbn_chrome.js @@ -60,13 +60,13 @@ export function kbnChromeProvider(chrome, internals) { // Continue to support legacy nav controls not registered with the NP. const navControls = Private(chromeHeaderNavControlsRegistry); - (navControls.bySide[NavControlSide.Left] || []).forEach(navControl => + (navControls.bySide[NavControlSide.Left] || []).forEach((navControl) => npStart.core.chrome.navControls.registerLeft({ order: navControl.order, mount: navControl.render, }) ); - (navControls.bySide[NavControlSide.Right] || []).forEach(navControl => + (navControls.bySide[NavControlSide.Right] || []).forEach((navControl) => npStart.core.chrome.navControls.registerRight({ order: navControl.order, mount: navControl.render, diff --git a/src/legacy/ui/public/config/__tests__/config.js b/src/legacy/ui/public/config/__tests__/config.js index 843fa864453fd..90dbdaf264a29 100644 --- a/src/legacy/ui/public/config/__tests__/config.js +++ b/src/legacy/ui/public/config/__tests__/config.js @@ -31,7 +31,7 @@ describe('Config service', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { config = $injector.get('config'); uiSettings = chrome.getUiSettingsClient(); $q = $injector.get('$q'); @@ -191,8 +191,8 @@ describe('Config service', () => { it('synchronously emits events when changes are outside a digest cycle', async () => { const stub = sinon.stub(); - await new Promise(resolve => { - setTimeout(function() { + await new Promise((resolve) => { + setTimeout(function () { const off = $rootScope.$on('change:config.foobar', stub); config.set('foobar', 'baz'); // we unlisten to make sure that stub is not called before our assertions below diff --git a/src/legacy/ui/public/config/config.js b/src/legacy/ui/public/config/config.js index 80a9d39221b2c..a8f24c126caff 100644 --- a/src/legacy/ui/public/config/config.js +++ b/src/legacy/ui/public/config/config.js @@ -31,7 +31,7 @@ const module = uiModules.get('kibana/config'); * to expose the exact same API as the config service that has existed since forever. * @name config */ -module.service(`config`, function($rootScope, Promise) { +module.service(`config`, function ($rootScope, Promise) { const uiSettings = chrome.getUiSettingsClient(); // direct bind sync methods @@ -43,7 +43,7 @@ module.service(`config`, function($rootScope, Promise) { this.isOverridden = (...args) => uiSettings.isOverridden(...args); // modify remove() to use angular Promises - this.remove = key => Promise.resolve(uiSettings.remove(key)); + this.remove = (key) => Promise.resolve(uiSettings.remove(key)); // modify set() to use angular Promises and angular.toJson() this.set = (key, value) => @@ -66,7 +66,7 @@ module.service(`config`, function($rootScope, Promise) { ); $rootScope.$on('$destroy', () => subscription.unsubscribe()); - this.watchAll = function(handler, scope = $rootScope) { + this.watchAll = function (handler, scope = $rootScope) { // call handler immediately to initialize handler(null, null, null, this); @@ -75,7 +75,7 @@ module.service(`config`, function($rootScope, Promise) { }); }; - this.watch = function(key, handler, scope = $rootScope) { + this.watch = function (key, handler, scope = $rootScope) { if (!this.isDeclared(key)) { throw new Error(`Unexpected \`config.watch("${key}", fn)\` call on unrecognized configuration setting "${key}". Setting an initial value via \`config.set("${key}", value)\` before binding @@ -100,8 +100,8 @@ any custom setting configuration watchers for "${key}" may fix this issue.`); * be stored. Defaults to the config key * @return {function} - an unbind function */ - this.bindToScope = function(scope, key, property = key) { - const onUpdate = newVal => { + this.bindToScope = function (scope, key, property = key) { + const onUpdate = (newVal) => { scope[property] = newVal; }; diff --git a/src/legacy/ui/public/directives/__tests__/input_focus.js b/src/legacy/ui/public/directives/__tests__/input_focus.js index 840803c4d28a0..45b1821cbfd21 100644 --- a/src/legacy/ui/public/directives/__tests__/input_focus.js +++ b/src/legacy/ui/public/directives/__tests__/input_focus.js @@ -22,7 +22,7 @@ import ngMock from 'ng_mock'; import $ from 'jquery'; import '../input_focus'; -describe('Input focus directive', function() { +describe('Input focus directive', function () { let $compile; let $rootScope; let $timeout; @@ -34,7 +34,7 @@ describe('Input focus directive', function() { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$compile_, _$rootScope_, _$timeout_) { + ngMock.inject(function (_$compile_, _$rootScope_, _$timeout_) { $compile = _$compile_; $rootScope = _$rootScope_; $timeout = _$timeout_; @@ -44,7 +44,7 @@ describe('Input focus directive', function() { }) ); - afterEach(function() { + afterEach(function () { $el.remove(); $el = null; }); @@ -61,25 +61,25 @@ describe('Input focus directive', function() { } } - it('should focus the input', function() { + it('should focus the input', function () { renderEl(''); expect(selectedEl).to.equal(element[0]); expect(selectedText.length).to.equal(0); }); - it('should select the text in the input', function() { + it('should select the text in the input', function () { renderEl(''); expect(selectedEl).to.equal(element[0]); expect(selectedText.length).to.equal(inputValue.length); expect(selectedText).to.equal(inputValue); }); - it('should not focus the input if disable-input-focus is set to true on the same element', function() { + it('should not focus the input if disable-input-focus is set to true on the same element', function () { renderEl(''); expect(selectedEl).not.to.be(element[0]); }); - it('should still focus the input if disable-input-focus is falsy', function() { + it('should still focus the input if disable-input-focus is falsy', function () { renderEl(''); expect(selectedEl).to.be(element[0]); }); diff --git a/src/legacy/ui/public/directives/bind/__tests__/bind.js b/src/legacy/ui/public/directives/bind/__tests__/bind.js index 1d2b46b2e0523..658a726e8c4cf 100644 --- a/src/legacy/ui/public/directives/bind/__tests__/bind.js +++ b/src/legacy/ui/public/directives/bind/__tests__/bind.js @@ -19,19 +19,19 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('$scope.$bind', function() { +describe('$scope.$bind', function () { let $rootScope; let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); }) ); - it('exposes $bind on all scopes', function() { + it('exposes $bind on all scopes', function () { expect($rootScope.$bind).to.be.a('function'); expect($scope).to.have.property('$bind', $rootScope.$bind); @@ -39,7 +39,7 @@ describe('$scope.$bind', function() { expect($isoScope).to.have.property('$bind', $rootScope.$bind); }); - it("sets up binding from a parent scope to it's child", function() { + it("sets up binding from a parent scope to it's child", function () { $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); expect($scope.localVal).to.be('foo'); @@ -51,7 +51,7 @@ describe('$scope.$bind', function() { expect($scope.localVal).to.be('bar'); }); - it('sets up a binding from the child to the parent scope', function() { + it('sets up a binding from the child to the parent scope', function () { $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); expect($scope.localVal).to.be('foo'); @@ -63,7 +63,7 @@ describe('$scope.$bind', function() { expect($rootScope.val).to.be('bar'); }); - it('pulls from the scopes $parent by default', function() { + it('pulls from the scopes $parent by default', function () { const $parent = $rootScope.$new(); const $self = $parent.$new(); @@ -74,7 +74,7 @@ describe('$scope.$bind', function() { expect($self.localVal).to.be('foo'); }); - it('accepts an alternate scope to read from', function() { + it('accepts an alternate scope to read from', function () { const $parent = $rootScope.$new(); const $self = $parent.$new(); diff --git a/src/legacy/ui/public/directives/bind/bind.js b/src/legacy/ui/public/directives/bind/bind.js index 490816501564d..a9210cace5cea 100644 --- a/src/legacy/ui/public/directives/bind/bind.js +++ b/src/legacy/ui/public/directives/bind/bind.js @@ -20,7 +20,7 @@ import angular from 'angular'; import { uiModules } from '../../modules'; -uiModules.get('kibana').config(function($provide) { +uiModules.get('kibana').config(function ($provide) { function strictEquality(a, b) { // are the values equal? or, are they both NaN? return a === b || (a !== a && b !== b); @@ -37,7 +37,7 @@ uiModules.get('kibana').config(function($provide) { ); } - $provide.decorator('$rootScope', function($delegate, $parse) { + $provide.decorator('$rootScope', function ($delegate, $parse) { /** * Two-way bind a value from scope to another property on scope. This * allow values on scope that work like they do in an isolate scope, but @@ -48,7 +48,7 @@ uiModules.get('kibana').config(function($provide) { * @param {Scope} $sourceScope - the scope to read "from" expression from * @return {undefined} */ - $delegate.constructor.prototype.$bind = function(to, from, $sourceScope) { + $delegate.constructor.prototype.$bind = function (to, from, $sourceScope) { const $source = $sourceScope || this.$parent; const $target = this; @@ -58,16 +58,16 @@ uiModules.get('kibana').config(function($provide) { const $from = $parse(from); // bind scopes to expressions - const getTarget = function() { + const getTarget = function () { return $to($target); }; - const setTarget = function(v) { + const setTarget = function (v) { return $to.assign($target, v); }; - const getSource = function() { + const getSource = function () { return $from($source); }; - const setSource = function(v) { + const setSource = function (v) { return $from.assignOrFail($source, v); }; @@ -80,7 +80,7 @@ uiModules.get('kibana').config(function($provide) { $from.assignOrFail = $from.assign || - function() { + function () { // revert the change and throw an error, child writes aren't supported $to($target, (lastSourceVal = $from($source))); errorNotAssignable(from, to); @@ -94,7 +94,7 @@ uiModules.get('kibana').config(function($provide) { setTarget(lastSourceVal); $target.$watch( - function() { + function () { const sourceVal = getSource(); const targetVal = getTarget(); diff --git a/src/legacy/ui/public/directives/input_focus.js b/src/legacy/ui/public/directives/input_focus.js index d9f744cb77de1..f047ff2547ba2 100644 --- a/src/legacy/ui/public/directives/input_focus.js +++ b/src/legacy/ui/public/directives/input_focus.js @@ -20,13 +20,13 @@ import { uiModules } from '../modules'; const module = uiModules.get('kibana'); -module.directive('inputFocus', function($parse, $timeout) { +module.directive('inputFocus', function ($parse, $timeout) { return { restrict: 'A', - link: function($scope, $elem, attrs) { + link: function ($scope, $elem, attrs) { const isDisabled = attrs.disableInputFocus && $parse(attrs.disableInputFocus)($scope); if (!isDisabled) { - $timeout(function() { + $timeout(function () { $elem.focus(); if (attrs.inputFocus === 'select') $elem.select(); }); diff --git a/src/legacy/ui/public/directives/kbn_href.js b/src/legacy/ui/public/directives/kbn_href.js index d7a5f886fd4e0..5c71396e6c4de 100644 --- a/src/legacy/ui/public/directives/kbn_href.js +++ b/src/legacy/ui/public/directives/kbn_href.js @@ -23,11 +23,11 @@ import { words, kebabCase } from 'lodash'; export function kbnUrlDirective(name) { const attr = kebabCase(words(name).slice(1)); - uiModules.get('kibana').directive(name, function(chrome) { + uiModules.get('kibana').directive(name, function (chrome) { return { restrict: 'A', - link: function($scope, $el, $attr) { - $attr.$observe(name, function(val) { + link: function ($scope, $el, $attr) { + $attr.$observe(name, function (val) { $attr.$set(attr, chrome.addBasePath(val)); }); }, diff --git a/src/legacy/ui/public/directives/listen/__tests__/listen.js b/src/legacy/ui/public/directives/listen/__tests__/listen.js index 7aa1a2d0e430c..9a1d482956154 100644 --- a/src/legacy/ui/public/directives/listen/__tests__/listen.js +++ b/src/legacy/ui/public/directives/listen/__tests__/listen.js @@ -23,24 +23,24 @@ import ngMock from 'ng_mock'; import '..'; import { EventsProvider } from '../../../events'; -describe('listen component', function() { +describe('listen component', function () { let $rootScope; let Events; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector, Private) { + ngMock.inject(function ($injector, Private) { $rootScope = $injector.get('$rootScope'); Events = Private(EventsProvider); }) ); - it('exposes the $listen method on all scopes', function() { + it('exposes the $listen method on all scopes', function () { expect($rootScope.$listen).to.be.a('function'); expect($rootScope.$new().$listen).to.be.a('function'); }); - it('binds to an event emitter', function() { + it('binds to an event emitter', function () { const emitter = new Events(); const $scope = $rootScope.$new(); @@ -51,7 +51,7 @@ describe('listen component', function() { expect(emitter._listeners.hello[0].handler).to.be(handler); }); - it('binds to $scope, waiting for the destroy event', function() { + it('binds to $scope, waiting for the destroy event', function () { const emitter = new Events(); const $scope = $rootScope.$new(); @@ -69,7 +69,7 @@ describe('listen component', function() { expect(call.args[1]).to.be.a('function'); }); - it('unbinds the event handler when $destroy is triggered', function() { + it('unbinds the event handler when $destroy is triggered', function () { const emitter = new Events(); const $scope = $rootScope.$new(); diff --git a/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js b/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js index 313f9e12b017a..a604eca52affe 100644 --- a/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js +++ b/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js @@ -27,10 +27,10 @@ let init; let $rootScope; let $compile; -describe('render_directive', function() { +describe('render_directive', function () { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $compile = $injector.get('$compile'); init = function init(markup = '', definition = {}) { @@ -55,14 +55,14 @@ describe('render_directive', function() { }) ); - describe('directive requirements', function() { - it('should throw if not given a definition', function() { + describe('directive requirements', function () { + it('should throw if not given a definition', function () { expect(() => init('', null)).to.throwException(/must have a definition/); }); }); - describe('rendering with definition', function() { - it('should call link method', function() { + describe('rendering with definition', function () { + it('should call link method', function () { const markup = '

hello world

'; const definition = { link: sinon.stub(), @@ -73,7 +73,7 @@ describe('render_directive', function() { sinon.assert.callCount(definition.link, 1); }); - it('should call controller method', function() { + it('should call controller method', function () { const markup = '

hello world

'; const definition = { controller: sinon.stub(), @@ -85,8 +85,8 @@ describe('render_directive', function() { }); }); - describe('definition scope binding', function() { - it('should accept two-way, attribute, and expression binding directives', function() { + describe('definition scope binding', function () { + it('should accept two-way, attribute, and expression binding directives', function () { const $el = angular.element(` { if (!bindingRE.test(binding)) { throw new Error(`Invalid scope binding "${binding}". Expected it to match ${bindingRE}`); @@ -44,7 +44,7 @@ export function ApplyScopeBindingsProvider($parse) { case '&': if (attr) { const getter = $parse(attr); - $scope[local] = function() { + $scope[local] = function () { return getter($scope.$parent); }; } else { @@ -53,7 +53,7 @@ export function ApplyScopeBindingsProvider($parse) { break; case '@': $scope[local] = attr; - $attrs.$observe(attribute, v => ($scope[local] = v)); + $attrs.$observe(attribute, (v) => ($scope[local] = v)); break; } }); diff --git a/src/legacy/ui/public/directives/render_directive/render_directive.js b/src/legacy/ui/public/directives/render_directive/render_directive.js index 1d28377ef9126..a5232f39b82c3 100644 --- a/src/legacy/ui/public/directives/render_directive/render_directive.js +++ b/src/legacy/ui/public/directives/render_directive/render_directive.js @@ -43,7 +43,7 @@ import { ApplyScopeBindingsProvider } from './apply_scope_bindings'; * @param [Object|Function] definition.link - either a post link function or an object with pre and/or * post link functions. */ -uiModules.get('kibana').directive('renderDirective', function(Private) { +uiModules.get('kibana').directive('renderDirective', function (Private) { const applyScopeBindings = Private(ApplyScopeBindingsProvider); return { @@ -51,10 +51,10 @@ uiModules.get('kibana').directive('renderDirective', function(Private) { scope: { definition: '=', }, - template: function($el) { + template: function ($el) { return $el.html(); }, - controller: function($scope, $element, $attrs, $transclude, $injector) { + controller: function ($scope, $element, $attrs, $transclude, $injector) { if (!$scope.definition) throw new Error('render-directive must have a definition attribute'); const { controller, controllerAs, scope } = $scope.definition; diff --git a/src/legacy/ui/public/directives/storage/index.js b/src/legacy/ui/public/directives/storage/index.js index 80e4c3b645108..7c195ecc85d2f 100644 --- a/src/legacy/ui/public/directives/storage/index.js +++ b/src/legacy/ui/public/directives/storage/index.js @@ -20,8 +20,8 @@ import { uiModules } from '../../modules'; import { Storage } from '../../../../../plugins/kibana_utils/public'; -const createService = function(type) { - return function($window) { +const createService = function (type) { + return function ($window) { return new Storage($window[type]); }; }; diff --git a/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js b/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js index 7aab953c55ac7..0de41a5ae57cb 100644 --- a/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js +++ b/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js @@ -22,20 +22,20 @@ import ngMock from 'ng_mock'; import expect from '@kbn/expect'; import sinon from 'sinon'; -describe('$scope.$watchMulti', function() { +describe('$scope.$watchMulti', function () { let $rootScope; let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); }) ); - describe('basic functionality', function() { - it('exposes $watchMulti on all scopes', function() { + describe('basic functionality', function () { + it('exposes $watchMulti on all scopes', function () { expect($rootScope.$watchMulti).to.be.a('function'); expect($scope).to.have.property('$watchMulti', $rootScope.$watchMulti); @@ -43,11 +43,11 @@ describe('$scope.$watchMulti', function() { expect($isoScope).to.have.property('$watchMulti', $rootScope.$watchMulti); }); - it('returns a working unwatch function', function() { + it('returns a working unwatch function', function () { $scope.a = 0; $scope.b = 0; let triggers = 0; - const unwatch = $scope.$watchMulti(['a', 'b'], function() { + const unwatch = $scope.$watchMulti(['a', 'b'], function () { triggers++; }); @@ -72,8 +72,8 @@ describe('$scope.$watchMulti', function() { }); }); - describe('simple scope watchers', function() { - it('only triggers a single watch on initialization', function() { + describe('simple scope watchers', function () { + it('only triggers a single watch on initialization', function () { const stub = sinon.stub(); $scope.$watchMulti(['one', 'two', 'three'], stub); @@ -82,8 +82,8 @@ describe('$scope.$watchMulti', function() { expect(stub.callCount).to.be(1); }); - it('only triggers a single watch when multiple values change', function() { - const stub = sinon.spy(function() {}); + it('only triggers a single watch when multiple values change', function () { + const stub = sinon.spy(function () {}); $scope.$watchMulti(['one', 'two', 'three'], stub); @@ -98,8 +98,8 @@ describe('$scope.$watchMulti', function() { expect(stub.callCount).to.be(2); }); - it('passes an array of the current and previous values, in order', function() { - const stub = sinon.spy(function() {}); + it('passes an array of the current and previous values, in order', function () { + const stub = sinon.spy(function () {}); $scope.one = 'a'; $scope.two = 'b'; @@ -123,17 +123,17 @@ describe('$scope.$watchMulti', function() { ]); }); - it('always has an up to date value', function() { + it('always has an up to date value', function () { let count = 0; $scope.vals = [1, 0]; - $scope.$watchMulti(['vals[0]', 'vals[1]'], function(cur) { + $scope.$watchMulti(['vals[0]', 'vals[1]'], function (cur) { expect(cur).to.eql($scope.vals); count++; }); const $child = $scope.$new(); - $child.$watch('vals[0]', function(cur) { + $child.$watch('vals[0]', function (cur) { $child.vals[1] = cur; }); @@ -142,17 +142,17 @@ describe('$scope.$watchMulti', function() { }); }); - describe('complex watch expressions', function() { + describe('complex watch expressions', function () { let stateWatchers; let firstValue; let secondValue; - beforeEach(function() { - const firstGetter = function() { + beforeEach(function () { + const firstGetter = function () { return firstValue; }; - const secondGetter = function() { + const secondGetter = function () { return secondValue; }; @@ -168,7 +168,7 @@ describe('$scope.$watchMulti', function() { ]; }); - it('should trigger the watcher on initialization', function() { + it('should trigger the watcher on initialization', function () { const stub = sinon.stub(); firstValue = 'first'; secondValue = 'second'; @@ -183,8 +183,8 @@ describe('$scope.$watchMulti', function() { }); }); - describe('nested watchers', function() { - it('should trigger the handler at least once', function() { + describe('nested watchers', function () { + it('should trigger the handler at least once', function () { const $scope = $rootScope.$new(); $scope.$$watchers = [ { @@ -205,7 +205,7 @@ describe('$scope.$watchMulti', function() { const second = sinon.stub(); function registerWatchers() { - $scope.$watchMulti([first, second], function() { + $scope.$watchMulti([first, second], function () { expect(first.callCount).to.be.greaterThan(0); expect(second.callCount).to.be.greaterThan(0); }); diff --git a/src/legacy/ui/public/doc_title/__tests__/doc_title.js b/src/legacy/ui/public/doc_title/__tests__/doc_title.js index 8e4af5aa11dc3..fa8b83f755957 100644 --- a/src/legacy/ui/public/doc_title/__tests__/doc_title.js +++ b/src/legacy/ui/public/doc_title/__tests__/doc_title.js @@ -23,38 +23,38 @@ import ngMock from 'ng_mock'; import { docTitle } from '../doc_title'; import { npStart } from '../../new_platform'; -describe('docTitle Service', function() { +describe('docTitle Service', function () { let initialDocTitle; const MAIN_TITLE = 'Kibana 4'; let $rootScope; - beforeEach(function() { + beforeEach(function () { initialDocTitle = document.title; document.title = MAIN_TITLE; npStart.core.chrome.docTitle.__legacy.setBaseTitle(MAIN_TITLE); }); - afterEach(function() { + afterEach(function () { document.title = initialDocTitle; npStart.core.chrome.docTitle.__legacy.setBaseTitle(initialDocTitle); }); beforeEach( - ngMock.module('kibana', function($provide) { + ngMock.module('kibana', function ($provide) { $provide.decorator('$rootScope', decorateWithSpy('$on')); }) ); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); }) ); - describe('setup', function() { - it('resets the title when a route change begins', function() { + describe('setup', function () { + it('resets the title when a route change begins', function () { const spy = $rootScope.$on; - const found = spy.args.some(function(args) { + const found = spy.args.some(function (args) { return args[0] === '$routeChangeStart' && args[1] === docTitle.reset; }); @@ -64,8 +64,8 @@ describe('docTitle Service', function() { }); }); - describe('#reset', function() { - it('clears the internal state', function() { + describe('#reset', function () { + it('clears the internal state', function () { docTitle.change('some title'); expect(document.title).to.be('some title - ' + MAIN_TITLE); @@ -74,8 +74,8 @@ describe('docTitle Service', function() { }); }); - describe('#change', function() { - it('writes the first param to as the first part of the doc name', function() { + describe('#change', function () { + it('writes the first param to as the first part of the doc name', function () { expect(document.title).to.be(MAIN_TITLE); docTitle.change('some secondary title'); expect(document.title).to.be('some secondary title - ' + MAIN_TITLE); @@ -83,7 +83,7 @@ describe('docTitle Service', function() { }); function decorateWithSpy(prop) { - return function($delegate) { + return function ($delegate) { sinon.spy($delegate, prop); return $delegate; }; diff --git a/src/legacy/ui/public/doc_title/doc_title.js b/src/legacy/ui/public/doc_title/doc_title.js index 5d0d63380f152..096e49e7a6de8 100644 --- a/src/legacy/ui/public/doc_title/doc_title.js +++ b/src/legacy/ui/public/doc_title/doc_title.js @@ -36,7 +36,7 @@ export const docTitle = { reset, }; -uiModules.get('kibana').run(function($rootScope) { +uiModules.get('kibana').run(function ($rootScope) { // always bind to the route events $rootScope.$on('$routeChangeStart', docTitle.reset); }); diff --git a/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js b/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js index 0e38ec998d62e..6c9cdd12422cf 100644 --- a/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js +++ b/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js @@ -23,8 +23,8 @@ import { metadata } from '../../metadata'; const urlVersion = metadata.branch; -describe('documentation link service', function() { - it("should inject Kibana's major.minor version into doc links", function() { +describe('documentation link service', function () { + it("should inject Kibana's major.minor version into doc links", function () { expect(documentationLinks.filebeat.configuration).to.contain(urlVersion); }); }); diff --git a/src/legacy/ui/public/dom_location.js b/src/legacy/ui/public/dom_location.js index 18411f3f66ed0..baf03ba4c4b1c 100644 --- a/src/legacy/ui/public/dom_location.js +++ b/src/legacy/ui/public/dom_location.js @@ -19,7 +19,7 @@ export function DomLocationProvider($window) { return { - reload: function(forceFetch) { + reload: function (forceFetch) { $window.location.reload(forceFetch); }, diff --git a/src/legacy/ui/public/events.js b/src/legacy/ui/public/events.js index 00c92038e7c9f..1dc8a71afb193 100644 --- a/src/legacy/ui/public/events.js +++ b/src/legacy/ui/public/events.js @@ -45,7 +45,7 @@ export function EventsProvider(Promise) { * @param {function} handler - The function to call when the event is triggered * @return {Events} - this, for chaining */ - Events.prototype.on = function(name, handler) { + Events.prototype.on = function (name, handler) { if (!Array.isArray(this._listeners[name])) { this._listeners[name] = []; } @@ -57,11 +57,11 @@ export function EventsProvider(Promise) { (function rebuildDefer() { listener.defer = createDefer(Promise); - listener.resolved = listener.defer.promise.then(function(args) { + listener.resolved = listener.defer.promise.then(function (args) { rebuildDefer(); // we ignore the completion of handlers, just watch for unhandled errors - Promise.resolve(handler.apply(handler, args)).catch(error => fatalError(error, location)); + Promise.resolve(handler.apply(handler, args)).catch((error) => fatalError(error, location)); // indicate to bluebird not to worry about this promise being a "runaway" return null; @@ -77,7 +77,7 @@ export function EventsProvider(Promise) { * @param {function} [handler] - The handler to remove * @return {Events} - this, for chaining */ - Events.prototype.off = function(name, handler) { + Events.prototype.off = function (name, handler) { if (!name && !handler) { this._listeners = {}; return this.removeAllListeners(); @@ -90,7 +90,7 @@ export function EventsProvider(Promise) { if (!handler) { delete this._listeners[name]; } else { - this._listeners[name] = _.filter(this._listeners[name], function(listener) { + this._listeners[name] = _.filter(this._listeners[name], function (listener) { return handler !== listener.handler; }); } @@ -105,7 +105,7 @@ export function EventsProvider(Promise) { * @param {any} [value] - The value that will be passed to all event handlers. * @returns {Promise} */ - Events.prototype.emit = function(name) { + Events.prototype.emit = function (name) { const self = this; const args = _.rest(arguments); @@ -113,8 +113,8 @@ export function EventsProvider(Promise) { return self._emitChain; } - return Promise.map(self._listeners[name], function(listener) { - return (self._emitChain = self._emitChain.then(function() { + return Promise.map(self._listeners[name], function (listener) { + return (self._emitChain = self._emitChain.then(function () { // Double check that off wasn't called after an emit, but before this is fired. if (!self._listeners[name] || self._listeners[name].indexOf(listener) < 0) return; @@ -130,7 +130,7 @@ export function EventsProvider(Promise) { * @param {string} name * @return {array[function]} */ - Events.prototype.listeners = function(name) { + Events.prototype.listeners = function (name) { return _.pluck(this._listeners[name], 'handler'); }; diff --git a/src/legacy/ui/public/i18n/index.tsx b/src/legacy/ui/public/i18n/index.tsx index 6f1120dce0c7c..290e82a1334b9 100644 --- a/src/legacy/ui/public/i18n/index.tsx +++ b/src/legacy/ui/public/i18n/index.tsx @@ -29,7 +29,7 @@ import { npStart } from 'ui/new_platform'; export const I18nContext = npStart.core.i18n.Context; export function wrapInI18nContext

(ComponentToWrap: React.ComponentType

) { - const ContextWrapper: React.FC

= props => { + const ContextWrapper: React.FC

= (props) => { return ( diff --git a/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js b/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js index bbc72d599651a..a8abbba9df433 100644 --- a/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js +++ b/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js @@ -37,42 +37,42 @@ users.inIdOrder = _.sortBy(users, 'id'); // then things started becoming unruly... so IndexedArray! -describe('IndexedArray', function() { - describe('Basics', function() { +describe('IndexedArray', function () { + describe('Basics', function () { let reg; - beforeEach(function() { + beforeEach(function () { reg = new IndexedArray(); }); - it('Extends Array', function() { + it('Extends Array', function () { expect(reg).to.be.a(Array); }); - it('fails basic lodash check', function() { + it('fails basic lodash check', function () { expect(Array.isArray(reg)).to.be(false); }); - it('clones to an object', function() { + it('clones to an object', function () { expect(_.isPlainObject(_.clone(reg))).to.be(true); expect(Array.isArray(_.clone(reg))).to.be(false); }); }); - describe('Indexing', function() { - it('provides the initial set', function() { + describe('Indexing', function () { + it('provides the initial set', function () { const reg = new IndexedArray({ initialSet: [1, 2, 3], }); expect(reg).to.have.length(3); - reg.forEach(function(v, i) { + reg.forEach(function (v, i) { expect(v).to.eql(i + 1); }); }); - it('indexes the initial set', function() { + it('indexes the initial set', function () { const reg = new IndexedArray({ index: ['username'], initialSet: users, @@ -82,7 +82,7 @@ describe('IndexedArray', function() { expect(reg.byUsername).to.eql(users.byUsername); }); - it('updates indices after values are added', function() { + it('updates indices after values are added', function () { // split up the user list, and add it in chunks const firstUser = users.slice(0, 1).pop(); const otherUsers = users.slice(1); @@ -106,7 +106,7 @@ describe('IndexedArray', function() { expect(reg.inIdOrder).to.eql(users.inIdOrder); }); - it('updates indices after values are removed', function() { + it('updates indices after values are removed', function () { // start off with all const reg = new IndexedArray({ group: ['group'], @@ -123,7 +123,7 @@ describe('IndexedArray', function() { const sumOfGroups = _.reduce( reg.byGroup, - function(note, group) { + function (note, group) { return note + group.length; }, 0 @@ -131,7 +131,7 @@ describe('IndexedArray', function() { expect(sumOfGroups).to.eql(expectedCount); }); - it('removes items based on a predicate', function() { + it('removes items based on a predicate', function () { const reg = new IndexedArray({ group: ['group'], order: ['id'], @@ -145,12 +145,12 @@ describe('IndexedArray', function() { expect(reg[0].name).to.be('Anon'); }); - it('updates indices after values are re-ordered', function() { + it('updates indices after values are re-ordered', function () { const rawUsers = users.slice(0); // collect and shuffle the ids available let ids = []; - _.times(rawUsers.length, function(i) { + _.times(rawUsers.length, function (i) { ids.push(i); }); ids = _.shuffle(ids); @@ -160,7 +160,7 @@ describe('IndexedArray', function() { // from here const fromI = ids.shift(); // do the move - const move = function(arr) { + const move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; @@ -178,8 +178,8 @@ describe('IndexedArray', function() { }); }); - describe('Ordering', function() { - it('ordering is case insensitive', function() { + describe('Ordering', function () { + it('ordering is case insensitive', function () { const reg = new IndexedArray({ index: ['title'], order: ['title'], @@ -191,7 +191,7 @@ describe('IndexedArray', function() { expect(ordered[1].title).to.be('APM'); }); - it('ordering handles numbers', function() { + it('ordering handles numbers', function () { const reg = new IndexedArray({ index: ['id'], order: ['id'], diff --git a/src/legacy/ui/public/indexed_array/__tests__/inflector.js b/src/legacy/ui/public/indexed_array/__tests__/inflector.js index 51e4b94b416eb..49ac79094e501 100644 --- a/src/legacy/ui/public/indexed_array/__tests__/inflector.js +++ b/src/legacy/ui/public/indexed_array/__tests__/inflector.js @@ -20,14 +20,14 @@ import { inflector } from '../inflector'; import expect from '@kbn/expect'; -describe('IndexedArray Inflector', function() { - it('returns a function', function() { +describe('IndexedArray Inflector', function () { + it('returns a function', function () { const getter = inflector(); expect(getter).to.be.a('function'); }); - describe('fn', function() { - it('prepends a prefix', function() { + describe('fn', function () { + it('prepends a prefix', function () { const inflect = inflector('my'); expect(inflect('Family')).to.be('myFamily'); @@ -35,7 +35,7 @@ describe('IndexedArray Inflector', function() { expect(inflect('fAmIlY')).to.be('myFAmIlY'); }); - it('adds both a prefix and suffix', function() { + it('adds both a prefix and suffix', function () { const inflect = inflector('foo', 'Bar'); expect(inflect('box')).to.be('fooBoxBar'); @@ -43,19 +43,19 @@ describe('IndexedArray Inflector', function() { expect(inflect('BaZzY')).to.be('fooBaZzYBar'); }); - it('ignores prefix if it is already at the end of the inflected string', function() { + it('ignores prefix if it is already at the end of the inflected string', function () { 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() { + it('ignores postfix if it is already at the end of the inflected string', function () { const inflect = inflector('foo', 'Bar'); expect(inflect('bar')).to.be('fooBar'); expect(inflect('showBoxBar')).to.be('fooShowBoxBar'); }); - it('works with "name"', function() { + it('works with "name"', function () { const inflect = inflector('in', 'Order'); expect(inflect('name')).to.be('inNameOrder'); }); diff --git a/src/legacy/ui/public/indexed_array/indexed_array.js b/src/legacy/ui/public/indexed_array/indexed_array.js index 39c79b2f021a3..79ef5e8c183da 100644 --- a/src/legacy/ui/public/indexed_array/indexed_array.js +++ b/src/legacy/ui/public/indexed_array/indexed_array.js @@ -21,9 +21,7 @@ import _ from 'lodash'; import { inflector } from './inflector'; import { organizeBy } from './helpers/organize_by'; -const pathGetter = _(_.get) - .rearg(1, 0) - .ary(2); +const pathGetter = _(_.get).rearg(1, 0).ary(2); const inflectIndex = inflector('by'); const inflectOrder = inflector('in', 'Order'); @@ -62,9 +60,7 @@ export class IndexedArray { if (typeof a === 'number' && typeof b === 'number') { return a - b; } - return String(a) - .toLowerCase() - .localeCompare(String(b).toLowerCase()); + return String(a).toLowerCase().localeCompare(String(b).toLowerCase()); }); }) ); @@ -171,7 +167,7 @@ export class IndexedArray { // shortcut for empty props if (!props || props.length === 0) return; - return props.map(prop => { + return props.map((prop) => { const indexName = inflect(prop); const getIndexValueFromItem = pathGetter.partial(prop).value(); let cache; @@ -180,7 +176,7 @@ export class IndexedArray { enumerable: false, configurable: false, - set: val => { + set: (val) => { // can't set any value other than the CLEAR_CACHE constant if (val === CLEAR_CACHE) { cache = false; @@ -208,7 +204,7 @@ export class IndexedArray { * @return {undefined} */ _clearIndices() { - this._indexNames.forEach(name => { + this._indexNames.forEach((name) => { this[name] = CLEAR_CACHE; }); } diff --git a/src/legacy/ui/public/indexed_array/inflector.js b/src/legacy/ui/public/indexed_array/inflector.js index 00aa4cdefc4f3..e034146f5f62f 100644 --- a/src/legacy/ui/public/indexed_array/inflector.js +++ b/src/legacy/ui/public/indexed_array/inflector.js @@ -39,7 +39,7 @@ export function inflector(prefix, postfix) { if (key.indexOf('.') !== -1) { inflected = key .split('.') - .map(function(step, i) { + .map(function (step, i) { return i === 0 ? step : upFirst(step, true); }) .join(''); diff --git a/src/legacy/ui/public/kfetch/kfetch.test.ts b/src/legacy/ui/public/kfetch/kfetch.test.ts index 259acc2753a43..c45a142d54e9b 100644 --- a/src/legacy/ui/public/kfetch/kfetch.test.ts +++ b/src/legacy/ui/public/kfetch/kfetch.test.ts @@ -353,11 +353,11 @@ describe('kfetch', () => { beforeEach(async () => { fetchMock.get('*', { foo: 'bar' }); addInterceptor({ - request: config => ({ + request: (config) => ({ ...config, pathname: '/my/intercepted-route', }), - response: res => ({ + response: (res) => ({ ...res, addedByResponseInterceptor: true, }), @@ -386,12 +386,12 @@ describe('kfetch', () => { beforeEach(async () => { fetchMock.get('*', { foo: 'bar' }); addInterceptor({ - request: config => + request: (config) => Promise.resolve({ ...config, pathname: '/my/intercepted-route', }), - response: res => + response: (res) => Promise.resolve({ ...res, addedByResponseInterceptor: true, @@ -421,7 +421,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { const interceptorCalls: string[] = []; interceptors.forEach((interceptor, i) => { addInterceptor({ - request: config => { + request: (config) => { interceptorCalls.push(`Request #${i + 1}`); if (interceptor.request) { @@ -430,7 +430,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { return config; }, - requestError: e => { + requestError: (e) => { interceptorCalls.push(`RequestError #${i + 1}`); if (interceptor.requestError) { return interceptor.requestError(e); @@ -438,7 +438,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { throw e; }, - response: res => { + response: (res) => { interceptorCalls.push(`Response #${i + 1}`); if (interceptor.response) { @@ -447,7 +447,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { return res; }, - responseError: e => { + responseError: (e) => { interceptorCalls.push(`ResponseError #${i + 1}`); if (interceptor.responseError) { diff --git a/src/legacy/ui/public/kfetch/kfetch.ts b/src/legacy/ui/public/kfetch/kfetch.ts index 02be7a32db296..4eb7149931575 100644 --- a/src/legacy/ui/public/kfetch/kfetch.ts +++ b/src/legacy/ui/public/kfetch/kfetch.ts @@ -60,7 +60,7 @@ export function createKfetch(http: HttpSetup) { .then(({ pathname, ...restOptions }) => http.fetch(pathname, { ...restOptions, prependBasePath }) ) - .catch(err => { + .catch((err) => { throw new KFetchError(err.response || { statusText: err.message }, err.body); }) ); diff --git a/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js b/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js index 3ca836e23881a..efcfb77997265 100644 --- a/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js +++ b/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js @@ -28,30 +28,30 @@ import { version } from '../../../../../core/server/utils/package_json'; const xsrfHeader = 'kbn-version'; -describe('chrome xsrf apis', function() { +describe('chrome xsrf apis', function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe('jQuery support', function() { - it('adds a global jQuery prefilter', function() { + describe('jQuery support', function () { + it('adds a global jQuery prefilter', function () { sandbox.stub($, 'ajaxPrefilter'); $setupXsrfRequestInterceptor(version); expect($.ajaxPrefilter.callCount).to.be(1); }); - describe('jQuery prefilter', function() { + describe('jQuery prefilter', function () { let prefilter; - beforeEach(function() { + beforeEach(function () { sandbox.stub($, 'ajaxPrefilter'); $setupXsrfRequestInterceptor(version); prefilter = $.ajaxPrefilter.args[0][0]; }); - it(`sets the ${xsrfHeader} header`, function() { + it(`sets the ${xsrfHeader} header`, function () { const setHeader = sinon.stub(); prefilter({}, {}, { setRequestHeader: setHeader }); @@ -59,24 +59,24 @@ describe('chrome xsrf apis', function() { expect(setHeader.args[0]).to.eql([xsrfHeader, version]); }); - it('can be canceled by setting the kbnXsrfToken option', function() { + it('can be canceled by setting the kbnXsrfToken option', function () { const setHeader = sinon.stub(); prefilter({ kbnXsrfToken: false }, {}, { setRequestHeader: setHeader }); expect(setHeader.callCount).to.be(0); }); }); - describe('Angular support', function() { + describe('Angular support', function () { let $http; let $httpBackend; - beforeEach(function() { + beforeEach(function () { sandbox.stub($, 'ajaxPrefilter'); ngMock.module($setupXsrfRequestInterceptor(version)); }); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $http = $injector.get('$http'); $httpBackend = $injector.get('$httpBackend'); @@ -84,14 +84,14 @@ describe('chrome xsrf apis', function() { }) ); - afterEach(function() { + afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); - it(`injects a ${xsrfHeader} header on every request`, function() { + it(`injects a ${xsrfHeader} header on every request`, function () { $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return headers[xsrfHeader] === version; }) .respond(200, ''); @@ -100,9 +100,9 @@ describe('chrome xsrf apis', function() { $httpBackend.flush(); }); - it('skips requests with the kbnXsrfToken set falsy', function() { + it('skips requests with the kbnXsrfToken set falsy', function () { $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return !(xsrfHeader in headers); }) .respond(200, ''); @@ -128,10 +128,10 @@ describe('chrome xsrf apis', function() { $httpBackend.flush(); }); - it('treats the kbnXsrfToken option as boolean-y', function() { + it('treats the kbnXsrfToken option as boolean-y', function () { const customToken = `custom:${version}`; $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return headers[xsrfHeader] === version; }) .respond(200, ''); diff --git a/src/legacy/ui/public/modules.js b/src/legacy/ui/public/modules.js index cbc222061e757..bb1c8aead1c34 100644 --- a/src/legacy/ui/public/modules.js +++ b/src/legacy/ui/public/modules.js @@ -107,7 +107,7 @@ export function get(moduleName, requires) { module.close = _.partial(close, moduleName); // ensure that it is required by linked modules - _.each(links, function(app) { + _.each(links, function (app) { if (!~app.requires.indexOf(moduleName)) app.requires.push(moduleName); }); } @@ -131,7 +131,7 @@ export function close(moduleName) { if (i > -1) links.splice(i, 1); // remove from linked modules list of required modules - _.each(links, function(app) { + _.each(links, function (app) { _.pull(app.requires, moduleName); }); diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index 67422fa659439..229bfb1978a4e 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -49,7 +49,7 @@ let isTimeRangeSelectorEnabled = true; let isAutoRefreshSelectorEnabled = true; export const mockUiSettings = { - get: item => { + get: (item) => { return mockUiSettings[item]; }, getUpdate$: () => ({ @@ -134,7 +134,7 @@ const querySetup = { getRefreshInterval: () => { return refreshInterval; }, - setRefreshInterval: interval => { + setRefreshInterval: (interval) => { refreshInterval = interval; }, enableTimeRangeSelector: () => { @@ -173,8 +173,8 @@ const mockAggTypesRegistry = () => { notifications: mockCoreStart.notifications, }), }); - aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); - aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); + aggTypes.buckets.forEach((type) => registrySetup.registerBucket(type)); + aggTypes.metrics.forEach((type) => registrySetup.registerMetric(type)); return registry; }; @@ -382,7 +382,7 @@ export const npStart = { }, getSuggestions: sinon.fake(), indexPatterns: { - get: sinon.spy(indexPatternId => + get: sinon.spy((indexPatternId) => Promise.resolve({ id: indexPatternId, isTimeNanosBased: () => false, @@ -428,7 +428,7 @@ export const npStart = { getRefreshInterval: () => { return refreshInterval; }, - setRefreshInterval: interval => { + setRefreshInterval: (interval) => { refreshInterval = interval; }, enableTimeRangeSelector: () => { diff --git a/src/legacy/ui/public/new_platform/new_platform.test.ts b/src/legacy/ui/public/new_platform/new_platform.test.ts index 21e7b559f71f5..d515c348ca440 100644 --- a/src/legacy/ui/public/new_platform/new_platform.test.ts +++ b/src/legacy/ui/public/new_platform/new_platform.test.ts @@ -113,7 +113,7 @@ describe('ui/new_platform', () => { controller(scopeMock, elementMock); // Flush promise queue. Must be done this way because the controller cannot return a Promise without breaking // angular. - await new Promise(resolve => setTimeout(resolve, 1)); + await new Promise((resolve) => setTimeout(resolve, 1)); const [event, eventHandler] = scopeMock.$on.mock.calls[0]; expect(event).toEqual('$destroy'); diff --git a/src/legacy/ui/public/new_platform/set_services.test.ts b/src/legacy/ui/public/new_platform/set_services.test.ts index 25a4524925169..b7878954846fa 100644 --- a/src/legacy/ui/public/new_platform/set_services.test.ts +++ b/src/legacy/ui/public/new_platform/set_services.test.ts @@ -29,8 +29,8 @@ import { npSetup, npStart } from './__mocks__'; describe('ui/new_platform', () => { describe('set service getters', () => { const testServiceGetters = (name: string, services: Record) => { - const getters = Object.keys(services).filter(k => k.substring(0, 3) === 'get'); - getters.forEach(g => { + const getters = Object.keys(services).filter((k) => k.substring(0, 3) === 'get'); + getters.forEach((g) => { it(`ui/new_platform sets a value for ${name} getter ${g}`, () => { __reset__(); __setup__( diff --git a/src/legacy/ui/public/private/__tests__/private.js b/src/legacy/ui/public/private/__tests__/private.js index c8c9c7467ad2e..1f9d696bb440f 100644 --- a/src/legacy/ui/public/private/__tests__/private.js +++ b/src/legacy/ui/public/private/__tests__/private.js @@ -20,17 +20,17 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('Private module loader', function() { +describe('Private module loader', function () { let Private; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { Private = $injector.get('Private'); }) ); - it('accepts a provider that will be called to init a module', function() { + it('accepts a provider that will be called to init a module', function () { const football = {}; function Provider() { return football; @@ -40,7 +40,7 @@ describe('Private module loader', function() { expect(instance).to.be(football); }); - it('injects angular dependencies into the Provider', function() { + it('injects angular dependencies into the Provider', function () { function Provider(Private) { return Private; } @@ -49,8 +49,8 @@ describe('Private module loader', function() { expect(instance).to.be(Private); }); - it('detects circular dependencies', function() { - expect(function() { + it('detects circular dependencies', function () { + expect(function () { function Provider1() { Private(Provider2); } @@ -63,7 +63,7 @@ describe('Private module loader', function() { }).to.throwException(/circular/i); }); - it('always provides the same instance form the Provider', function() { + it('always provides the same instance form the Provider', function () { function Provider() { return {}; } @@ -71,8 +71,8 @@ describe('Private module loader', function() { expect(Private(Provider)).to.be(Private(Provider)); }); - describe('#stub', function() { - it('accepts a replacement instance for a Provider', function() { + describe('#stub', function () { + it('accepts a replacement instance for a Provider', function () { const replaced = {}; const replacement = {}; @@ -95,8 +95,8 @@ describe('Private module loader', function() { }); }); - describe('#swap', function() { - it('accepts a new Provider that should replace an existing Provider', function() { + describe('#swap', function () { + it('accepts a new Provider that should replace an existing Provider', function () { function Provider1() { return {}; } @@ -120,7 +120,7 @@ describe('Private module loader', function() { expect(instance3).to.be(instance1); }); - it('gives the new Provider access to the Provider it replaced via an injectable dependency called $decorate', function() { + it('gives the new Provider access to the Provider it replaced via an injectable dependency called $decorate', function () { function Provider1() { return {}; } diff --git a/src/legacy/ui/public/promises/__tests__/promises.js b/src/legacy/ui/public/promises/__tests__/promises.js index cbf995d76e994..7041aa2993376 100644 --- a/src/legacy/ui/public/promises/__tests__/promises.js +++ b/src/legacy/ui/public/promises/__tests__/promises.js @@ -35,7 +35,7 @@ describe('Promise service', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { sandbox.useFakeTimers(); Promise = $injector.get('Promise'); @@ -126,8 +126,8 @@ describe('Promise service', () => { describe('Promise.race()', () => { it(`resolves with the first resolved promise's value`, () => { - const p1 = new Promise(resolve => setTimeout(resolve, 100, 1)); - const p2 = new Promise(resolve => setTimeout(resolve, 200, 2)); + const p1 = new Promise((resolve) => setTimeout(resolve, 100, 1)); + const p2 = new Promise((resolve) => setTimeout(resolve, 200, 2)); const onResolve = sinon.stub(); Promise.race([p1, p2]).then(onResolve); @@ -155,10 +155,10 @@ describe('Promise service', () => { it('does not wait for subsequent promises to resolve/reject', () => { const onP1Resolve = sinon.stub(); - const p1 = new Promise(resolve => setTimeout(resolve, 100)).then(onP1Resolve); + const p1 = new Promise((resolve) => setTimeout(resolve, 100)).then(onP1Resolve); const onP2Resolve = sinon.stub(); - const p2 = new Promise(resolve => setTimeout(resolve, 101)).then(onP2Resolve); + const p2 = new Promise((resolve) => setTimeout(resolve, 101)).then(onP2Resolve); const onResolve = sinon.stub(); Promise.race([p1, p2]).then(onResolve); @@ -226,8 +226,8 @@ describe('Promise service', () => { describe('argument is a generator', () => { it('resolves with the first resolved value', () => { function* gen() { - yield new Promise(resolve => setTimeout(resolve, 100, 1)); - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 100, 1)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); @@ -242,7 +242,7 @@ describe('Promise service', () => { it('resolves with the first non-promise value', () => { function* gen() { yield 1; - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); @@ -260,7 +260,7 @@ describe('Promise service', () => { yieldCount += 1; yield 1; yieldCount += 1; - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); diff --git a/src/legacy/ui/public/react_components.js b/src/legacy/ui/public/react_components.js index b771e37c9d538..21fb53d6407fa 100644 --- a/src/legacy/ui/public/react_components.js +++ b/src/legacy/ui/public/react_components.js @@ -25,8 +25,8 @@ import { uiModules } from './modules'; const app = uiModules.get('app/kibana', ['react']); -app.directive('icon', reactDirective => reactDirective(EuiIcon)); +app.directive('icon', (reactDirective) => reactDirective(EuiIcon)); -app.directive('iconTip', reactDirective => +app.directive('iconTip', (reactDirective) => reactDirective(EuiIconTip, ['content', 'type', 'position', 'title', 'color']) ); diff --git a/src/legacy/ui/public/registry/__tests__/registry.js b/src/legacy/ui/public/registry/__tests__/registry.js index 14e4ce4a14e28..10b2423abc0e3 100644 --- a/src/legacy/ui/public/registry/__tests__/registry.js +++ b/src/legacy/ui/public/registry/__tests__/registry.js @@ -21,23 +21,23 @@ import { uiRegistry } from '../_registry'; import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('Registry', function() { +describe('Registry', function () { let Private; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { Private = $injector.get('Private'); }) ); - it('is technically a function', function() { + it('is technically a function', function () { const reg = uiRegistry(); expect(reg).to.be.a('function'); }); - describe('#register', function() { - it('accepts a Private module', function() { + describe('#register', function () { + it('accepts a Private module', function () { const reg = uiRegistry(); const mod = function SomePrivateModule() {}; @@ -45,9 +45,9 @@ describe('Registry', function() { // modules are not exposed, so this is the most that we can test }); - it('applies the filter function if one is specified', function() { + it('applies the filter function if one is specified', function () { const reg = uiRegistry({ - filter: item => item.value % 2 === 0, // register only even numbers + filter: (item) => item.value % 2 === 0, // register only even numbers }); reg.register(() => ({ value: 17 })); @@ -60,8 +60,8 @@ describe('Registry', function() { }); }); - describe('as a module', function() { - it('exposes the list of registered modules', function() { + describe('as a module', function () { + it('exposes the list of registered modules', function () { const reg = uiRegistry(); const mod = function SomePrivateModule(Private) { this.PrivateModuleLoader = Private; @@ -74,12 +74,12 @@ describe('Registry', function() { }); }); - describe('spec', function() { - it('executes with the module list as "this", and can override it', function() { + describe('spec', function () { + it('executes with the module list as "this", and can override it', function () { let self; const reg = uiRegistry({ - constructor: function() { + constructor: function () { return { mods: (self = this) }; }, }); @@ -90,8 +90,8 @@ describe('Registry', function() { }); }); - describe('spec.name', function() { - it('sets the displayName of the registry and the name param on the final instance', function() { + describe('spec.name', function () { + it('sets the displayName of the registry and the name param on the final instance', function () { const reg = uiRegistry({ name: 'visTypes', }); @@ -101,12 +101,12 @@ describe('Registry', function() { }); }); - describe('spec.constructor', function() { - it('executes before the modules are returned', function() { + describe('spec.constructor', function () { + it('executes before the modules are returned', function () { let i = 0; const reg = uiRegistry({ - constructor: function() { + constructor: function () { i = i + 1; }, }); @@ -115,11 +115,11 @@ describe('Registry', function() { expect(i).to.be(1); }); - it('executes with the module list as "this", and can override it', function() { + it('executes with the module list as "this", and can override it', function () { let self; const reg = uiRegistry({ - constructor: function() { + constructor: function () { return { mods: (self = this) }; }, }); @@ -134,7 +134,7 @@ describe('Registry', function() { it('is called with the registered providers and defines the initial set of values in the registry', () => { const reg = uiRegistry({ invokeProviders(providers) { - return providers.map(i => i * 1000); + return providers.map((i) => i * 1000); }, }); @@ -152,10 +152,10 @@ describe('Registry', function() { }); }); - describe('spec[any]', function() { - it('mixes the extra properties into the module list', function() { + describe('spec[any]', function () { + it('mixes the extra properties into the module list', function () { const reg = uiRegistry({ - someMethod: function() { + someMethod: function () { return this; }, }); diff --git a/src/legacy/ui/public/registry/_registry.js b/src/legacy/ui/public/registry/_registry.js index 39e0d1526fd8a..85aa1d9f2eca8 100644 --- a/src/legacy/ui/public/registry/_registry.js +++ b/src/legacy/ui/public/registry/_registry.js @@ -91,14 +91,14 @@ export function uiRegistry(spec) { * that were registered, the registry spec * defines how things will be indexed. */ - const registry = function(Private, $injector) { - getInvokedProviders = function(newProviders) { + const registry = function (Private, $injector) { + getInvokedProviders = function (newProviders) { let set = invokeProviders ? $injector.invoke(invokeProviders, undefined, { providers: newProviders }) : newProviders.map(Private); if (filter && _.isFunction(filter)) { - set = set.filter(item => filter(item)); + set = set.filter((item) => filter(item)); } return set; @@ -123,7 +123,7 @@ export function uiRegistry(spec) { registry.displayName = '[registry ' + props.name + ']'; - registry.register = function(privateModule) { + registry.register = function (privateModule) { providers.push(privateModule); if (isInstantiated) { diff --git a/src/legacy/ui/public/routes/__tests__/_route_manager.js b/src/legacy/ui/public/routes/__tests__/_route_manager.js index 011922c7ed789..51bde8b8605ac 100644 --- a/src/legacy/ui/public/routes/__tests__/_route_manager.js +++ b/src/legacy/ui/public/routes/__tests__/_route_manager.js @@ -31,9 +31,9 @@ const chainableMethods = [ ]; let $rp; -describe('routes/route_manager', function() { +describe('routes/route_manager', function () { beforeEach( - ngMock.module('kibana', function($routeProvider) { + ngMock.module('kibana', function ($routeProvider) { $rp = $routeProvider; sinon.stub($rp, 'otherwise'); sinon.stub($rp, 'when'); @@ -41,19 +41,19 @@ describe('routes/route_manager', function() { ); beforeEach( - ngMock.inject(function() { + ngMock.inject(function () { routes = new RouteManager(); }) ); - it('should have chainable methods: ' + _.pluck(chainableMethods, 'name').join(', '), function() { - chainableMethods.forEach(function(meth) { + it('should have chainable methods: ' + _.pluck(chainableMethods, 'name').join(', '), function () { + chainableMethods.forEach(function (meth) { expect(routes[meth.name].apply(routes, _.clone(meth.args))).to.be(routes); }); }); - describe('#otherwise', function() { - it('should forward the last otherwise route', function() { + describe('#otherwise', function () { + it('should forward the last otherwise route', function () { const otherRoute = {}; routes.otherwise({}); routes.otherwise(otherRoute); @@ -65,15 +65,15 @@ describe('routes/route_manager', function() { }); }); - describe('#when', function() { - it('should merge the additions into the when() defined routes', function() { + describe('#when', function () { + it('should merge the additions into the when() defined routes', function () { routes.when('/some/route'); routes.when('/some/other/route'); // add the addition resolve to every route routes.defaults(/.*/, { resolve: { - addition: function() {}, + addition: function () {}, }, }); @@ -89,21 +89,21 @@ describe('routes/route_manager', function() { }); }); - describe('#config', function() { - it('should add defined routes to the global $routeProvider service in order', function() { + describe('#config', function () { + it('should add defined routes to the global $routeProvider service in order', function () { const args = [ ['/one', {}], ['/two', {}], ]; - args.forEach(function(a) { + args.forEach(function (a) { routes.when(a[0], a[1]); }); routes.config($rp); expect($rp.when.callCount).to.be(args.length); - _.times(args.length, function(i) { + _.times(args.length, function (i) { const call = $rp.when.getCall(i); const a = args.shift(); @@ -112,7 +112,7 @@ describe('routes/route_manager', function() { }); }); - it('sets route.reloadOnSearch to false by default', function() { + it('sets route.reloadOnSearch to false by default', function () { routes.when('/nothing-set'); routes.when('/no-reload', { reloadOnSearch: false }); routes.when('/always-reload', { reloadOnSearch: true }); diff --git a/src/legacy/ui/public/routes/__tests__/_work_queue.js b/src/legacy/ui/public/routes/__tests__/_work_queue.js index cc6b4ce8d29bc..72891f7321fbd 100644 --- a/src/legacy/ui/public/routes/__tests__/_work_queue.js +++ b/src/legacy/ui/public/routes/__tests__/_work_queue.js @@ -24,32 +24,32 @@ import { WorkQueue } from '../work_queue'; import sinon from 'sinon'; import { createDefer } from 'ui/promises'; -describe('work queue', function() { +describe('work queue', function () { let queue; let Promise; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_Promise_) { + ngMock.inject(function (_Promise_) { Promise = _Promise_; }) ); - beforeEach(function() { + beforeEach(function () { queue = new WorkQueue(); }); - afterEach(function() { + afterEach(function () { queue.empty(); }); - describe('#push', function() { - it('adds to the interval queue', function() { + describe('#push', function () { + it('adds to the interval queue', function () { queue.push(createDefer(Promise)); expect(queue).to.have.length(1); }); }); - describe('#resolveWhenFull', function() { - it('resolves requests waiting for the queue to fill when appropriate', function() { + describe('#resolveWhenFull', function () { + it('resolves requests waiting for the queue to fill when appropriate', function () { const size = _.random(5, 50); queue.limit = size; @@ -58,7 +58,7 @@ describe('work queue', function() { queue.resolveWhenFull(whenFull); // push all but one into the queue - _.times(size - 1, function() { + _.times(size - 1, function () { queue.push(createDefer(Promise)); }); @@ -81,7 +81,7 @@ describe('work queue', function() { const size = _.random(5, 50); const stub = sinon.stub(); - _.times(size, function() { + _.times(size, function () { const d = createDefer(Promise); // overwrite the defer methods with the stub d.resolve = stub; @@ -92,9 +92,9 @@ describe('work queue', function() { then(size, stub); } - describe('#doWork', function() { - it('flushes the queue and resolves all promises', function() { - fillWithStubs(function(size, stub) { + describe('#doWork', function () { + it('flushes the queue and resolves all promises', function () { + fillWithStubs(function (size, stub) { expect(queue).to.have.length(size); queue.doWork(); expect(queue).to.have.length(0); @@ -103,9 +103,9 @@ describe('work queue', function() { }); }); - describe('#empty()', function() { - it('empties the internal queue WITHOUT resolving any promises', function() { - fillWithStubs(function(size, stub) { + describe('#empty()', function () { + it('empties the internal queue WITHOUT resolving any promises', function () { + fillWithStubs(function (size, stub) { expect(queue).to.have.length(size); queue.empty(); expect(queue).to.have.length(0); diff --git a/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js b/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js index c5175e86040c1..8ae85fce591a1 100644 --- a/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js +++ b/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js @@ -26,20 +26,20 @@ import '../../private'; let routes; -describe('wrapRouteWithPrep fn', function() { +describe('wrapRouteWithPrep fn', function () { require('test_utils/no_digest_promises').activateForSuite(); - beforeEach(function() { + beforeEach(function () { routes = new RouteManager(); }); - const SchedulingTest = function(opts) { + const SchedulingTest = function (opts) { opts = opts || {}; const delaySetup = opts.delayUserWork ? 0 : 50; const delayUserWork = opts.delayUserWork ? 50 : 0; - return function() { + return function () { ngMock.module('kibana'); let setupComplete = false; let userWorkComplete = false; @@ -47,14 +47,14 @@ describe('wrapRouteWithPrep fn', function() { let Promise; let $injector; - ngMock.inject(function(_Promise_, _$injector_) { + ngMock.inject(function (_Promise_, _$injector_) { Promise = _Promise_; $injector = _$injector_; }); - routes.addSetupWork(function() { - return new Promise(function(resolve) { - setTimeout(function() { + routes.addSetupWork(function () { + return new Promise(function (resolve) { + setTimeout(function () { setupComplete = true; resolve(); }, delaySetup); @@ -64,26 +64,26 @@ describe('wrapRouteWithPrep fn', function() { routes .when('/', { resolve: { - test: function() { + test: function () { expect(setupComplete).to.be(true); userWorkComplete = true; }, }, }) .config({ - when: function(p, _r) { + when: function (p, _r) { route = _r; }, }); - return new Promise(function(resolve, reject) { - setTimeout(function() { + return new Promise(function (resolve, reject) { + setTimeout(function () { Promise.all( - _.map(route.resolve, function(fn) { + _.map(route.resolve, function (fn) { return $injector.invoke(fn); }) ) - .then(function() { + .then(function () { expect(setupComplete).to.be(true); expect(userWorkComplete).to.be(true); }) diff --git a/src/legacy/ui/public/routes/__tests__/index.js b/src/legacy/ui/public/routes/__tests__/index.js index 62bbec9ef3e67..30cedaaca3d19 100644 --- a/src/legacy/ui/public/routes/__tests__/index.js +++ b/src/legacy/ui/public/routes/__tests__/index.js @@ -20,4 +20,4 @@ import './_route_manager'; import './_work_queue'; import './_wrap_route_with_prep'; -describe('Custom Route Management', function() {}); +describe('Custom Route Management', function () {}); diff --git a/src/legacy/ui/public/routes/route_manager.js b/src/legacy/ui/public/routes/route_manager.js index 1cf2a5fc5a64a..de8a541d1c50a 100644 --- a/src/legacy/ui/public/routes/route_manager.js +++ b/src/legacy/ui/public/routes/route_manager.js @@ -31,12 +31,12 @@ export default function RouteManager() { const defaults = []; let otherwise; - self.config = function($routeProvider) { - when.forEach(function(args) { + self.config = function ($routeProvider) { + when.forEach(function (args) { const path = args[0]; const route = args[1] || {}; - defaults.forEach(def => { + defaults.forEach((def) => { if (def.regex.test(path)) { defaultsDeep(route, cloneDeep(def.value)); } @@ -56,7 +56,7 @@ export default function RouteManager() { } }; - self.run = function($location, $route, $injector, $rootScope) { + self.run = function ($location, $route, $injector, $rootScope) { if (window.elasticApm && typeof window.elasticApm.startTransaction === 'function') { /** * capture route-change events as transactions which happens after @@ -89,24 +89,24 @@ export default function RouteManager() { this.afterSetupWork = wrap(setup.afterSetupWork, wrapSetupAndChain); this.afterWork = wrap(setup.afterWork, wrapSetupAndChain); - self.when = function(path, route) { + self.when = function (path, route) { when.push([path, route]); return self; }; // before attaching the routes to the routeProvider, test the RE // against the .when() path and add/override the resolves if there is a match - self.defaults = function(regex, value) { + self.defaults = function (regex, value) { defaults.push({ regex, value }); return self; }; - self.otherwise = function(route) { + self.otherwise = function (route) { otherwise = route; return self; }; - self.getBreadcrumbs = function() { + self.getBreadcrumbs = function () { // overwritten in self.run(); return []; }; diff --git a/src/legacy/ui/public/routes/route_setup_manager.js b/src/legacy/ui/public/routes/route_setup_manager.js index ded295e97d4c4..a7a2f078f40fb 100644 --- a/src/legacy/ui/public/routes/route_setup_manager.js +++ b/src/legacy/ui/public/routes/route_setup_manager.js @@ -55,7 +55,7 @@ export class RouteSetupManager { */ doWork(Promise, $injector, userWork) { const invokeEach = (arr, locals) => { - return Promise.map(arr, fn => { + return Promise.map(arr, (fn) => { if (!fn) return; return $injector.invoke(fn, null, locals); }); @@ -69,13 +69,13 @@ export class RouteSetupManager { // clone so we don't discard handlers or loose them handlers = handlers.slice(0); - const next = err => { + const next = (err) => { if (!handlers.length) throw err; const handler = handlers.shift(); if (!handler) return next(err); - return Promise.try(function() { + return Promise.try(function () { return $injector.invoke(handler, null, { err }); }).catch(next); }; @@ -86,7 +86,7 @@ export class RouteSetupManager { return invokeEach(this.setupWork) .then( () => invokeEach(this.onSetupComplete), - err => callErrorHandlers(this.onSetupError, err) + (err) => callErrorHandlers(this.onSetupError, err) ) .then(() => { // wait for the queue to fill up, then do all the work @@ -95,7 +95,7 @@ export class RouteSetupManager { return defer.promise.then(() => Promise.all(userWork.doWork())); }) - .catch(error => { + .catch((error) => { if (error === WAIT_FOR_URL_CHANGE_TOKEN) { // prevent moving forward, return a promise that never resolves // so that the $router can observe the $location update @@ -106,7 +106,7 @@ export class RouteSetupManager { }) .then( () => invokeEach(this.onWorkComplete), - err => callErrorHandlers(this.onWorkError, err) + (err) => callErrorHandlers(this.onWorkError, err) ); } } diff --git a/src/legacy/ui/public/routes/work_queue.js b/src/legacy/ui/public/routes/work_queue.js index f733375697438..5c4c83663c590 100644 --- a/src/legacy/ui/public/routes/work_queue.js +++ b/src/legacy/ui/public/routes/work_queue.js @@ -25,40 +25,40 @@ export function WorkQueue() { q.limit = 0; Object.defineProperty(q, 'length', { - get: function() { + get: function () { return work.length; }, }); - const resolve = function(defers) { - return defers.splice(0).map(function(defer) { + const resolve = function (defers) { + return defers.splice(0).map(function (defer) { return defer.resolve(); }); }; - const checkIfFull = function() { + const checkIfFull = function () { if (work.length >= q.limit && fullDefers.length) { resolve(fullDefers); } }; - q.resolveWhenFull = function(defer) { + q.resolveWhenFull = function (defer) { fullDefers.push(defer); checkIfFull(); }; - q.doWork = function() { + q.doWork = function () { const resps = resolve(work); checkIfFull(); return resps; }; - q.empty = function() { + q.empty = function () { work.splice(0); checkIfFull(); }; - q.push = function(defer) { + q.push = function (defer) { work.push(defer); checkIfFull(); }; diff --git a/src/legacy/ui/public/routes/wrap_route_with_prep.js b/src/legacy/ui/public/routes/wrap_route_with_prep.js index e74de9c85efa8..e9ed33148d9ac 100644 --- a/src/legacy/ui/public/routes/wrap_route_with_prep.js +++ b/src/legacy/ui/public/routes/wrap_route_with_prep.js @@ -30,18 +30,18 @@ export function wrapRouteWithPrep(route, setup) { userWork.limit = _.keys(route.resolve).length; const resolve = { - __prep__: function($injector) { + __prep__: function ($injector) { return $injector.invoke(setup.doWork, setup, { userWork }); }, }; // send each user resolve to the userWork queue, which will prevent it from running before the // prep is complete - _.forOwn(route.resolve || {}, function(expr, name) { - resolve[name] = function($injector, Promise) { + _.forOwn(route.resolve || {}, function (expr, name) { + resolve[name] = function ($injector, Promise) { const defer = createDefer(Promise); userWork.push(defer); - return defer.promise.then(function() { + return defer.promise.then(function () { return $injector[angular.isString(expr) ? 'get' : 'invoke'](expr); }); }; diff --git a/src/legacy/ui/public/state_management/__tests__/app_state.js b/src/legacy/ui/public/state_management/__tests__/app_state.js index 1c8cfe7f796a1..c47fa3bb0417f 100644 --- a/src/legacy/ui/public/state_management/__tests__/app_state.js +++ b/src/legacy/ui/public/state_management/__tests__/app_state.js @@ -22,31 +22,31 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import { AppStateProvider } from '../app_state'; -describe('State Management', function() { +describe('State Management', function () { let $rootScope; let AppState; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private) { + ngMock.inject(function (_$rootScope_, _$location_, Private) { $rootScope = _$rootScope_; AppState = Private(AppStateProvider); }) ); - describe('App State', function() { + describe('App State', function () { let appState; - beforeEach(function() { + beforeEach(function () { appState = new AppState(); }); - it('should have _urlParam of _a', function() { + it('should have _urlParam of _a', function () { expect(appState).to.have.property('_urlParam'); expect(appState._urlParam).to.equal('_a'); }); - it('should use passed in params', function() { + it('should use passed in params', function () { const params = { test: true, mock: false, @@ -55,17 +55,17 @@ describe('State Management', function() { appState = new AppState(params); expect(appState).to.have.property('_defaults'); - Object.keys(params).forEach(function(key) { + Object.keys(params).forEach(function (key) { expect(appState._defaults).to.have.property(key); expect(appState._defaults[key]).to.equal(params[key]); }); }); - it('should have a destroy method', function() { + it('should have a destroy method', function () { expect(appState).to.have.property('destroy'); }); - it('should be destroyed on $routeChangeStart', function() { + it('should be destroyed on $routeChangeStart', function () { const destroySpy = sinon.spy(appState, 'destroy'); $rootScope.$emit('$routeChangeStart'); diff --git a/src/legacy/ui/public/state_management/__tests__/config_provider.js b/src/legacy/ui/public/state_management/__tests__/config_provider.js index 1f971bed6c165..9f756bc51dcb0 100644 --- a/src/legacy/ui/public/state_management/__tests__/config_provider.js +++ b/src/legacy/ui/public/state_management/__tests__/config_provider.js @@ -21,13 +21,13 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../config_provider'; -describe('State Management Config', function() { +describe('State Management Config', function () { let stateManagementConfig; describe('is enabled', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_stateManagementConfig_) { + ngMock.inject(function (_stateManagementConfig_) { stateManagementConfig = _stateManagementConfig_; }) ); @@ -39,13 +39,13 @@ describe('State Management Config', function() { describe('can be disabled', () => { beforeEach( - ngMock.module('kibana', function(stateManagementConfigProvider) { + ngMock.module('kibana', function (stateManagementConfigProvider) { stateManagementConfigProvider.disable(); }) ); beforeEach( - ngMock.inject(function(_stateManagementConfig_) { + ngMock.inject(function (_stateManagementConfig_) { stateManagementConfig = _stateManagementConfig_; }) ); diff --git a/src/legacy/ui/public/state_management/__tests__/global_state.js b/src/legacy/ui/public/state_management/__tests__/global_state.js index 08c90bab0d2ef..e9dae5880a8d1 100644 --- a/src/legacy/ui/public/state_management/__tests__/global_state.js +++ b/src/legacy/ui/public/state_management/__tests__/global_state.js @@ -21,20 +21,20 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../global_state'; -describe('State Management', function() { +describe('State Management', function () { let $location; let state; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$location_, globalState) { + ngMock.inject(function (_$location_, globalState) { $location = _$location_; state = globalState; }) ); - describe('Global State', function() { - it('should use previous state when not in URL', function() { + describe('Global State', function () { + it('should use previous state when not in URL', function () { // set satte via URL $location.search({ _g: '(foo:(bar:baz))' }); state.fetch(); diff --git a/src/legacy/ui/public/state_management/__tests__/state.js b/src/legacy/ui/public/state_management/__tests__/state.js index ab70413c2d10e..cde123e6c1d85 100644 --- a/src/legacy/ui/public/state_management/__tests__/state.js +++ b/src/legacy/ui/public/state_management/__tests__/state.js @@ -46,18 +46,15 @@ describe('State Management', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private, config) { + ngMock.inject(function (_$rootScope_, _$location_, Private, config) { const State = Private(StateProvider); $location = _$location_; $rootScope = _$rootScope_; Events = Private(EventsProvider); - setup = opts => { + setup = (opts) => { const { param, initial, storeInHash } = opts || {}; - sinon - .stub(config, 'get') - .withArgs('state:storeInSessionStorage') - .returns(!!storeInHash); + sinon.stub(config, 'get').withArgs('state:storeInSessionStorage').returns(!!storeInHash); const store = new StubBrowserStorage(); const hashedItemStore = new HashedItemStore(store); const state = new State(param, initial, hashedItemStore); @@ -89,9 +86,9 @@ describe('State Management', () => { expect(state).to.be.an(Events); }); - it('should emit an event if reset with changes', done => { + it('should emit an event if reset with changes', (done) => { const { state } = setup({ initial: { message: ['test'] } }); - state.on('reset_with_changes', keys => { + state.on('reset_with_changes', (keys) => { expect(keys).to.eql(['message']); done(); }); @@ -122,9 +119,9 @@ describe('State Management', () => { expect(search._s).to.equal('(test:foo)'); }); - it('should emit an event if changes are saved', done => { + it('should emit an event if changes are saved', (done) => { const { state, getUnhashedSearch } = setup(); - state.on('save_with_changes', keys => { + state.on('save_with_changes', (keys) => { expect(keys).to.eql(['test']); done(); }); @@ -136,9 +133,9 @@ describe('State Management', () => { }); describe('Fetch', () => { - it('should emit an event if changes are fetched', done => { + it('should emit an event if changes are fetched', (done) => { const { state } = setup(); - state.on('fetch_with_changes', keys => { + state.on('fetch_with_changes', (keys) => { expect(keys).to.eql(['foo']); done(); }); @@ -148,9 +145,9 @@ describe('State Management', () => { $rootScope.$apply(); }); - it('should have events that attach to scope', done => { + it('should have events that attach to scope', (done) => { const { state } = setup(); - state.on('test', message => { + state.on('test', (message) => { expect(message).to.equal('foo'); done(); }); @@ -158,9 +155,9 @@ describe('State Management', () => { $rootScope.$apply(); }); - it('should fire listeners for #onUpdate() on #fetch()', done => { + it('should fire listeners for #onUpdate() on #fetch()', (done) => { const { state } = setup(); - state.on('fetch_with_changes', keys => { + state.on('fetch_with_changes', (keys) => { expect(keys).to.eql(['foo']); done(); }); @@ -230,7 +227,7 @@ describe('State Management', () => { it('does not replace the state value on read', () => { const { state } = setup(); - sinon.stub($location, 'search').callsFake(newSearch => { + sinon.stub($location, 'search').callsFake((newSearch) => { if (newSearch) { return $location; } else { @@ -310,7 +307,7 @@ describe('State Management', () => { sinon.assert.calledOnce(fatalErrorStub); sinon.assert.calledWith( fatalErrorStub, - sinon.match(error => error instanceof Error && error.message.includes('github.com')) + sinon.match((error) => error instanceof Error && error.message.includes('github.com')) ); }); @@ -344,20 +341,17 @@ describe('State Management', () => { }; beforeEach( - ngMock.module('kibana', function(stateManagementConfigProvider) { + ngMock.module('kibana', function (stateManagementConfigProvider) { stateManagementConfigProvider.disable(); }) ); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private, config) { + ngMock.inject(function (_$rootScope_, _$location_, Private, config) { const State = Private(StateProvider); $location = _$location_; $rootScope = _$rootScope_; - sinon - .stub(config, 'get') - .withArgs('state:storeInSessionStorage') - .returns(false); + sinon.stub(config, 'get').withArgs('state:storeInSessionStorage').returns(false); class MockPersistedState extends State { _persistAcrossApps = true; @@ -372,7 +366,7 @@ describe('State Management', () => { describe('changing state', () => { const methods = ['save', 'replace', 'reset']; - methods.forEach(method => { + methods.forEach((method) => { it(`${method} should not change the URL`, () => { $location.search({ _s: '(foo:bar)' }); state[method](); diff --git a/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js b/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js index 601212d2da1a5..dc00d4e05e82f 100644 --- a/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js +++ b/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js @@ -23,7 +23,7 @@ import { EventEmitter } from 'events'; import { cloneDeep } from 'lodash'; import { stateMonitorFactory } from '../state_monitor_factory'; -describe('stateMonitorFactory', function() { +describe('stateMonitorFactory', function () { const noop = () => {}; const eventTypes = ['save_with_changes', 'reset_with_changes', 'fetch_with_changes']; @@ -44,27 +44,27 @@ describe('stateMonitorFactory', function() { mockState = createMockState({}); }); - it('should have a create method', function() { + it('should have a create method', function () { expect(stateMonitorFactory).to.have.property('create'); expect(stateMonitorFactory.create).to.be.a('function'); }); - describe('factory creation', function() { - it('should not call onChange with only the state', function() { + describe('factory creation', function () { + it('should not call onChange with only the state', function () { const monitor = stateMonitorFactory.create(mockState); const changeStub = sinon.stub(); monitor.onChange(changeStub); sinon.assert.notCalled(changeStub); }); - it('should not call onChange with matching defaultState', function() { + it('should not call onChange with matching defaultState', function () { const monitor = stateMonitorFactory.create(mockState, {}); const changeStub = sinon.stub(); monitor.onChange(changeStub); sinon.assert.notCalled(changeStub); }); - it('should call onChange with differing defaultState', function() { + it('should call onChange with differing defaultState', function () { const monitor = stateMonitorFactory.create(mockState, { test: true }); const changeStub = sinon.stub(); monitor.onChange(changeStub); @@ -72,21 +72,21 @@ describe('stateMonitorFactory', function() { }); }); - describe('instance', function() { + describe('instance', function () { let monitor; beforeEach(() => { monitor = stateMonitorFactory.create(mockState); }); - describe('onChange', function() { - it('should throw if not given a handler function', function() { + describe('onChange', function () { + it('should throw if not given a handler function', function () { const fn = () => monitor.onChange('not a function'); expect(fn).to.throwException(/must be a function/); }); - eventTypes.forEach(eventType => { - describe(`when ${eventType} is emitted`, function() { + eventTypes.forEach((eventType) => { + describe(`when ${eventType} is emitted`, function () { let handlerFn; beforeEach(() => { @@ -95,24 +95,24 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(handlerFn); }); - it('should get called', function() { + it('should get called', function () { mockState.emit(eventType); sinon.assert.calledOnce(handlerFn); }); - it('should be given the state status', function() { + it('should be given the state status', function () { mockState.emit(eventType); const args = handlerFn.firstCall.args; expect(args[0]).to.be.an('object'); }); - it('should be given the event type', function() { + it('should be given the event type', function () { mockState.emit(eventType); const args = handlerFn.firstCall.args; expect(args[1]).to.equal(eventType); }); - it('should be given the changed keys', function() { + it('should be given the changed keys', function () { const keys = ['one', 'two', 'three']; mockState.emit(eventType, keys); const args = handlerFn.firstCall.args; @@ -122,8 +122,8 @@ describe('stateMonitorFactory', function() { }); }); - describe('ignoreProps', function() { - it('should not set status to dirty when ignored properties change', function() { + describe('ignoreProps', function () { + it('should not set status to dirty when ignored properties change', function () { let status; const mockState = createMockState({ messages: { world: 'hello', foo: 'bar' } }); const monitor = stateMonitorFactory.create(mockState); @@ -148,7 +148,7 @@ describe('stateMonitorFactory', function() { }); }); - describe('setInitialState', function() { + describe('setInitialState', function () { let changeStub; beforeEach(() => { @@ -157,22 +157,22 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(changeStub); }); - it('should throw if no state is provided', function() { + it('should throw if no state is provided', function () { const fn = () => monitor.setInitialState(); expect(fn).to.throwException(/must be an object/); }); - it('should throw if given the wrong type', function() { + it('should throw if given the wrong type', function () { const fn = () => monitor.setInitialState([]); expect(fn).to.throwException(/must be an object/); }); - it('should trigger the onChange handler', function() { + it('should trigger the onChange handler', function () { monitor.setInitialState({ new: 'state' }); sinon.assert.calledOnce(changeStub); }); - it('should change the status with differing state', function() { + it('should change the status with differing state', function () { monitor.setInitialState({ new: 'state' }); sinon.assert.calledOnce(changeStub); @@ -181,13 +181,13 @@ describe('stateMonitorFactory', function() { expect(status).to.have.property('dirty', true); }); - it('should not trigger the onChange handler without state change', function() { + it('should not trigger the onChange handler without state change', function () { monitor.setInitialState(cloneDeep(mockState.toJSON())); sinon.assert.notCalled(changeStub); }); }); - describe('status object', function() { + describe('status object', function () { let handlerFn; beforeEach(() => { @@ -195,21 +195,21 @@ describe('stateMonitorFactory', function() { monitor.onChange(handlerFn); }); - it('should be clean by default', function() { + it('should be clean by default', function () { mockState.emit(eventTypes[0]); const status = handlerFn.firstCall.args[0]; expect(status).to.have.property('clean', true); expect(status).to.have.property('dirty', false); }); - it('should be dirty when state changes', function() { + it('should be dirty when state changes', function () { setState(mockState, { message: 'i am dirty now' }); const status = handlerFn.firstCall.args[0]; expect(status).to.have.property('clean', false); expect(status).to.have.property('dirty', true); }); - it('should be clean when state is reset', function() { + it('should be clean when state is reset', function () { const defaultState = { message: 'i am the original state' }; const handlerFn = sinon.stub(); @@ -237,7 +237,7 @@ describe('stateMonitorFactory', function() { }); }); - describe('destroy', function() { + describe('destroy', function () { let stateSpy; beforeEach(() => { @@ -245,16 +245,16 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(stateSpy); }); - it('should remove the listeners', function() { + it('should remove the listeners', function () { monitor.onChange(noop); monitor.destroy(); sinon.assert.callCount(stateSpy, eventTypes.length); - eventTypes.forEach(eventType => { + eventTypes.forEach((eventType) => { sinon.assert.calledWith(stateSpy, eventType); }); }); - it('should stop the instance from being used any more', function() { + it('should stop the instance from being used any more', function () { monitor.onChange(noop); monitor.destroy(); const fn = () => monitor.onChange(noop); diff --git a/src/legacy/ui/public/state_management/app_state.js b/src/legacy/ui/public/state_management/app_state.js index 76675b05e0fe5..ec680d163b9da 100644 --- a/src/legacy/ui/public/state_management/app_state.js +++ b/src/legacy/ui/public/state_management/app_state.js @@ -58,17 +58,17 @@ export function AppStateProvider(Private, $location) { // if the url param is missing, write it back AppState.prototype._persistAcrossApps = false; - AppState.prototype.destroy = function() { + AppState.prototype.destroy = function () { AppState.Super.prototype.destroy.call(this); AppState.getAppState._set(null); - eventUnsubscribers.forEach(listener => listener()); + eventUnsubscribers.forEach((listener) => listener()); }; /** * @returns PersistedState instance. */ - AppState.prototype.makeStateful = function(prop) { + AppState.prototype.makeStateful = function (prop) { if (persistedStates[prop]) return persistedStates[prop]; const self = this; @@ -76,25 +76,25 @@ export function AppStateProvider(Private, $location) { persistedStates[prop] = new PersistedState(); // update the app state when the stateful instance changes - const updateOnChange = function() { + const updateOnChange = function () { const replaceState = false; // TODO: debouncing logic self[prop] = persistedStates[prop].getChanges(); // Save state to the URL. self.save(replaceState); }; - const 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 - const persistOnChange = function(changes) { + const persistOnChange = function (changes) { if (!changes) return; if (changes.indexOf(prop) !== -1) { persistedStates[prop].set(self[prop]); } }; - const handlePersist = method => this[method]('fetch_with_changes', persistOnChange); + const handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); handlePersist('on'); eventUnsubscribers.push(() => handlePersist('off')); @@ -104,7 +104,7 @@ export function AppStateProvider(Private, $location) { return persistedStates[prop]; }; - AppState.getAppState = (function() { + AppState.getAppState = (function () { let currentAppState; function get() { @@ -112,12 +112,12 @@ export function AppStateProvider(Private, $location) { } // Checks to see if the appState might already exist, even if it hasn't been newed up - get.previouslyStored = function() { + get.previouslyStored = function () { const search = $location.search(); return search[urlParam] ? true : false; }; - get._set = function(current) { + get._set = function (current) { currentAppState = current; }; @@ -129,9 +129,9 @@ export function AppStateProvider(Private, $location) { uiModules .get('kibana/global_state') - .factory('AppState', function(Private) { + .factory('AppState', function (Private) { return Private(AppStateProvider); }) - .service('getAppState', function(Private) { + .service('getAppState', function (Private) { return Private(AppStateProvider).getAppState; }); diff --git a/src/legacy/ui/public/state_management/global_state.js b/src/legacy/ui/public/state_management/global_state.js index d8ff38106b978..0e8dfe40d5950 100644 --- a/src/legacy/ui/public/state_management/global_state.js +++ b/src/legacy/ui/public/state_management/global_state.js @@ -37,6 +37,6 @@ export function GlobalStateProvider(Private) { return new GlobalState(); } -module.service('globalState', function(Private) { +module.service('globalState', function (Private) { return Private(GlobalStateProvider); }); diff --git a/src/legacy/ui/public/state_management/state.js b/src/legacy/ui/public/state_management/state.js index c2274eae59f50..93428e9f8fa4e 100644 --- a/src/legacy/ui/public/state_management/state.js +++ b/src/legacy/ui/public/state_management/state.js @@ -90,7 +90,7 @@ export function StateProvider( this.fetch(); } - State.prototype._readFromURL = function() { + State.prototype._readFromURL = function () { const search = $location.search(); const urlVal = search[this._urlParam]; @@ -139,7 +139,7 @@ export function StateProvider( * Fetches the state from the url * @returns {void} */ - State.prototype.fetch = function() { + State.prototype.fetch = function () { if (!stateManagementConfig.enabled) { return; } @@ -168,7 +168,7 @@ export function StateProvider( * Saves the state to the url * @returns {void} */ - State.prototype.save = function(replace) { + State.prototype.save = function (replace) { if (!stateManagementConfig.enabled) { return; } @@ -207,7 +207,7 @@ export function StateProvider( * Calls save with a forced replace * @returns {void} */ - State.prototype.replace = function() { + State.prototype.replace = function () { if (!stateManagementConfig.enabled) { return; } @@ -220,7 +220,7 @@ export function StateProvider( * * @returns {void} */ - State.prototype.reset = function() { + State.prototype.reset = function () { if (!stateManagementConfig.enabled) { return; } @@ -239,14 +239,14 @@ export function StateProvider( * Cleans up the state object * @returns {void} */ - State.prototype.destroy = function() { + State.prototype.destroy = function () { this.off(); // removes all listeners // Removes the $routeUpdate listener - this._cleanUpListeners.forEach(listener => listener(this)); + this._cleanUpListeners.forEach((listener) => listener(this)); }; - State.prototype.setDefaults = function(defaults) { + State.prototype.setDefaults = function (defaults) { this._defaults = defaults || {}; }; @@ -257,7 +257,7 @@ export function StateProvider( * @param {string} stateHash - state hash value from the query string. * @return {any} - the stored value, or null if hash does not resolve. */ - State.prototype._parseStateHash = function(stateHash) { + State.prototype._parseStateHash = function (stateHash) { const json = this._hashedItemStore.getItem(stateHash); if (json === null) { toastNotifications.addDanger( @@ -278,7 +278,7 @@ export function StateProvider( * @param {string} stateHashOrRison - either state hash value or rison string. * @return {string} rison */ - State.prototype.translateHashToRison = function(stateHashOrRison) { + State.prototype.translateHashToRison = function (stateHashOrRison) { if (isStateHash(stateHashOrRison)) { return rison.encode(this._parseStateHash(stateHashOrRison)); } @@ -286,7 +286,7 @@ export function StateProvider( return stateHashOrRison; }; - State.prototype.isHashingEnabled = function() { + State.prototype.isHashingEnabled = function () { return !!config.get('state:storeInSessionStorage'); }; @@ -295,7 +295,7 @@ export function StateProvider( * * @return {string} */ - State.prototype.toQueryParam = function(state = this.toObject()) { + State.prototype.toQueryParam = function (state = this.toObject()) { if (!this.isHashingEnabled()) { return rison.encode(state); } @@ -330,7 +330,7 @@ export function StateProvider( * Get the query string parameter name where this state writes and reads * @return {string} */ - State.prototype.getQueryParamName = function() { + State.prototype.getQueryParamName = function () { return this._urlParam; }; @@ -340,7 +340,7 @@ export function StateProvider( * * @return {object} */ - State.prototype.toObject = function() { + State.prototype.toObject = function () { return _.omit(this, (value, key) => { return key.charAt(0) === '$' || key.charAt(0) === '_' || _.isFunction(value); }); @@ -351,7 +351,7 @@ export function StateProvider( * @obsolete Please use 'toObject' method instead * @return {object} */ - State.prototype.toJSON = function() { + State.prototype.toJSON = function () { return this.toObject(); }; diff --git a/src/legacy/ui/public/state_management/state_monitor_factory.ts b/src/legacy/ui/public/state_management/state_monitor_factory.ts index 27f3e59852569..454fefd4f8253 100644 --- a/src/legacy/ui/public/state_management/state_monitor_factory.ts +++ b/src/legacy/ui/public/state_management/state_monitor_factory.ts @@ -57,7 +57,7 @@ function stateMonitor( } function removeIgnoredProps(innerState: TStateDefault) { - ignoredProps.forEach(path => { + ignoredProps.forEach((path) => { set(innerState, path, true); }); return innerState; @@ -79,7 +79,7 @@ function stateMonitor( if (!changeHandlers) { throw new Error('Change handlers is undefined, this object has been destroyed'); } - changeHandlers.forEach(changeHandler => { + changeHandlers.forEach((changeHandler) => { changeHandler(status, type, keys); }); } diff --git a/src/legacy/ui/public/test_harness/test_harness.js b/src/legacy/ui/public/test_harness/test_harness.js index 22c78b1952e18..22c981fe0cf54 100644 --- a/src/legacy/ui/public/test_harness/test_harness.js +++ b/src/legacy/ui/public/test_harness/test_harness.js @@ -73,7 +73,7 @@ function createStubUiSettings() { createStubUiSettings(); sinon.stub(chrome, 'getUiSettingsClient').callsFake(() => stubUiSettings); -afterEach(function() { +afterEach(function () { createStubUiSettings(); }); diff --git a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js b/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js index f830b8208aea3..53800d08ca05b 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js +++ b/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js @@ -28,8 +28,8 @@ */ export function findTestBundleUrl() { const scriptTags = document.querySelectorAll('script[src]'); - const scriptUrls = [].map.call(scriptTags, el => el.getAttribute('src')); - const testBundleUrl = scriptUrls.find(url => url.includes('/tests.bundle.js')); + const scriptUrls = [].map.call(scriptTags, (el) => el.getAttribute('src')); + const testBundleUrl = scriptUrls.find((url) => url.includes('/tests.bundle.js')); if (!testBundleUrl) { throw new Error("test bundle url couldn't be found"); diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js b/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js index 0093102f72390..fce1876162387 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js +++ b/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js @@ -58,7 +58,7 @@ export function setupTestSharding() { }); // Filter top-level describe statements as they come - setupTopLevelDescribeFilter(describeName => { + setupTopLevelDescribeFilter((describeName) => { const describeShardNum = getShardNum(shardTotal, describeName); if (describeShardNum === shardNum) return true; // track shard numbers that we ignore diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js b/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js index 9790b5367af81..726f890077b94 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js +++ b/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js @@ -87,7 +87,7 @@ export function setupTopLevelDescribeFilter(test) { */ let describeCallDepth = 0; - const describeInterceptor = function(describeName, describeBody) { + const describeInterceptor = function (describeName, describeBody) { const context = this; const isTopLevelCall = describeCallDepth === 0; diff --git a/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js b/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js index 254ad3907e441..965e8f4bc9f38 100644 --- a/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js +++ b/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js @@ -21,100 +21,100 @@ import expect from '@kbn/expect'; import { extractAppPathAndId } from '../extract_app_path_and_id'; -describe('extractAppPathAndId', function() { - describe('from an absolute url with a base path', function() { - describe('with a base path', function() { +describe('extractAppPathAndId', function () { + describe('from an absolute url with a base path', function () { + describe('with a base path', function () { const basePath = '/gza'; const absoluteUrl = 'http://www.test.com:5601/gza/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(absoluteUrl, basePath).appPath).to.be( 'appPathIsHere?query=here' ); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl, basePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('http://www.test.com:5601/gza/noapppath'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('without a base path', function() { + describe('without a base path', function () { const absoluteUrl = 'http://www.test.com:5601/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(absoluteUrl).appPath).to.be('appPathIsHere?query=here'); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('http://www.test.com:5601/noapppath'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('when appPath is empty', function() { + describe('when appPath is empty', function () { const absoluteUrl = 'http://www.test.com:5601/app/appId'; - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl).appId).to.be('appId'); }); - it('extracts empty appPath', function() { + it('extracts empty appPath', function () { expect(extractAppPathAndId(absoluteUrl).appPath).to.be(''); }); }); }); - describe('from a root relative url', function() { - describe('with a base path', function() { + describe('from a root relative url', function () { + describe('with a base path', function () { const basePath = '/gza'; const rootRelativePath = '/gza/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(rootRelativePath, basePath).appPath).to.be( 'appPathIsHere?query=here' ); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath, basePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('/gza/notformattedright'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('without a base path', function() { + describe('without a base path', function () { const rootRelativePath = '/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(rootRelativePath).appPath).to.be('appPathIsHere?query=here'); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('/notformattedright'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('when appPath is empty', function() { + describe('when appPath is empty', function () { const rootRelativePath = '/app/appId'; - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath).appId).to.be('appId'); }); - it('extracts empty appPath', function() { + it('extracts empty appPath', function () { expect(extractAppPathAndId(rootRelativePath).appPath).to.be(''); }); }); diff --git a/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js b/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js index 422b1318bc82c..6ea199c3d22cc 100644 --- a/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js +++ b/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js @@ -21,8 +21,8 @@ import expect from '@kbn/expect'; import { KibanaParsedUrl } from '../kibana_parsed_url'; -describe('KibanaParsedUrl', function() { - it('getHashedAppPath', function() { +describe('KibanaParsedUrl', function () { + it('getHashedAppPath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/hi', appId: 'bye', @@ -31,7 +31,7 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getHashedAppPath()).to.be('#visualize?hi=there&bye'); }); - it('getAppRootPath', function() { + it('getAppRootPath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/hi', appId: 'appId', @@ -40,8 +40,8 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getAppRootPath()).to.be('/app/appId#dashboard?edit=123'); }); - describe('when basePath is specified', function() { - it('getRootRelativePath', function() { + describe('when basePath is specified', function () { + it('getRootRelativePath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -50,12 +50,12 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getRootRelativePath()).to.be('/base/app/appId#visualize?hi=there&bye'); }); - describe('getAbsolutePath', function() { + describe('getAbsolutePath', function () { const protocol = 'http'; const hostname = 'www.test.com'; const port = '5601'; - it('returns the absolute url when there is a port', function() { + it('returns the absolute url when there is a port', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -69,7 +69,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when there are no query parameters', function() { + it('returns the absolute url when there are no query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -82,7 +82,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when the are query parameters', function() { + it('returns the absolute url when the are query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -97,8 +97,8 @@ describe('KibanaParsedUrl', function() { }); }); - describe('when basePath is not specified', function() { - it('getRootRelativePath', function() { + describe('when basePath is not specified', function () { + it('getRootRelativePath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=there&bye', @@ -106,12 +106,12 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getRootRelativePath()).to.be('/app/appId#visualize?hi=there&bye'); }); - describe('getAbsolutePath', function() { + describe('getAbsolutePath', function () { const protocol = 'http'; const hostname = 'www.test.com'; const port = '5601'; - it('returns the absolute url when there is a port', function() { + it('returns the absolute url when there is a port', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=there&bye', @@ -124,7 +124,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when there are no query parameters', function() { + it('returns the absolute url when there are no query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize', @@ -134,7 +134,7 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getAbsoluteUrl()).to.be('http://www.test.com/app/appId#visualize'); }); - it('returns the absolute url when there are query parameters', function() { + it('returns the absolute url when there are query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=bye&tata', @@ -148,21 +148,21 @@ describe('KibanaParsedUrl', function() { }); }); - describe('getGlobalState', function() { + describe('getGlobalState', function () { const basePath = '/xyz'; const appId = 'myApp'; - it('returns an empty string when the KibanaParsedUrl is in an invalid state', function() { + it('returns an empty string when the KibanaParsedUrl is in an invalid state', function () { const url = new KibanaParsedUrl({ basePath }); expect(url.getGlobalState()).to.be(''); }); - it('returns an empty string when there is no global state', function() { + it('returns an empty string when there is no global state', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi?notg=something' }); expect(url.getGlobalState()).to.be(''); }); - it('returns the global state when it is the last parameter', function() { + it('returns the global state when it is the last parameter', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -171,7 +171,7 @@ describe('KibanaParsedUrl', function() { expect(url.getGlobalState()).to.be('(thisismyglobalstate)'); }); - it('returns the global state when it is the first parameter', function() { + it('returns the global state when it is the first parameter', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -181,23 +181,23 @@ describe('KibanaParsedUrl', function() { }); }); - describe('setGlobalState', function() { + describe('setGlobalState', function () { const basePath = '/xyz'; const appId = 'myApp'; - it('does nothing when KibanaParsedUrl is in an invalid state', function() { + it('does nothing when KibanaParsedUrl is in an invalid state', function () { const url = new KibanaParsedUrl({ basePath }); url.setGlobalState('newglobalstate'); expect(url.getGlobalState()).to.be(''); }); - it('clears the global state when setting it to an empty string', function() { + it('clears the global state when setting it to an empty string', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi?_g=globalstate' }); url.setGlobalState(''); expect(url.getGlobalState()).to.be(''); }); - it('updates the global state when a string is passed in', function() { + it('updates the global state when a string is passed in', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -207,7 +207,7 @@ describe('KibanaParsedUrl', function() { expect(url.getGlobalState()).to.be('newstate'); }); - it('adds the global state parameters if it did not exist before', function() { + it('adds the global state parameters if it did not exist before', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi' }); url.setGlobalState('newstate'); expect(url.getGlobalState()).to.be('newstate'); diff --git a/src/legacy/ui/public/url/__tests__/prepend_path.js b/src/legacy/ui/public/url/__tests__/prepend_path.js index 488a16e17410e..36991b77553e4 100644 --- a/src/legacy/ui/public/url/__tests__/prepend_path.js +++ b/src/legacy/ui/public/url/__tests__/prepend_path.js @@ -21,59 +21,59 @@ import expect from '@kbn/expect'; import { prependPath } from '../prepend_path'; -describe('url prependPath', function() { - describe('returns the relative path unchanged', function() { - it('if it is null', function() { +describe('url prependPath', function () { + describe('returns the relative path unchanged', function () { + it('if it is null', function () { expect(prependPath(null, 'kittens')).to.be(null); }); - it('if it is undefined', function() { + it('if it is undefined', function () { expect(prependPath(undefined, 'kittens')).to.be(undefined); }); - it('if it is an absolute url', function() { + it('if it is an absolute url', function () { expect(prependPath('http://www.hithere.com/howareyou', 'welcome')).to.be( 'http://www.hithere.com/howareyou' ); }); - it('if it does not start with a /', function() { + it('if it does not start with a /', function () { expect(prependPath('are/so/cool', 'cats')).to.be('are/so/cool'); }); - it('when new path is empty', function() { + it('when new path is empty', function () { expect(prependPath('/are/so/cool', '')).to.be('/are/so/cool'); }); - it('when it is only a slash and new path is empty', function() { + it('when it is only a slash and new path is empty', function () { expect(prependPath('/', '')).to.be('/'); }); }); - describe('returns an updated relative path', function() { - it('when it starts with a slash', function() { + describe('returns an updated relative path', function () { + it('when it starts with a slash', function () { expect(prependPath('/are/so/cool', 'dinosaurs')).to.be('dinosaurs/are/so/cool'); }); - it('when new path starts with a slash', function() { + it('when new path starts with a slash', function () { expect(prependPath('/are/so/cool', '/fish')).to.be('/fish/are/so/cool'); }); - it('with two slashes if new path is a slash', function() { + it('with two slashes if new path is a slash', function () { expect(prependPath('/are/so/cool', '/')).to.be('//are/so/cool'); }); - it('when there is a slash on the end', function() { + it('when there is a slash on the end', function () { expect(prependPath('/are/delicious/', 'lollipops')).to.be('lollipops/are/delicious/'); }); - it('when pathname that ends with a file', function() { + it('when pathname that ends with a file', function () { expect(prependPath('/are/delicious/index.html', 'donuts')).to.be( 'donuts/are/delicious/index.html' ); }); - it('when it is only a slash', function() { + it('when it is only a slash', function () { expect(prependPath('/', 'kittens')).to.be('kittens/'); }); }); diff --git a/src/legacy/ui/public/url/__tests__/url.js b/src/legacy/ui/public/url/__tests__/url.js index 999bef24ac5e2..8b173482e1bb4 100644 --- a/src/legacy/ui/public/url/__tests__/url.js +++ b/src/legacy/ui/public/url/__tests__/url.js @@ -41,22 +41,22 @@ class StubAppState { } function init() { - ngMock.module('kibana/url', 'kibana', function($provide, PrivateProvider) { - $provide.service('$route', function() { + ngMock.module('kibana/url', 'kibana', function ($provide, PrivateProvider) { + $provide.service('$route', function () { return { reload: _.noop, }; }); appState = new StubAppState(); - PrivateProvider.swap(AppStateProvider, $decorate => { + PrivateProvider.swap(AppStateProvider, ($decorate) => { const AppState = $decorate(); AppState.getAppState = () => appState; return AppState; }); }); - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $route = $injector.get('$route'); $location = $injector.get('$location'); $rootScope = $injector.get('$rootScope'); @@ -64,13 +64,13 @@ function init() { }); } -describe('kbnUrl', function() { - beforeEach(function() { +describe('kbnUrl', function () { + beforeEach(function () { init(); }); - describe('forcing reload', function() { - it('schedules a listener for $locationChangeSuccess on the $rootScope', function() { + describe('forcing reload', function () { + it('schedules a listener for $locationChangeSuccess on the $rootScope', function () { $location.url('/url'); $route.current = { $$route: { @@ -87,7 +87,7 @@ describe('kbnUrl', function() { expect($rootScope.$on.firstCall.args[0]).to.be('$locationChangeSuccess'); }); - it('handler unbinds the listener and calls reload', function() { + it('handler unbinds the listener and calls reload', function () { $location.url('/url'); $route.current = { $$route: { @@ -109,7 +109,7 @@ describe('kbnUrl', function() { expect($route.reload.callCount).to.be(1); }); - it('reloads requested before the first are ignored', function() { + it('reloads requested before the first are ignored', function () { $location.url('/url'); $route.current = { $$route: { @@ -130,7 +130,7 @@ describe('kbnUrl', function() { expect($rootScope.$on.callCount).to.be(1); }); - it('one reload can happen once the first has completed', function() { + it('one reload can happen once the first has completed', function () { $location.url('/url'); $route.current = { $$route: { @@ -155,34 +155,34 @@ describe('kbnUrl', function() { }); }); - describe('remove', function() { - it('removes a parameter with a value from the url', function() { + describe('remove', function () { + it('removes a parameter with a value from the url', function () { $location.url('/myurl?exist&WithAParamToRemove=2&anothershouldexist=5'); kbnUrl.removeParam('WithAParamToRemove'); expect($location.url()).to.be('/myurl?exist&anothershouldexist=5'); }); - it('removes a parameter with no value from the url', function() { + it('removes a parameter with no value from the url', function () { $location.url('/myurl?removeme&hi=5'); kbnUrl.removeParam('removeme'); expect($location.url()).to.be('/myurl?hi=5'); }); - it('is noop if the given parameter doesn\t exist in the url', function() { + it('is noop if the given parameter doesn\t exist in the url', function () { $location.url('/myurl?hi&bye'); kbnUrl.removeParam('noexist'); expect($location.url()).to.be('/myurl?hi&bye'); }); - it('is noop if given empty string param', function() { + it('is noop if given empty string param', function () { $location.url('/myurl?hi&bye'); kbnUrl.removeParam(''); expect($location.url()).to.be('/myurl?hi&bye'); }); }); - describe('change', function() { - it('should set $location.url', function() { + describe('change', function () { + it('should set $location.url', function () { sinon.stub($location, 'url'); expect($location.url.callCount).to.be(0); @@ -190,7 +190,7 @@ describe('kbnUrl', function() { expect($location.url.callCount).to.be(1); }); - it('should uri encode replaced params', function() { + it('should uri encode replaced params', function () { const url = '/some/path/'; const params = { replace: faker.Lorem.words(3).join(' ') }; const check = encodeURIComponent(params.replace); @@ -201,7 +201,7 @@ describe('kbnUrl', function() { expect($location.url.firstCall.args[0]).to.be(url + check); }); - it('should parse angular expression in substitutions and uri encode the results', function() { + it('should parse angular expression in substitutions and uri encode the results', function () { // build url by piecing together these parts const urlParts = ['/', '/', '?', '&', '#']; // make sure it can parse templates with weird spacing @@ -219,14 +219,14 @@ describe('kbnUrl', function() { // the words (template keys) used must all be unique const words = _.uniq(faker.Lorem.words(10)) .slice(0, urlParts.length) - .map(function(word, i) { + .map(function (word, i) { if (filters[i].length) { return word + '|' + filters[i]; } return word; }); - const replacements = faker.Lorem.words(urlParts.length).map(function(word, i) { + const replacements = faker.Lorem.words(urlParts.length).map(function (word, i) { // make selected replacement into an object if (i === objIndex) { return { replace: word }; @@ -238,7 +238,7 @@ describe('kbnUrl', function() { // build the url and test url let url = ''; let testUrl = ''; - urlParts.forEach(function(part, i) { + urlParts.forEach(function (part, i) { url += part + wrappers[i][0] + words[i] + wrappers[i][1]; const locals = {}; locals[words[i].split('|')[0]] = replacements[i]; @@ -247,7 +247,7 @@ describe('kbnUrl', function() { // create the locals replacement object const params = {}; - replacements.forEach(function(replacement, i) { + replacements.forEach(function (replacement, i) { const word = words[i].split('|')[0]; params[word] = replacement; }); @@ -260,7 +260,7 @@ describe('kbnUrl', function() { expect($location.url.firstCall.args[0]).to.be(testUrl); }); - it('should handle dot notation', function() { + it('should handle dot notation', function () { const url = '/some/thing/{{that.is.substituted}}'; kbnUrl.change(url, { @@ -274,7 +274,7 @@ describe('kbnUrl', function() { expect($location.url()).to.be('/some/thing/test'); }); - it('should throw when params are missing', function() { + it('should throw when params are missing', function () { const url = '/{{replace_me}}'; const params = {}; @@ -287,7 +287,7 @@ describe('kbnUrl', function() { } }); - it('should throw when filtered params are missing', function() { + it('should throw when filtered params are missing', function () { const url = '/{{replace_me|number}}'; const params = {}; @@ -300,16 +300,13 @@ describe('kbnUrl', function() { } }); - it('should change the entire url', function() { + it('should change the entire url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -324,16 +321,13 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should allow setting app state on the target url', function() { + it('should allow setting app state on the target url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -349,17 +343,14 @@ describe('kbnUrl', function() { }); }); - describe('changePath', function() { - it('should change just the path', function() { + describe('changePath', function () { + it('should change just the path', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -375,17 +366,14 @@ describe('kbnUrl', function() { }); }); - describe('redirect', function() { - it('should change the entire url', function() { + describe('redirect', function () { + it('should change the entire url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -400,16 +388,13 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should allow setting app state on the target url', function() { + it('should allow setting app state on the target url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -424,7 +409,7 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should replace the current history entry', function() { + it('should replace the current history entry', function () { sinon.stub($location, 'replace'); $location.url('/some/path'); @@ -433,7 +418,7 @@ describe('kbnUrl', function() { expect($location.replace.callCount).to.be(1); }); - it('should call replace on $location', function() { + it('should call replace on $location', function () { sinon.stub(kbnUrl, '_shouldForceReload').returns(false); sinon.stub($location, 'replace'); @@ -443,17 +428,14 @@ describe('kbnUrl', function() { }); }); - describe('redirectPath', function() { - it('should only change the path', function() { + describe('redirectPath', function () { + it('should only change the path', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -468,7 +450,7 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(hash); }); - it('should call replace on $location', function() { + it('should call replace on $location', function () { sinon.stub(kbnUrl, '_shouldForceReload').returns(false); sinon.stub($location, 'replace'); @@ -478,11 +460,11 @@ describe('kbnUrl', function() { }); }); - describe('_shouldForceReload', function() { + describe('_shouldForceReload', function () { let next; let prev; - beforeEach(function() { + beforeEach(function () { $route.current = { $$route: { regexp: /^\/is-current-route\/(\d+)/, @@ -494,21 +476,21 @@ describe('kbnUrl', function() { next = { path: '/is-current-route/1', search: {} }; }); - it("returns false if the passed url doesn't match the current route", function() { + it("returns false if the passed url doesn't match the current route", function () { next.path = '/not current'; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); - describe('if the passed url does match the route', function() { - describe('and the route reloads on search', function() { - describe('and the path is the same', function() { - describe('and the search params are the same', function() { - it('returns true', function() { + describe('if the passed url does match the route', function () { + describe('and the route reloads on search', function () { + describe('and the path is the same', function () { + describe('and the search params are the same', function () { + it('returns true', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); @@ -516,18 +498,18 @@ describe('kbnUrl', function() { }); }); - describe('and the path is different', function() { - beforeEach(function() { + describe('and the path is different', function () { + beforeEach(function () { next.path = '/not-same'; }); - describe('and the search params are the same', function() { - it('returns false', function() { + describe('and the search params are the same', function () { + it('returns false', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); @@ -536,19 +518,19 @@ describe('kbnUrl', function() { }); }); - describe('but the route does not reload on search', function() { - beforeEach(function() { + describe('but the route does not reload on search', function () { + beforeEach(function () { $route.current.$$route.reloadOnSearch = false; }); - describe('and the path is the same', function() { - describe('and the search params are the same', function() { - it('returns true', function() { + describe('and the path is the same', function () { + describe('and the search params are the same', function () { + it('returns true', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); }); }); - describe('but the search params are different', function() { - it('returns true', function() { + describe('but the search params are different', function () { + it('returns true', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); @@ -556,18 +538,18 @@ describe('kbnUrl', function() { }); }); - describe('and the path is different', function() { - beforeEach(function() { + describe('and the path is different', function () { + beforeEach(function () { next.path = '/not-same'; }); - describe('and the search params are the same', function() { - it('returns false', function() { + describe('and the search params are the same', function () { + it('returns false', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); diff --git a/src/legacy/ui/public/url/kibana_parsed_url.ts b/src/legacy/ui/public/url/kibana_parsed_url.ts index 712dfd119c615..1c60e8729e0ff 100644 --- a/src/legacy/ui/public/url/kibana_parsed_url.ts +++ b/src/legacy/ui/public/url/kibana_parsed_url.ts @@ -111,13 +111,13 @@ export class KibanaParsedUrl { return; } - this.appPath = modifyUrl(this.appPath, parsed => { + this.appPath = modifyUrl(this.appPath, (parsed) => { parsed.query._g = newGlobalState; }); } public addQueryParameter(name: string, val: string) { - this.appPath = modifyUrl(this.appPath, parsed => { + this.appPath = modifyUrl(this.appPath, (parsed) => { parsed.query[name] = val; }); } @@ -139,7 +139,7 @@ export class KibanaParsedUrl { } public getAbsoluteUrl() { - return modifyUrl(this.getRootRelativePath(), parsed => { + return modifyUrl(this.getRootRelativePath(), (parsed) => { parsed.protocol = this.protocol; parsed.port = this.port; parsed.hostname = this.hostname; diff --git a/src/legacy/ui/public/url/redirect_when_missing.js b/src/legacy/ui/public/url/redirect_when_missing.js index e6b4a488160dd..85c90a14d9fd7 100644 --- a/src/legacy/ui/public/url/redirect_when_missing.js +++ b/src/legacy/ui/public/url/redirect_when_missing.js @@ -24,7 +24,7 @@ import { toastNotifications } from 'ui/notify'; import { SavedObjectNotFound } from '../../../../plugins/kibana_utils/public'; import { uiModules } from '../modules'; -uiModules.get('kibana/url').service('redirectWhenMissing', function(Private) { +uiModules.get('kibana/url').service('redirectWhenMissing', function (Private) { return Private(RedirectWhenMissingProvider); }); @@ -37,12 +37,12 @@ export function RedirectWhenMissingProvider(kbnUrl, Promise) { * couldn't be found, or just a string that will be used for all types * @return {function} - the handler to pass to .catch() */ - return function(mapping) { + return function (mapping) { if (typeof mapping === 'string') { mapping = { '*': mapping }; } - return function(error) { + return function (error) { // if this error is not "404", rethrow const savedObjectNotFound = error instanceof SavedObjectNotFound; const unknownVisType = error.message.indexOf('Invalid type') === 0; diff --git a/src/legacy/ui/public/url/url.js b/src/legacy/ui/public/url/url.js index 8c854950784c4..fb243b02e05c7 100644 --- a/src/legacy/ui/public/url/url.js +++ b/src/legacy/ui/public/url/url.js @@ -22,7 +22,7 @@ import { i18n } from '@kbn/i18n'; import { uiModules } from '../modules'; import { AppStateProvider } from '../state_management/app_state'; -uiModules.get('kibana/url').service('kbnUrl', function(Private, $injector) { +uiModules.get('kibana/url').service('kbnUrl', function (Private, $injector) { //config is not directly used but registers global event listeners to kbnUrl to function $injector.get('config'); return Private(KbnUrlProvider); @@ -56,7 +56,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.change = function(url, paramObj, appState) { + self.change = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, false, appState); }; @@ -68,7 +68,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.changePath = function(path, paramObj) { + self.changePath = function (path, paramObj) { self._changeLocation('path', path, paramObj); }; @@ -79,7 +79,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.redirect = function(url, paramObj, appState) { + self.redirect = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, true, appState); }; @@ -91,7 +91,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.redirectPath = function(path, paramObj) { + self.redirectPath = function (path, paramObj) { self._changeLocation('path', path, paramObj, true); }; @@ -104,10 +104,10 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @return {String} - the evaluated result * @throws {Error} If any of the expressions can't be parsed. */ - self.eval = function(template, paramObj) { + self.eval = function (template, paramObj) { paramObj = paramObj || {}; - return template.replace(/\{\{([^\}]+)\}\}/g, function(match, expr) { + return template.replace(/\{\{([^\}]+)\}\}/g, function (match, expr) { // remove filters const key = expr.split('|')[0].trim(); @@ -136,7 +136,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {string} - the computed href */ - self.getRouteHref = function(obj, route) { + self.getRouteHref = function (obj, route) { return '#' + self.getRouteUrl(obj, route); }; @@ -147,7 +147,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {string} - the computed url */ - self.getRouteUrl = function(obj, route) { + self.getRouteUrl = function (obj, route) { const template = obj && obj.routes && obj.routes[route]; if (template) return self.eval(template, obj); }; @@ -160,7 +160,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {undefined} */ - self.redirectToRoute = function(obj, route) { + self.redirectToRoute = function (obj, route) { self.redirect(self.getRouteUrl(obj, route)); }; @@ -172,7 +172,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {undefined} */ - self.changeToRoute = function(obj, route) { + self.changeToRoute = function (obj, route) { self.change(self.getRouteUrl(obj, route)); }; @@ -181,7 +181,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * history. * @param param */ - self.removeParam = function(param) { + self.removeParam = function (param) { $location.search(param, null).replace(); }; @@ -190,7 +190,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private ///// let reloading; - self._changeLocation = function(type, url, paramObj, replace, appState) { + self._changeLocation = function (type, url, paramObj, replace, appState) { const prev = { path: $location.path(), search: $location.search(), @@ -216,7 +216,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private const appState = Private(AppStateProvider).getAppState(); if (appState) appState.destroy(); - reloading = $rootScope.$on('$locationChangeSuccess', function() { + reloading = $rootScope.$on('$locationChangeSuccess', function () { // call the "unlisten" function returned by $on reloading(); reloading = false; @@ -228,7 +228,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private }; // determine if the router will automatically reload the route - self._shouldForceReload = function(next, prev, $route) { + self._shouldForceReload = function (next, prev, $route) { if (reloading) return false; const route = $route.current && $route.current.$$route; diff --git a/src/legacy/ui/public/utils/legacy_class.js b/src/legacy/ui/public/utils/legacy_class.js index 0aebdd4f5b667..f47650a77bb6d 100644 --- a/src/legacy/ui/public/utils/legacy_class.js +++ b/src/legacy/ui/public/utils/legacy_class.js @@ -29,7 +29,7 @@ function describeConst(val) { } const props = { - inherits: describeConst(function(SuperClass) { + inherits: describeConst(function (SuperClass) { const prototype = Object.create(SuperClass.prototype, { constructor: describeConst(this), superConstructor: describeConst(SuperClass), diff --git a/src/legacy/ui/ui_apps/__tests__/ui_app.js b/src/legacy/ui/ui_apps/__tests__/ui_app.js index 50cefd7032e11..bb4bcfe2d7443 100644 --- a/src/legacy/ui/ui_apps/__tests__/ui_app.js +++ b/src/legacy/ui/ui_apps/__tests__/ui_app.js @@ -41,10 +41,7 @@ function createStubKbnServer(extraParams) { return { plugins: [], config: { - get: sinon - .stub() - .withArgs('server.basePath') - .returns(''), + get: sinon.stub().withArgs('server.basePath').returns(''), }, server: {}, ...extraParams, @@ -288,7 +285,7 @@ describe('ui apps / UiApp', () => { it('throws an error at instantiation', () => { expect(() => { createUiApp(createStubUiAppSpec({ pluginId: 'foo' })); - }).to.throwException(error => { + }).to.throwException((error) => { expect(error.message).to.match(/Unknown plugin id/); }); }); diff --git a/src/legacy/ui/ui_apps/ui_app.js b/src/legacy/ui/ui_apps/ui_app.js index 926db5836e9d1..7da9e39394deb 100644 --- a/src/legacy/ui/ui_apps/ui_app.js +++ b/src/legacy/ui/ui_apps/ui_app.js @@ -109,7 +109,7 @@ export class UiApp { const pluginId = this._pluginId; const { plugins } = this._kbnServer; - return pluginId ? plugins.find(plugin => plugin.id === pluginId) : undefined; + return pluginId ? plugins.find((plugin) => plugin.id === pluginId) : undefined; } toJSON() { diff --git a/src/legacy/ui/ui_apps/ui_apps_mixin.js b/src/legacy/ui/ui_apps/ui_apps_mixin.js index 5165c9859fec5..c80b12a46bee3 100644 --- a/src/legacy/ui/ui_apps/ui_apps_mixin.js +++ b/src/legacy/ui/ui_apps/ui_apps_mixin.js @@ -34,7 +34,7 @@ export function uiAppsMixin(kbnServer, server) { const appsById = new Map(); const hiddenAppsById = new Map(); - kbnServer.uiApps = uiAppSpecs.map(spec => { + kbnServer.uiApps = uiAppSpecs.map((spec) => { const app = new UiApp(kbnServer, spec); const id = app.getId(); @@ -54,14 +54,14 @@ export function uiAppsMixin(kbnServer, server) { }); server.decorate('server', 'getAllUiApps', () => kbnServer.uiApps.slice(0)); - server.decorate('server', 'getUiAppById', id => appsById.get(id)); - server.decorate('server', 'getHiddenUiAppById', id => hiddenAppsById.get(id)); + server.decorate('server', 'getUiAppById', (id) => appsById.get(id)); + server.decorate('server', 'getHiddenUiAppById', (id) => hiddenAppsById.get(id)); server.decorate('server', 'injectUiAppVars', (appId, provider) => kbnServer.newPlatform.__internals.legacy.injectUiAppVars(appId, provider) ); server.decorate( 'server', 'getInjectedUiAppVars', - async appId => await kbnServer.newPlatform.__internals.legacy.getInjectedUiAppVars(appId) + async (appId) => await kbnServer.newPlatform.__internals.legacy.getInjectedUiAppVars(appId) ); } diff --git a/src/legacy/ui/ui_bundles/app_entry_template.js b/src/legacy/ui/ui_bundles/app_entry_template.js index 683fedd34316f..a48de9a8cf7ee 100644 --- a/src/legacy/ui/ui_bundles/app_entry_template.js +++ b/src/legacy/ui/ui_bundles/app_entry_template.js @@ -19,7 +19,7 @@ import { apmImport, apmInit } from '../apm'; -export const appEntryTemplate = bundle => ` +export const appEntryTemplate = (bundle) => ` /** * Kibana entry file * diff --git a/src/legacy/ui/ui_bundles/ui_bundle.js b/src/legacy/ui/ui_bundles/ui_bundle.js index a8d4259fb98f2..4e853ad410efe 100644 --- a/src/legacy/ui/ui_bundles/ui_bundle.js +++ b/src/legacy/ui/ui_bundles/ui_bundle.js @@ -57,7 +57,7 @@ export class UiBundle { } getRequires() { - return this._modules.map(module => `require('${normalizePath(module)}');`); + return this._modules.map((module) => `require('${normalizePath(module)}');`); } renderContent() { @@ -66,7 +66,7 @@ export class UiBundle { async readEntryFile() { try { - const content = await fcb(cb => readFile(this.getEntryPath(), cb)); + const content = await fcb((cb) => readFile(this.getEntryPath(), cb)); return content.toString('utf8'); } catch (e) { return null; @@ -74,11 +74,11 @@ export class UiBundle { } async writeEntryFile() { - return await fcb(cb => writeFile(this.getEntryPath(), this.renderContent(), 'utf8', cb)); + return await fcb((cb) => writeFile(this.getEntryPath(), this.renderContent(), 'utf8', cb)); } async touchStyleFile() { - return await fcb(cb => writeFile(this.getStylePath(), '', 'utf8', cb)); + return await fcb((cb) => writeFile(this.getStylePath(), '', 'utf8', cb)); } /** @@ -98,8 +98,8 @@ export class UiBundle { } try { - await fcb(cb => stat(this.getOutputPath(), cb)); - await fcb(cb => stat(this.getStylePath(), cb)); + await fcb((cb) => stat(this.getOutputPath(), cb)); + await fcb((cb) => stat(this.getStylePath(), cb)); return true; } catch (e) { return false; diff --git a/src/legacy/ui/ui_bundles/ui_bundles_controller.js b/src/legacy/ui/ui_bundles/ui_bundles_controller.js index 79112fd687e84..dadb28cbb2f3a 100644 --- a/src/legacy/ui/ui_bundles/ui_bundles_controller.js +++ b/src/legacy/ui/ui_bundles/ui_bundles_controller.js @@ -56,7 +56,7 @@ function stableCloneAppExtensions(appExtensions) { Object.entries(appExtensions).map(([extensionType, moduleIds]) => [ extensionType, moduleIds - .map(moduleId => { + .map((moduleId) => { if (isAbsolute(moduleId)) { moduleId = `absolute:${relative(REPO_ROOT, moduleId)}`; } @@ -246,7 +246,7 @@ export class UiBundlesController { } getIds() { - return this._bundles.map(bundle => bundle.getId()); + return this._bundles.map((bundle) => bundle.getId()); } getExtendedConfig(webpackConfig) { diff --git a/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js b/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js index 352e8642e930e..3686a2dad8f24 100644 --- a/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js +++ b/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js @@ -106,7 +106,7 @@ describe('plugin discovery', () => { uiExports: { migrations: { 'test-type': { - '1.2.3': doc => { + '1.2.3': (doc) => { return doc; }, }, @@ -116,7 +116,7 @@ describe('plugin discovery', () => { ]; }, }).getPluginSpecs(); - expect(() => collectUiExports(invalidSpecs)).to.throwError(err => { + expect(() => collectUiExports(invalidSpecs)).to.throwError((err) => { expect(err).to.be.a(Error); expect(err).to.have.property( 'message', diff --git a/src/legacy/ui/ui_exports/ui_export_defaults.js b/src/legacy/ui/ui_exports/ui_export_defaults.js index 1341777bc0991..d60bf7df899e3 100644 --- a/src/legacy/ui/ui_exports/ui_export_defaults.js +++ b/src/legacy/ui/ui_exports/ui_export_defaults.js @@ -33,7 +33,7 @@ export const UI_EXPORT_DEFAULTS = { test_harness: resolve(ROOT, 'src/test_harness/public'), }, - styleSheetPaths: ['light', 'dark'].map(theme => ({ + styleSheetPaths: ['light', 'dark'].map((theme) => ({ theme, localPath: resolve(ROOT, 'src/core/public/index.scss'), publicPath: `core.${theme}.css`, diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js index 511e7c20bd3b0..a894e59a03c81 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js @@ -24,5 +24,5 @@ * @param {String} newType * @return {Function} */ -export const alias = newType => next => (acc, spec, type, pluginSpec) => +export const alias = (newType) => (next) => (acc, spec, type, pluginSpec) => next(acc, spec, newType, pluginSpec); diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js index de0cfb177b6e9..5970c45e7445e 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js @@ -25,5 +25,5 @@ * @param {Function} mapFn receives `(specs, type, pluginSpec)` * @return {Function} */ -export const mapSpec = mapFn => next => (acc, spec, type, pluginSpec) => +export const mapSpec = (mapFn) => (next) => (acc, spec, type, pluginSpec) => next(acc, mapFn(spec, type, pluginSpec), type, pluginSpec); diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js index 9a2519f79eda8..dedcd057b09e3 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js @@ -17,10 +17,10 @@ * under the License. */ -const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); +const pluginId = (pluginSpec) => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); -export const uniqueKeys = sourceType => next => (acc, spec, type, pluginSpec) => { - const duplicates = Object.keys(spec).filter(key => acc[type] && acc[type].hasOwnProperty(key)); +export const uniqueKeys = (sourceType) => (next) => (acc, spec, type, pluginSpec) => { + const duplicates = Object.keys(spec).filter((key) => acc[type] && acc[type].hasOwnProperty(key)); if (duplicates.length) { throw new Error( diff --git a/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js b/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js index a4df5debf1316..bf4793c208308 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js +++ b/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js @@ -26,7 +26,7 @@ * @param {Function} reducer * @return {Function} */ -export const createTypeReducer = reducer => (acc, spec, type, pluginSpec) => ({ +export const createTypeReducer = (reducer) => (acc, spec, type, pluginSpec) => ({ ...acc, [type]: reducer(acc[type], spec, type, pluginSpec), }); diff --git a/src/legacy/ui/ui_exports/ui_export_types/saved_object.js b/src/legacy/ui/ui_exports/ui_export_types/saved_object.js index 63a3c5f036993..be6898d3e642c 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/saved_object.js +++ b/src/legacy/ui/ui_exports/ui_export_types/saved_object.js @@ -30,7 +30,7 @@ export const mappings = wrap( flatConcatAtType ); -const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); +const pluginId = (pluginSpec) => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); // Combines the `migrations` property of each plugin, // ensuring that properties are unique across plugins @@ -38,9 +38,9 @@ const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.get // See saved_objects/migrations for more details. export const migrations = wrap( alias('savedObjectMigrations'), - next => (acc, spec, type, pluginSpec) => { + (next) => (acc, spec, type, pluginSpec) => { const mappings = pluginSpec.getExportSpecs().mappings || {}; - const invalidMigrationTypes = Object.keys(spec).filter(type => !mappings[type]); + const invalidMigrationTypes = Object.keys(spec).filter((type) => !mappings[type]); if (invalidMigrationTypes.length) { throw new Error( 'Migrations and mappings must be defined together in the uiExports of a single plugin. ' + diff --git a/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js b/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js index e3e051cbfac7e..6a1fa7bdf3633 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js +++ b/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js @@ -28,8 +28,8 @@ const pluginSpec = { }; expect.addSnapshotSerializer({ - test: value => typeof value === 'string' && value.startsWith(dir), - print: value => value.replace(dir, '').replace(/\\/g, '/'), + test: (value) => typeof value === 'string' && value.startsWith(dir), + print: (value) => value.replace(dir, '').replace(/\\/g, '/'), }); describe('uiExports.styleSheetPaths', () => { diff --git a/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js b/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js index 83aa91b810c5f..3f3ff8b97999c 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js +++ b/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js @@ -33,7 +33,7 @@ export const __bundleProvider__ = wrap(alias('uiBundleProviders'), flatConcatAtT export const __webpackPluginProvider__ = wrap(alias('webpackPluginProviders'), flatConcatAtType); export const noParse = wrap( alias('webpackNoParseRules'), - mapSpec(rule => { + mapSpec((rule) => { if (typeof rule === 'string') { return new RegExp(`${isAbsolute(rule) ? '^' : ''}${escapeRegExp(rule)}`); } diff --git a/src/legacy/ui/ui_render/ui_render_mixin.js b/src/legacy/ui/ui_render/ui_render_mixin.js index 8024a6ded2967..52c43c426ed91 100644 --- a/src/legacy/ui/ui_render/ui_render_mixin.js +++ b/src/legacy/ui/ui_render/ui_render_mixin.js @@ -108,10 +108,10 @@ export function uiRenderMixin(kbnServer, server, config) { const dllBundlePath = `${basePath}/${buildHash}/built_assets/dlls`; const dllStyleChunks = DllCompiler.getRawDllConfig().chunks.map( - chunk => `${dllBundlePath}/vendors${chunk}.style.dll.css` + (chunk) => `${dllBundlePath}/vendors${chunk}.style.dll.css` ); const dllJsChunks = DllCompiler.getRawDllConfig().chunks.map( - chunk => `${dllBundlePath}/vendors${chunk}.bundle.dll.js` + (chunk) => `${dllBundlePath}/vendors${chunk}.bundle.dll.js` ); const styleSheetPaths = [ @@ -139,9 +139,9 @@ export function uiRenderMixin(kbnServer, server, config) { `${regularBundlePath}/${app.getId()}.style.css`, ...kbnServer.uiExports.styleSheetPaths .filter( - path => path.theme === '*' || path.theme === (darkMode ? 'dark' : 'light') + (path) => path.theme === '*' || path.theme === (darkMode ? 'dark' : 'light') ) - .map(path => + .map((path) => path.localPath.endsWith('.scss') ? `${basePath}/${buildHash}/built_assets/css/${path.publicPath}` : `${basePath}/${path.publicPath}` @@ -162,7 +162,7 @@ export function uiRenderMixin(kbnServer, server, config) { const jsDependencyPaths = [ ...UiSharedDeps.jsDepFilenames.map( - filename => `${regularBundlePath}/kbn-ui-shared-deps/${filename}` + (filename) => `${regularBundlePath}/kbn-ui-shared-deps/${filename}` ), `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.jsFilename}`, ...(isCore @@ -174,7 +174,7 @@ export function uiRenderMixin(kbnServer, server, config) { ]), ...kpPluginIds.map( - pluginId => `${regularBundlePath}/plugin/${pluginId}/${pluginId}.plugin.js` + (pluginId) => `${regularBundlePath}/plugin/${pluginId}/${pluginId}.plugin.js` ), ]; @@ -260,17 +260,14 @@ export function uiRenderMixin(kbnServer, server, config) { vars, }); - return h - .response(content) - .type('text/html') - .header('content-security-policy', http.csp.header); + return h.response(content).type('text/html').header('content-security-policy', http.csp.header); } - server.decorate('toolkit', 'renderApp', function(app, overrides) { + server.decorate('toolkit', 'renderApp', function (app, overrides) { return renderApp(this, app, true, overrides); }); - server.decorate('toolkit', 'renderAppWithDefaultConfig', function(app) { + server.decorate('toolkit', 'renderAppWithDefaultConfig', function (app) { return renderApp(this, app, false); }); } diff --git a/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts b/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts index dd3f12903abca..bee0d69706ebb 100644 --- a/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts +++ b/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts @@ -52,7 +52,7 @@ describe('uiSettingsMixin()', () => { log: sinon.stub(), route: sinon.stub(), addMemoizedFactoryToRequest(name: string, factory: (...args: any[]) => any) { - this.decorate('request', name, function(this: typeof server) { + this.decorate('request', name, function (this: typeof server) { return factory(this); }); }, @@ -103,9 +103,7 @@ describe('uiSettingsMixin()', () => { describe('server.uiSettingsServiceFactory()', () => { it('decorates server with "uiSettingsServiceFactory"', () => { const { decorations } = setup(); - expect(decorations.server) - .to.have.property('uiSettingsServiceFactory') - .a('function'); + expect(decorations.server).to.have.property('uiSettingsServiceFactory').a('function'); const uiSettingsServiceFactoryStub = sandbox.stub( uiSettingsServiceFactoryNS, @@ -118,9 +116,7 @@ describe('uiSettingsMixin()', () => { it('passes `server` and `options` argument to factory', () => { const { decorations, server } = setup(); - expect(decorations.server) - .to.have.property('uiSettingsServiceFactory') - .a('function'); + expect(decorations.server).to.have.property('uiSettingsServiceFactory').a('function'); const uiSettingsServiceFactoryStub = sandbox.stub( uiSettingsServiceFactoryNS, @@ -143,9 +139,7 @@ describe('uiSettingsMixin()', () => { describe('request.getUiSettingsService()', () => { it('exposes "getUiSettingsService" on requests', () => { const { decorations } = setup(); - expect(decorations.request) - .to.have.property('getUiSettingsService') - .a('function'); + expect(decorations.request).to.have.property('getUiSettingsService').a('function'); const getUiSettingsServiceForRequestStub = sandbox.stub( getUiSettingsServiceForRequestNS, @@ -158,9 +152,7 @@ describe('uiSettingsMixin()', () => { it('passes request to getUiSettingsServiceForRequest', () => { const { server, decorations } = setup(); - expect(decorations.request) - .to.have.property('getUiSettingsService') - .a('function'); + expect(decorations.request).to.have.property('getUiSettingsService').a('function'); const getUiSettingsServiceForRequestStub = sandbox.stub( getUiSettingsServiceForRequestNS, @@ -176,9 +168,7 @@ describe('uiSettingsMixin()', () => { describe('server.uiSettings()', () => { it('throws an error, links to pr', () => { const { decorations } = setup(); - expect(decorations.server) - .to.have.property('uiSettings') - .a('function'); + expect(decorations.server).to.have.property('uiSettings').a('function'); expect(() => { decorations.server.uiSettings(); }).to.throwError('http://github.com' as any); // incorrect typings diff --git a/src/legacy/ui/ui_settings/ui_exports_consumer.js b/src/legacy/ui/ui_settings/ui_exports_consumer.js index 0ced11afc8d2c..d2bb3a00ce0ed 100644 --- a/src/legacy/ui/ui_settings/ui_exports_consumer.js +++ b/src/legacy/ui/ui_settings/ui_exports_consumer.js @@ -41,7 +41,7 @@ export class UiExportsConsumer { switch (type) { case 'uiSettingDefaults': return (plugin, settingDefinitions) => { - Object.keys(settingDefinitions).forEach(key => { + Object.keys(settingDefinitions).forEach((key) => { if (key in this._uiSettingDefaults) { throw new Error(`uiSettingDefaults for key "${key}" are already defined`); } diff --git a/src/legacy/ui/ui_settings/ui_settings_mixin.js b/src/legacy/ui/ui_settings/ui_settings_mixin.js index 64251d290776c..accdc4d043d1a 100644 --- a/src/legacy/ui/ui_settings/ui_settings_mixin.js +++ b/src/legacy/ui/ui_settings/ui_settings_mixin.js @@ -43,7 +43,7 @@ export function uiSettingsMixin(kbnServer, server) { return uiSettingsServiceFactory(server, options); }); - server.addMemoizedFactoryToRequest('getUiSettingsService', request => { + server.addMemoizedFactoryToRequest('getUiSettingsService', (request) => { return getUiSettingsServiceForRequest(server, request); }); diff --git a/src/legacy/utils/__tests__/unset.js b/src/legacy/utils/__tests__/unset.js index 6e6840758c7ae..69122e06ac572 100644 --- a/src/legacy/utils/__tests__/unset.js +++ b/src/legacy/utils/__tests__/unset.js @@ -20,77 +20,77 @@ import { unset } from '../unset'; import expect from '@kbn/expect'; -describe('unset(obj, key)', function() { - describe('invalid input', function() { - it('should do nothing if not given an object', function() { +describe('unset(obj, key)', function () { + describe('invalid input', function () { + it('should do nothing if not given an object', function () { const obj = 'hello'; unset(obj, 'e'); expect(obj).to.equal('hello'); }); - it('should do nothing if not given a key', function() { + it('should do nothing if not given a key', function () { const obj = { one: 1 }; unset(obj); expect(obj).to.eql({ one: 1 }); }); - it('should do nothing if given an empty string as a key', function() { + it('should do nothing if given an empty string as a key', function () { const obj = { one: 1 }; unset(obj, ''); expect(obj).to.eql({ one: 1 }); }); }); - describe('shallow removal', function() { + describe('shallow removal', function () { let obj; - beforeEach(function() { + beforeEach(function () { obj = { one: 1, two: 2, deep: { three: 3, four: 4 } }; }); - it('should remove the param using a string key', function() { + it('should remove the param using a string key', function () { unset(obj, 'two'); expect(obj).to.eql({ one: 1, deep: { three: 3, four: 4 } }); }); - it('should remove the param using an array key', function() { + it('should remove the param using an array key', function () { unset(obj, ['two']); expect(obj).to.eql({ one: 1, deep: { three: 3, four: 4 } }); }); }); - describe('deep removal', function() { + describe('deep removal', function () { let obj; - beforeEach(function() { + beforeEach(function () { obj = { one: 1, two: 2, deep: { three: 3, four: 4 } }; }); - it('should remove the param using a string key', function() { + it('should remove the param using a string key', function () { unset(obj, 'deep.three'); expect(obj).to.eql({ one: 1, two: 2, deep: { four: 4 } }); }); - it('should remove the param using an array key', function() { + it('should remove the param using an array key', function () { unset(obj, ['deep', 'three']); expect(obj).to.eql({ one: 1, two: 2, deep: { four: 4 } }); }); }); - describe('recursive removal', function() { - it('should clear object if only value is removed', function() { + describe('recursive removal', function () { + it('should clear object if only value is removed', function () { const obj = { one: { two: { three: 3 } } }; unset(obj, 'one.two.three'); expect(obj).to.eql({}); }); - it('should clear object if no props are left', function() { + it('should clear object if no props are left', function () { const obj = { one: { two: { three: 3 } } }; unset(obj, 'one.two'); expect(obj).to.eql({}); }); - it('should remove deep property, then clear the object', function() { + it('should remove deep property, then clear the object', function () { const obj = { one: { two: { three: 3, four: 4 } } }; unset(obj, 'one.two.three'); expect(obj).to.eql({ one: { two: { four: 4 } } }); diff --git a/src/legacy/utils/__tests__/watch_stdio_for_line.js b/src/legacy/utils/__tests__/watch_stdio_for_line.js index 1bd69cfd8b64d..32d61658c1114 100644 --- a/src/legacy/utils/__tests__/watch_stdio_for_line.js +++ b/src/legacy/utils/__tests__/watch_stdio_for_line.js @@ -23,12 +23,12 @@ import sinon from 'sinon'; import { watchStdioForLine } from '../watch_stdio_for_line'; -describe('src/legacy/utils/watch_stdio_for_line', function() { +describe('src/legacy/utils/watch_stdio_for_line', function () { const sandbox = sinon.sandbox.create(); afterEach(() => sandbox.reset()); const onLogLine = sandbox.stub(); - const logFn = line => onLogLine(stripAnsi(line)); + const logFn = (line) => onLogLine(stripAnsi(line)); it('calls logFn with log lines', async () => { const proc = execa(process.execPath, ['-e', 'console.log("hi")']); @@ -39,7 +39,7 @@ describe('src/legacy/utils/watch_stdio_for_line', function() { sinon.assert.calledWithExactly(onLogLine, sinon.match(/hi/)); }); - it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function() { + it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function () { // fixture proc will exit after 10 seconds if sigint not received, but the test won't fail // unless we see the log line `SIGINT not received`, so we let the test take up to 30 seconds // for potentially huge delays here and there diff --git a/src/legacy/utils/binder.ts b/src/legacy/utils/binder.ts index 20c7cb9d4d490..55577e3a69e2b 100644 --- a/src/legacy/utils/binder.ts +++ b/src/legacy/utils/binder.ts @@ -38,6 +38,6 @@ export class BinderBase { public destroy() { const destroyers = this.disposal; this.disposal = []; - destroyers.forEach(fn => fn()); + destroyers.forEach((fn) => fn()); } } diff --git a/src/legacy/utils/streams/concat_stream_providers.js b/src/legacy/utils/streams/concat_stream_providers.js index 64643787ea771..11dfb84284df3 100644 --- a/src/legacy/utils/streams/concat_stream_providers.js +++ b/src/legacy/utils/streams/concat_stream_providers.js @@ -51,7 +51,7 @@ export function concatStreamProviders(sourceProviders, options = {}) { source // proxy errors from the source to the destination - .once('error', error => destination.emit('error', error)) + .once('error', (error) => destination.emit('error', error)) // pipe the source to the destination but only proxy the // end event if this is the last source .pipe(destination, { end: isLast }); diff --git a/src/legacy/utils/streams/filter_stream.test.ts b/src/legacy/utils/streams/filter_stream.test.ts index f5140b7639c74..7f4901f31c173 100644 --- a/src/legacy/utils/streams/filter_stream.test.ts +++ b/src/legacy/utils/streams/filter_stream.test.ts @@ -64,7 +64,7 @@ describe('createFilterStream()', () => { test('send the filtered values on the output stream', async () => { const result = await createPromiseFromStreams([ createListStream([1, 2, 3]), - createFilterStream(n => n % 2 === 0), + createFilterStream((n) => n % 2 === 0), createConcatStream([]), ]); diff --git a/src/legacy/utils/streams/list_stream.js b/src/legacy/utils/streams/list_stream.js index 703d664a97ec7..a614620b054b7 100644 --- a/src/legacy/utils/streams/list_stream.js +++ b/src/legacy/utils/streams/list_stream.js @@ -32,7 +32,7 @@ export function createListStream(items = []) { return new Readable({ objectMode: true, read(size) { - queue.splice(0, size).forEach(item => { + queue.splice(0, size).forEach((item) => { this.push(item); }); diff --git a/src/legacy/utils/streams/list_stream.test.js b/src/legacy/utils/streams/list_stream.test.js index 9052127793c6e..12e20696b0510 100644 --- a/src/legacy/utils/streams/list_stream.test.js +++ b/src/legacy/utils/streams/list_stream.test.js @@ -25,7 +25,7 @@ describe('listStream', () => { const onData = jest.fn(); str.on('data', onData); - await new Promise(resolve => str.on('end', resolve)); + await new Promise((resolve) => str.on('end', resolve)); expect(onData).toHaveBeenCalledTimes(4); expect(onData.mock.calls[0]).toEqual([1]); @@ -38,7 +38,7 @@ describe('listStream', () => { const list = [1, 2, 3, 4]; const str = createListStream(list); str.resume(); - await new Promise(resolve => str.on('end', resolve)); + await new Promise((resolve) => str.on('end', resolve)); expect(list).toEqual([1, 2, 3, 4]); }); }); diff --git a/src/legacy/utils/streams/map_stream.test.js b/src/legacy/utils/streams/map_stream.test.js index 4ffabe7477d73..d86da178f0c1b 100644 --- a/src/legacy/utils/streams/map_stream.test.js +++ b/src/legacy/utils/streams/map_stream.test.js @@ -39,7 +39,7 @@ describe('createMapStream()', () => { test('send the return value from the mapper on the output stream', async () => { const result = await createPromiseFromStreams([ createListStream([1, 2, 3]), - createMapStream(n => n * 100), + createMapStream((n) => n * 100), createConcatStream([]), ]); diff --git a/src/legacy/utils/streams/promise_from_streams.js b/src/legacy/utils/streams/promise_from_streams.js index 9c8205702f254..05f6a08aa1a09 100644 --- a/src/legacy/utils/streams/promise_from_streams.js +++ b/src/legacy/utils/streams/promise_from_streams.js @@ -58,7 +58,7 @@ export async function createPromiseFromStreams(streams) { ); } return new Promise((resolve, reject) => { - pipeline(...streams, err => { + pipeline(...streams, (err) => { if (err) return reject(err); resolve(finalChunk); }); diff --git a/src/legacy/utils/streams/promise_from_streams.test.js b/src/legacy/utils/streams/promise_from_streams.test.js index 9876e452e262b..e4d9835106f12 100644 --- a/src/legacy/utils/streams/promise_from_streams.test.js +++ b/src/legacy/utils/streams/promise_from_streams.test.js @@ -25,9 +25,9 @@ describe('promiseFromStreams', () => { test('pipes together an array of streams', async () => { const str1 = createListStream([1, 2, 3]); const str2 = createReduceStream((acc, n) => acc + n, 0); - const sumPromise = new Promise(resolve => str2.once('data', resolve)); + const sumPromise = new Promise((resolve) => str2.once('data', resolve)); createPromiseFromStreams([str1, str2]); - await new Promise(resolve => str2.once('end', resolve)); + await new Promise((resolve) => str2.once('end', resolve)); expect(await sumPromise).toBe(6); }); @@ -88,7 +88,7 @@ describe('promiseFromStreams', () => { write(chunk, enc, cb) { duplexReadQueue.push( - new Promise(resolve => { + new Promise((resolve) => { setTimeout(() => { written += chunk; cb(); diff --git a/src/legacy/utils/streams/reduce_stream.test.js b/src/legacy/utils/streams/reduce_stream.test.js index 98d01ec2c773a..2c073f67f82a8 100644 --- a/src/legacy/utils/streams/reduce_stream.test.js +++ b/src/legacy/utils/streams/reduce_stream.test.js @@ -20,7 +20,7 @@ import { createReduceStream, createPromiseFromStreams, createListStream } from './'; const promiseFromEvent = (name, emitter) => - new Promise(resolve => emitter.on(name, () => resolve(name))); + new Promise((resolve) => emitter.on(name, () => resolve(name))); describe('reduceStream', () => { test('calls the reducer for each item provided', async () => { @@ -41,7 +41,7 @@ describe('reduceStream', () => { test('provides the return value of the last iteration of the reducer', async () => { const result = await createPromiseFromStreams([ createListStream('abcdefg'.split('')), - createReduceStream(acc => acc + 1, 0), + createReduceStream((acc) => acc + 1, 0), ]); expect(result).toBe(7); }); diff --git a/src/legacy/utils/streams/replace_stream.test.js b/src/legacy/utils/streams/replace_stream.test.js index 219d4fb18a59e..01b89f93e5af0 100644 --- a/src/legacy/utils/streams/replace_stream.test.js +++ b/src/legacy/utils/streams/replace_stream.test.js @@ -28,7 +28,7 @@ import { async function concatToString(streams) { return await createPromiseFromStreams([ ...streams, - createMapStream(buff => buff.toString('utf8')), + createMapStream((buff) => buff.toString('utf8')), createConcatStream(''), ]); } @@ -41,7 +41,7 @@ describe('replaceStream', () => { createConcatStream([]), ]); - chunks.forEach(chunk => { + chunks.forEach((chunk) => { expect(chunk).toBeInstanceOf(Buffer); }); }); @@ -53,7 +53,7 @@ describe('replaceStream', () => { createConcatStream([]), ]); - chunks.forEach(chunk => { + chunks.forEach((chunk) => { expect(chunk).toBeInstanceOf(Buffer); }); }); diff --git a/src/legacy/utils/streams/split_stream.test.js b/src/legacy/utils/streams/split_stream.test.js index 148b9211b81bb..e0736d220ba5c 100644 --- a/src/legacy/utils/streams/split_stream.test.js +++ b/src/legacy/utils/streams/split_stream.test.js @@ -25,7 +25,7 @@ async function split(stream, input) { stream.pipe(concat); const output = createPromiseFromStreams([concat]); - input.forEach(i => { + input.forEach((i) => { stream.write(i); }); stream.end(); diff --git a/src/legacy/utils/watch_stdio_for_line.js b/src/legacy/utils/watch_stdio_for_line.js index dc822602931b7..01323b4d4e967 100644 --- a/src/legacy/utils/watch_stdio_for_line.js +++ b/src/legacy/utils/watch_stdio_for_line.js @@ -53,7 +53,7 @@ export async function watchStdioForLine(proc, logFn, exitAfter) { } await Promise.all([ - proc.catch(error => { + proc.catch((error) => { // ignore the error thrown by execa if it's because we killed with SIGINT if (error.signal !== 'SIGINT') { throw error; diff --git a/src/optimize/base_optimizer.js b/src/optimize/base_optimizer.js index 9d3a834b455db..12131b89e03c1 100644 --- a/src/optimize/base_optimizer.js +++ b/src/optimize/base_optimizer.js @@ -109,7 +109,7 @@ export default class BaseOptimizer { } registerCompilerDoneHook() { - this.compiler.hooks.done.tap('base_optimizer-done', stats => { + this.compiler.hooks.done.tap('base_optimizer-done', (stats) => { // We are not done while we have an additional // compilation pass to run // We also don't need to emit the stats if we don't have @@ -120,7 +120,7 @@ export default class BaseOptimizer { const path = this.uiBundles.resolvePath('stats.json'); const content = JSON.stringify(stats.toJson()); - writeFile(path, content, function(err) { + writeFile(path, content, function (err) { if (err) throw err; }); }); @@ -226,7 +226,7 @@ export default class BaseOptimizer { * Creates the selection rules for a loader that will only pass for * source files that are eligible for automatic transpilation. */ - const createSourceFileResourceSelector = test => { + const createSourceFileResourceSelector = (test) => { return [ { test, @@ -268,20 +268,22 @@ export default class BaseOptimizer { cacheGroups: { commons: { name: 'commons', - chunks: chunk => + chunks: (chunk) => chunk.canBeInitial() && chunk.name !== 'light_theme' && chunk.name !== 'dark_theme', minChunks: 2, reuseExistingChunk: true, }, light_theme: { name: 'light_theme', - test: m => m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'light_theme', + test: (m) => + m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'light_theme', chunks: 'all', enforce: true, }, dark_theme: { name: 'dark_theme', - test: m => m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'dark_theme', + test: (m) => + m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'dark_theme', chunks: 'all', enforce: true, }, @@ -302,13 +304,13 @@ export default class BaseOptimizer { }), // ignore scss imports in new-platform code that finds its way into legacy bundles - new webpack.NormalModuleReplacementPlugin(/\.scss$/, resource => { + new webpack.NormalModuleReplacementPlugin(/\.scss$/, (resource) => { resource.request = EMPTY_MODULE_PATH; }), // replace imports for `uiExports/*` modules with a synthetic module // created by create_ui_exports_module.js - new webpack.NormalModuleReplacementPlugin(/^uiExports\//, resource => { + new webpack.NormalModuleReplacementPlugin(/^uiExports\//, (resource) => { // the map of uiExport types to module ids const extensions = this.uiBundles.getAppExtensions(); @@ -330,7 +332,7 @@ export default class BaseOptimizer { ].join(''); }), - ...this.uiBundles.getWebpackPluginProviders().map(provider => provider(webpack)), + ...this.uiBundles.getWebpackPluginProviders().map((provider) => provider(webpack)), ], module: { @@ -376,7 +378,7 @@ export default class BaseOptimizer { }, ]), }, - ...this.uiBundles.getPostLoaders().map(loader => ({ + ...this.uiBundles.getPostLoaders().map((loader) => ({ enforce: 'post', ...loader, })), diff --git a/src/optimize/bundles_route/file_hash.ts b/src/optimize/bundles_route/file_hash.ts index 7b0801098ed10..d8b4c4419b844 100644 --- a/src/optimize/bundles_route/file_hash.ts +++ b/src/optimize/bundles_route/file_hash.ts @@ -46,15 +46,15 @@ export async function getFileHash(cache: FileHashCache, path: string, stat: Fs.S const promise = Rx.merge( Rx.fromEvent(read, 'data'), Rx.fromEvent(read, 'error').pipe( - map(error => { + map((error) => { throw error; }) ) ) .pipe(takeUntil(Rx.fromEvent(read, 'end'))) - .forEach(chunk => hash.update(chunk)) + .forEach((chunk) => hash.update(chunk)) .then(() => hash.digest('hex')) - .catch(error => { + .catch((error) => { // don't cache failed attempts cache.del(key); throw error; diff --git a/src/optimize/create_ui_exports_module.js b/src/optimize/create_ui_exports_module.js index 2ab19d71e1f1c..d20814b10931b 100644 --- a/src/optimize/create_ui_exports_module.js +++ b/src/optimize/create_ui_exports_module.js @@ -22,7 +22,7 @@ function normalizePath(path) { return path.replace(/[\\\/]+/g, '/'); } -module.exports = function() { +module.exports = function () { if (!module.id.includes('?')) { throw new Error('create_ui_exports_module loaded without JSON args in module.id'); } @@ -31,7 +31,7 @@ module.exports = function() { const comment = `// dynamically generated to load ${type} uiExports from plugins`; const requires = modules .sort((a, b) => a.localeCompare(b)) - .map(m => `require('${normalizePath(m)}')`) + .map((m) => `require('${normalizePath(m)}')`) .join('\n '); return { diff --git a/src/optimize/dynamic_dll_plugin/dll_compiler.js b/src/optimize/dynamic_dll_plugin/dll_compiler.js index 9889c1f71c3bf..9ab21ee0e9076 100644 --- a/src/optimize/dynamic_dll_plugin/dll_compiler.js +++ b/src/optimize/dynamic_dll_plugin/dll_compiler.js @@ -48,7 +48,7 @@ export class DllCompiler { uiBundles = {}, babelLoaderCacheDir = '', threadLoaderPoolConfig = {}, - chunks = Array.from(Array(4).keys()).map(chunkN => `_${chunkN}`) + chunks = Array.from(Array(4).keys()).map((chunkN) => `_${chunkN}`) ) { return { uiBundles, @@ -130,25 +130,25 @@ export class DllCompiler { } getDllPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.dllExt}`) ); } getEntryPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.entryExt}`) ); } getManifestPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.manifestExt}`) ); } getStylePaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.styleExt}`) ); } @@ -156,7 +156,7 @@ export class DllCompiler { async ensureEntryFilesExists() { const entryPaths = this.getEntryPaths(); - await Promise.all(entryPaths.map(async entryPath => await this.ensureFileExists(entryPath))); + await Promise.all(entryPaths.map(async (entryPath) => await this.ensureFileExists(entryPath))); } async ensureManifestFilesExists() { @@ -179,7 +179,7 @@ export class DllCompiler { async ensureStyleFileExists() { const stylePaths = this.getStylePaths(); - await Promise.all(stylePaths.map(async stylePath => await this.ensureFileExists(stylePath))); + await Promise.all(stylePaths.map(async (stylePath) => await this.ensureFileExists(stylePath))); } async ensureFileExists(filePath, content) { @@ -208,7 +208,7 @@ export class DllCompiler { dllsExistsSync() { const dllPaths = this.getDllPaths(); - return dllPaths.every(dllPath => this.existsSync(dllPath)); + return dllPaths.every((dllPath) => this.existsSync(dllPath)); } existsSync(filePath) { @@ -223,7 +223,7 @@ export class DllCompiler { const entryPaths = this.getEntryPaths(); const entryFilesContent = await Promise.all( - entryPaths.map(async entryPath => await this.readFile(entryPath)) + entryPaths.map(async (entryPath) => await this.readFile(entryPath)) ); // merge all the module contents from entry files again into @@ -304,7 +304,7 @@ export class DllCompiler { // bundled inside the dll bundle const notAllowedModules = []; - stats.compilation.modules.forEach(module => { + stats.compilation.modules.forEach((module) => { // ignore if no module or userRequest are defined if (!module || !module.resource) { return; @@ -327,7 +327,7 @@ export class DllCompiler { if (notInNodeModulesOrWebpackShims(module.resource)) { const reasons = module.reasons || []; - reasons.forEach(reason => { + reasons.forEach((reason) => { // Skip if we can't read the reason info if (!reason || !reason.module || !reason.module.resource) { return; diff --git a/src/optimize/dynamic_dll_plugin/dll_entry_template.js b/src/optimize/dynamic_dll_plugin/dll_entry_template.js index 0c286896d0b71..351bed4e591ba 100644 --- a/src/optimize/dynamic_dll_plugin/dll_entry_template.js +++ b/src/optimize/dynamic_dll_plugin/dll_entry_template.js @@ -19,7 +19,7 @@ export function dllEntryTemplate(requirePaths = []) { return requirePaths - .map(path => `require('${path}');`) + .map((path) => `require('${path}');`) .sort() .join('\n'); } @@ -33,9 +33,5 @@ export function dllEntryFileContentArrayToString(content = []) { } export function dllMergeAllEntryFilesContent(content = []) { - return content - .join('\n') - .split('\n') - .sort() - .join('\n'); + return content.join('\n').split('\n').sort().join('\n'); } diff --git a/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js b/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js index 484c7dfbfd595..fb6f6e097b5cd 100644 --- a/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js +++ b/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js @@ -72,7 +72,7 @@ export class DynamicDllPlugin { const dllContext = rawDllConfig.context; const dllManifestPaths = this.dllCompiler.getManifestPaths(); - dllManifestPaths.forEach(dllChunkManifestPath => { + dllManifestPaths.forEach((dllChunkManifestPath) => { new webpack.DllReferencePlugin({ context: dllContext, manifest: dllChunkManifestPath, @@ -109,10 +109,10 @@ export class DynamicDllPlugin { registerBeforeCompileHook(compiler) { compiler.hooks.beforeCompile.tapPromise('DynamicDllPlugin', async ({ normalModuleFactory }) => { - normalModuleFactory.hooks.factory.tap('DynamicDllPlugin', actualFactory => (params, cb) => { + normalModuleFactory.hooks.factory.tap('DynamicDllPlugin', (actualFactory) => (params, cb) => { // This is used in order to avoid the cache for DLL modules // resolved from other dependencies - normalModuleFactory.cachePredicate = module => + normalModuleFactory.cachePredicate = (module) => !(module.stubType === DLL_ENTRY_STUB_MODULE_TYPE); // Overrides the normalModuleFactory module creation behaviour @@ -123,7 +123,7 @@ export class DynamicDllPlugin { } else { this.mapNormalModule(module).then( (m = module) => cb(undefined, m), - error => cb(error) + (error) => cb(error) ); } }); @@ -132,7 +132,7 @@ export class DynamicDllPlugin { } registerCompilationHook(compiler) { - compiler.hooks.compilation.tap('DynamicDllPlugin', compilation => { + compiler.hooks.compilation.tap('DynamicDllPlugin', (compilation) => { compilation.hooks.needAdditionalPass.tap('DynamicDllPlugin', () => { // Run the procedures in order to execute our dll compilation // The process is very straightforward in it's conception: @@ -215,7 +215,7 @@ export class DynamicDllPlugin { } registerDoneHook(compiler) { - compiler.hooks.done.tapPromise('DynamicDllPlugin', async stats => { + compiler.hooks.done.tapPromise('DynamicDllPlugin', async (stats) => { if (stats.compilation.needsDLLCompilation) { // Run the dlls compiler and increment // the performed compilations @@ -341,7 +341,7 @@ export class DynamicDllPlugin { // that we rely in next ones. this.dllCompiler .getManifestPaths() - .forEach(chunkDllManifestPath => mainCompiler.inputFileSystem.purge(chunkDllManifestPath)); + .forEach((chunkDllManifestPath) => mainCompiler.inputFileSystem.purge(chunkDllManifestPath)); this.performedCompilations++; diff --git a/src/optimize/fs_optimizer.js b/src/optimize/fs_optimizer.js index 03e413f04eb46..71a4c85a9e5a5 100644 --- a/src/optimize/fs_optimizer.js +++ b/src/optimize/fs_optimizer.js @@ -26,7 +26,7 @@ export default class FsOptimizer extends BaseOptimizer { await this.init(); } - await fromNode(cb => { + await fromNode((cb) => { this.compiler.run((err, stats) => { if (err || !stats) return cb(err); diff --git a/src/optimize/np_ui_plugin_public_dirs.ts b/src/optimize/np_ui_plugin_public_dirs.ts index e7c3207948f6a..8b49ffb74cb08 100644 --- a/src/optimize/np_ui_plugin_public_dirs.ts +++ b/src/optimize/np_ui_plugin_public_dirs.ts @@ -36,7 +36,7 @@ export function isNpUiPluginPublicDirs(x: any): x is NpUiPluginPublicDirs { return ( Array.isArray(x) && x.every( - s => typeof s === 'object' && s && typeof s.id === 'string' && typeof s.path === 'string' + (s) => typeof s === 'object' && s && typeof s.id === 'string' && typeof s.path === 'string' ) ); } diff --git a/src/optimize/public_path_placeholder.ts b/src/optimize/public_path_placeholder.ts index 1ec2b4a431aa6..d5f57a1586774 100644 --- a/src/optimize/public_path_placeholder.ts +++ b/src/optimize/public_path_placeholder.ts @@ -38,7 +38,7 @@ export function replacePlaceholder(read: Stream.Readable, replacement: string) { // choose what to do with them. Rx.fromEvent(read, 'error') .pipe(take(1), takeUntil(Rx.fromEvent(read, 'end'))) - .forEach(error => { + .forEach((error) => { replace.emit('error', error); replace.end(); }); diff --git a/src/optimize/watch/optmzr_role.js b/src/optimize/watch/optmzr_role.js index 1f6107996277c..ba8007e1065b4 100644 --- a/src/optimize/watch/optmzr_role.js +++ b/src/optimize/watch/optmzr_role.js @@ -71,7 +71,7 @@ export default async (kbnServer, kibanaHapiServer, config) => { process.send(['WORKER_BROADCAST', { optimizeReady: ready }]); }; - process.on('message', msg => { + process.on('message', (msg) => { if (msg && msg.optimizeReady === '?') sendReady(); }); diff --git a/src/optimize/watch/proxy_role.js b/src/optimize/watch/proxy_role.js index 0f6f3b2d4b622..ce2d63aa2eff0 100644 --- a/src/optimize/watch/proxy_role.js +++ b/src/optimize/watch/proxy_role.js @@ -30,7 +30,7 @@ export default (kbnServer, server, config) => { }) ); - return fromNode(cb => { + return fromNode((cb) => { const timeout = setTimeout(() => { cb(new Error('Timeout waiting for the optimizer to become ready')); }, config.get('optimize.watchProxyTimeout')); @@ -42,7 +42,7 @@ export default (kbnServer, server, config) => { if (!process.connected) return; process.send(['WORKER_BROADCAST', { optimizeReady: '?' }]); - process.on('message', msg => { + process.on('message', (msg) => { switch (get(msg, 'optimizeReady')) { case true: clearTimeout(timeout); diff --git a/src/optimize/watch/watch.js b/src/optimize/watch/watch.js index a84fcc59e13f5..a284da11f294f 100644 --- a/src/optimize/watch/watch.js +++ b/src/optimize/watch/watch.js @@ -19,7 +19,7 @@ import { isWorker } from 'cluster'; -export default async kbnServer => { +export default async (kbnServer) => { if (!isWorker) { throw new Error(`watch optimization is only available when using the "--dev" cli flag`); } diff --git a/src/optimize/watch/watch_cache.ts b/src/optimize/watch/watch_cache.ts index b6784c1734a17..40bd1d6075f47 100644 --- a/src/optimize/watch/watch_cache.ts +++ b/src/optimize/watch/watch_cache.ts @@ -174,7 +174,7 @@ async function recursiveDelete(directory: string) { const entries = await readdirAsync(directory, { withFileTypes: true }); await Promise.all( - entries.map(entry => { + entries.map((entry) => { const absolutePath = path.join(directory, entry.name); return entry.isDirectory() ? recursiveDelete(absolutePath) : unlinkAsync(absolutePath); }) diff --git a/src/optimize/watch/watch_optimizer.js b/src/optimize/watch/watch_optimizer.js index cdff57a00c2e0..816185e544ab5 100644 --- a/src/optimize/watch/watch_optimizer.js +++ b/src/optimize/watch/watch_optimizer.js @@ -83,7 +83,7 @@ export default class WatchOptimizer extends BaseOptimizer { registerCompilerDoneHook() { super.registerCompilerDoneHook(); - this.compiler.hooks.done.tap('watch_optimizer-done', stats => { + this.compiler.hooks.done.tap('watch_optimizer-done', (stats) => { if (stats.compilation.needAdditionalPass) { return; } @@ -145,7 +145,7 @@ export default class WatchOptimizer extends BaseOptimizer { } } - compilerWatchErrorHandler = error => { + compilerWatchErrorHandler = (error) => { if (error) { this.status$.next({ type: STATUS.FATAL, diff --git a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx index 97abdcb10016d..d8853015d362a 100644 --- a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx +++ b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx @@ -125,7 +125,7 @@ export class AdvancedSettingsComponent extends Component< mapConfig(config: IUiSettingsClient) { const all = config.getAll(); return Object.entries(all) - .map(setting => { + .map((setting) => { return toEditableConfig({ def: setting[1], name: setting[0], @@ -134,7 +134,7 @@ export class AdvancedSettingsComponent extends Component< isOverridden: config.isOverridden(setting[0]), }); }) - .filter(c => !c.readonly) + .filter((c) => !c.readonly) .sort(Comparators.property('name', Comparators.default('asc'))); } diff --git a/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx b/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx index cb2999830b053..9e06da5f79008 100644 --- a/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx @@ -60,8 +60,8 @@ export class AdvancedSettingsVoiceAnnouncement extends Component { }; render() { - const filteredSections = Object.values(this.props.settings).map(setting => - setting.map(option => option.ariaName) + const filteredSections = Object.values(this.props.settings).map((setting) => + setting.map((option) => option.ariaName) ); const filteredOptions = [...filteredSections]; return ( diff --git a/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx b/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx index 356e38c799659..72992c190e8ae 100644 --- a/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx @@ -205,7 +205,7 @@ const getFieldSettingValue = (wrapper: ReactWrapper, name: string, type: string) }; describe('Field', () => { - Object.keys(settings).forEach(type => { + Object.keys(settings).forEach((type) => { const setting = settings[type]; describe(`for ${type} setting`, () => { @@ -325,10 +325,10 @@ describe('Field', () => { ); const select = findTestSubject(component, `advancedSetting-editField-${setting.name}`); // @ts-ignore - const values = select.find('option').map(option => option.prop('value')); + const values = select.find('option').map((option) => option.prop('value')); expect(values).toEqual(['apple', 'orange', 'banana']); // @ts-ignore - const labels = select.find('option').map(option => option.text()); + const labels = select.find('option').map((option) => option.text()); expect(labels).toEqual(['Apple', 'Orange', 'banana']); }); } diff --git a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx index 60d2b55dfceb4..32bfc0826e7c4 100644 --- a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx @@ -266,7 +266,7 @@ export class Field extends PureComponent { reader.onload = () => { resolve(reader.result || undefined); }; - reader.onerror = err => { + reader.onerror = (err) => { reject(err); }; }); @@ -378,7 +378,7 @@ export class Field extends PureComponent { { + options={(options as string[]).map((option) => { return { text: optionLabels.hasOwnProperty(option) ? optionLabels[option] : option, value: option, diff --git a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx index 2cd4d3c0b43ec..142ea06c7dce4 100644 --- a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx @@ -82,7 +82,7 @@ export class Form extends PureComponent { getSettingByKey = (key: string): FieldSetting | undefined => { return Object.values(this.props.settings) .flat() - .find(el => el.name === key); + .find((el) => el.name === key); }; getCountOfUnsavedChanges = (): number => { @@ -92,8 +92,8 @@ export class Form extends PureComponent { getCountOfHiddenUnsavedChanges = (): number => { const shownSettings = Object.values(this.props.visibleSettings) .flat() - .map(setting => setting.name); - return Object.keys(this.state.unsavedChanges).filter(key => !shownSettings.includes(key)) + .map((setting) => setting.name); + return Object.keys(this.state.unsavedChanges).filter((key) => !shownSettings.includes(key)) .length; }; @@ -256,7 +256,7 @@ export class Form extends PureComponent { - {settings.map(setting => { + {settings.map((setting) => { return ( { // TODO #64541 // Delete these classes let bottomBarClasses = ''; - const pageNav = this.props.settings.general.find(setting => setting.name === 'pageNavigation'); + const pageNav = this.props.settings.general.find( + (setting) => setting.name === 'pageNavigation' + ); if (pageNav?.value === 'legacy') { bottomBarClasses = classNames('mgtAdvancedSettingsForm__bottomBar', { @@ -401,7 +403,7 @@ export class Form extends PureComponent { const { visibleSettings, categories, categoryCounts, clearQuery } = this.props; const currentCategories: Category[] = []; - categories.forEach(category => { + categories.forEach((category) => { if (visibleSettings[category] && visibleSettings[category].length) { currentCategories.push(category); } @@ -411,7 +413,7 @@ export class Form extends PureComponent {

{currentCategories.length - ? currentCategories.map(category => { + ? currentCategories.map((category) => { return this.renderCategory( category, visibleSettings[category], diff --git a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx index 74e4894a27a6d..e440159b0ed71 100644 --- a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx @@ -35,7 +35,7 @@ export class Search extends PureComponent { constructor(props: SearchProps) { super(props); const { categories } = props; - this.categories = categories.map(category => { + this.categories = categories.map((category) => { return { value: category, name: getCategoryName(category), diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts index e129481a397c1..f27f58c599cca 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts @@ -20,16 +20,16 @@ import expect from '@kbn/expect'; import { getAriaName } from './get_aria_name'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getAriaName(name)', function() { - it('should return a space delimited lower-case string with no special characters', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getAriaName(name)', function () { + it('should return a space delimited lower-case string with no special characters', function () { expect(getAriaName('xPack:defaultAdminEmail')).to.be('x pack default admin email'); expect(getAriaName('doc_table:highlight')).to.be('doc table highlight'); expect(getAriaName('foo')).to.be('foo'); }); - it('should return an empty string if passed undefined or null', function() { + it('should return an empty string if passed undefined or null', function () { expect(getAriaName()).to.be(''); expect(getAriaName(undefined)).to.be(''); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts index d5c2be752a278..c33ac6abafb54 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts @@ -28,6 +28,6 @@ import { words } from 'lodash'; */ export function getAriaName(name?: string) { return words(name || '') - .map(word => word.toLowerCase()) + .map((word) => word.toLowerCase()) .join(' '); } diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts index 73e303e20c64d..74b61587524f5 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts @@ -20,14 +20,14 @@ import expect from '@kbn/expect'; import { getCategoryName } from './get_category_name'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getCategoryName(category)', function() { - it('should capitalize unknown category', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getCategoryName(category)', function () { + it('should capitalize unknown category', function () { expect(getCategoryName('elasticsearch')).to.be('Elasticsearch'); }); - it('should return empty string for no category', function() { + it('should return empty string for no category', function () { expect(getCategoryName()).to.be(''); expect(getCategoryName('')).to.be(''); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts index 46d28ce9d5c40..bf3ac9628754a 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; -const upperFirst = (str = '') => str.replace(/^./, strng => strng.toUpperCase()); +const upperFirst = (str = '') => str.replace(/^./, (strng) => strng.toUpperCase()); const names: Record = { general: i18n.translate('advancedSettings.categoryNames.generalLabel', { diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts index ec59dcaa1ea29..e971f545fd605 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts @@ -20,16 +20,16 @@ import expect from '@kbn/expect'; import { getValType } from './get_val_type'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getValType(def, val)', function() { - it('should return the explicitly defined type of a setting', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getValType(def, val)', function () { + it('should return the explicitly defined type of a setting', function () { expect(getValType({ type: 'string' })).to.be('string'); expect(getValType({ type: 'json' })).to.be('json'); expect(getValType({ type: 'string', value: 5 })).to.be('string'); }); - it('should return array if the value is an Array and there is no defined type', function() { + it('should return array if the value is an Array and there is no defined type', function () { expect(getValType({ type: 'string' }, [1, 2, 3])).to.be('string'); expect(getValType({ type: 'json', value: [1, 2, 3] })).to.be('json'); @@ -37,12 +37,12 @@ describe('Settings', function() { expect(getValType({ value: [1, 2, 3] }, 'someString')).to.be('array'); }); - it('should return the type of the default value if there is no type and it is not an array', function() { + it('should return the type of the default value if there is no type and it is not an array', function () { expect(getValType({ value: 'someString' })).to.be('string'); expect(getValType({ value: 'someString' }, 42)).to.be('string'); }); - it('should return the type of the value if the default value is null', function() { + it('should return the type of the value if the default value is null', function () { expect(getValType({ value: null }, 'someString')).to.be('string'); }); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts b/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts index 836dcb6b87676..4cde8bf517499 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts @@ -21,10 +21,10 @@ import expect from '@kbn/expect'; import { isDefaultValue } from './is_default_value'; import { UiSettingsType } from '../../../../../core/public'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getCategoryName(category)', function() { - describe('when given a setting definition object', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getCategoryName(category)', function () { + describe('when given a setting definition object', function () { const setting = { isCustom: false, value: 'value', @@ -43,21 +43,21 @@ describe('Settings', function() { validation: { regex: /regexString/, message: 'validation description' }, }; - describe('that is custom', function() { - it('should return true', function() { + describe('that is custom', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, isCustom: true })).to.be(true); }); }); - describe('without a value', function() { - it('should return true', function() { + describe('without a value', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, value: undefined })).to.be(true); expect(isDefaultValue({ ...setting, value: '' })).to.be(true); }); }); - describe('with a value that is the same as the default value', function() { - it('should return true', function() { + describe('with a value that is the same as the default value', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, value: 'defaultValue' })).to.be(true); expect(isDefaultValue({ ...setting, value: [], defVal: [] })).to.be(true); expect( @@ -69,8 +69,8 @@ describe('Settings', function() { }); }); - describe('with a value that is different than the default value', function() { - it('should return false', function() { + describe('with a value that is different than the default value', function () { + it('should return false', function () { expect(isDefaultValue({ ...setting })).to.be(false); expect(isDefaultValue({ ...setting, value: [1], defVal: [2] })).to.be(false); expect( diff --git a/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts b/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts index 7ac9b281eb99a..0f7edb4bd6332 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts @@ -37,26 +37,26 @@ function invoke({ return toEditableConfig({ def, name, value, isCustom: def === defDefault, isOverridden: true }); } -describe('Settings', function() { - describe('Advanced', function() { - describe('toEditableConfig(def, name, value)', function() { - it('sets name', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('toEditableConfig(def, name, value)', function () { + it('sets name', function () { expect(invoke({ name: 'who' }).name).to.equal('who'); }); - it('sets value', function() { + it('sets value', function () { expect(invoke({ value: 'what' }).value).to.equal('what'); }); - it('sets type', function() { + it('sets type', function () { expect(invoke({ value: 'what' }).type).to.be('string'); expect(invoke({ value: 0 }).type).to.be('number'); expect(invoke({ value: [] }).type).to.be('array'); }); - describe('when given a setting definition object', function() { + describe('when given a setting definition object', function () { let def: PublicUiSettingsParams & { isOverridden?: boolean }; - beforeEach(function() { + beforeEach(function () { def = { value: 'the original', description: 'the one and only', @@ -64,38 +64,38 @@ describe('Settings', function() { }; }); - it('is not marked as custom', function() { + it('is not marked as custom', function () { expect(invoke({ def }).isCustom).to.be(false); }); - it('sets a default value', function() { + it('sets a default value', function () { expect(invoke({ def }).defVal).to.equal(def.value); }); - it('sets a description', function() { + it('sets a description', function () { expect(invoke({ def }).description).to.equal(def.description); }); - it('sets options', function() { + it('sets options', function () { expect(invoke({ def }).options).to.equal(def.options); }); - describe('that contains a type', function() { - it('sets that type', function() { + describe('that contains a type', function () { + it('sets that type', function () { def.type = 'string'; expect(invoke({ def }).type).to.equal(def.type); }); }); - describe('that contains a value of type array', function() { - it('sets type to array', function() { + describe('that contains a value of type array', function () { + it('sets type to array', function () { def.value = []; expect(invoke({ def }).type).to.equal('array'); }); }); - describe('that contains a validation object', function() { - it('constructs a validation regex with message', function() { + describe('that contains a validation object', function () { + it('constructs a validation regex with message', function () { def.validation = { regexString: '^foo', message: 'must start with "foo"', @@ -108,24 +108,24 @@ describe('Settings', function() { }); }); - describe('when not given a setting definition object', function() { - it('is marked as custom', function() { + describe('when not given a setting definition object', function () { + it('is marked as custom', function () { expect(invoke({}).isCustom).to.be(true); }); - it('sets defVal to undefined', function() { + it('sets defVal to undefined', function () { expect(invoke({}).defVal).to.be(undefined); }); - it('sets description to undefined', function() { + it('sets description to undefined', function () { expect(invoke({}).description).to.be(undefined); }); - it('sets options to undefined', function() { + it('sets options to undefined', function () { expect(invoke({}).options).to.be(undefined); }); - it('sets validation to undefined', function() { + it('sets validation to undefined', function () { expect(invoke({}).validation).to.be(undefined); }); }); diff --git a/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts b/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts index 271bcab21172f..d2a4ee8297a11 100644 --- a/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts +++ b/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts @@ -644,8 +644,9 @@ export const createDotNetAgentInstructions = (apmServerUrl = '', secretToken = ' commands: `{curlyOpen} "ElasticApm": {curlyOpen} "SecretToken": "${secretToken}", - "ServerUrls": "${apmServerUrl || - 'http://localhost:8200'}", //Set custom APM Server URL (default: http://localhost:8200) + "ServerUrls": "${ + apmServerUrl || 'http://localhost:8200' + }", //Set custom APM Server URL (default: http://localhost:8200) "ServiceName" : "MyApp", //allowed characters: a-z, A-Z, 0-9, -, _, and space. Default is the entry assembly of the application {curlyClose} {curlyClose}`.split('\n'), diff --git a/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts b/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts index 5b145a2523070..c924cf3a04f1c 100644 --- a/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts +++ b/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts @@ -66,7 +66,7 @@ describe('createBatchedFunction', () => { expect(onCall).toHaveBeenCalledWith(123); expect(onBatch).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 15)); + await new Promise((r) => setTimeout(r, 15)); expect(onCall).toHaveBeenCalledTimes(1); expect(onBatch).toHaveBeenCalledTimes(1); diff --git a/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts b/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts index 064b791327e69..26c1d9e5033e0 100644 --- a/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts +++ b/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts @@ -24,17 +24,17 @@ import { Subject } from 'rxjs'; const getPromiseState = (promise: Promise): Promise<'resolved' | 'rejected' | 'pending'> => Promise.race<'resolved' | 'rejected' | 'pending'>([ - new Promise(resolve => + new Promise((resolve) => promise.then( () => resolve('resolved'), () => resolve('rejected') ) ), - new Promise<'pending'>(resolve => resolve()).then(() => 'pending'), + new Promise<'pending'>((resolve) => resolve()).then(() => 'pending'), ]); const isPending = (promise: Promise): Promise => - getPromiseState(promise).then(state => state === 'pending'); + getPromiseState(promise).then((state) => state === 'pending'); const setup = () => { const xhr = ({} as unknown) as XMLHttpRequest; @@ -93,7 +93,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ baz: 'quix' }); expect(fetchStreaming).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(1); }); @@ -107,7 +107,7 @@ describe('createStreamingBatchedFunction()', () => { }); expect(fetchStreaming).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(0); }); @@ -121,7 +121,7 @@ describe('createStreamingBatchedFunction()', () => { }); fn({ foo: 'bar' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming.mock.calls[0][0]).toMatchObject({ url: '/test', @@ -141,7 +141,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ foo: 'bar' }); fn({ baz: 'quix' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); const { body } = fetchStreaming.mock.calls[0][0]; expect(JSON.parse(body)).toEqual({ batch: [{ foo: 'bar' }, { baz: 'quix' }], @@ -205,7 +205,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ c: '3' }); expect(fetchStreaming).toHaveBeenCalledTimes(1); fn({ d: '4' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(2); }); }); @@ -222,7 +222,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise1)).toBe(true); expect(await isPending(promise2)).toBe(true); @@ -240,7 +240,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); const promise3 = fn({ c: '3' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise1)).toBe(true); expect(await isPending(promise2)).toBe(true); @@ -281,7 +281,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); const promise3 = fn({ c: '3' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -313,7 +313,7 @@ describe('createStreamingBatchedFunction()', () => { }); const promise = fn({ a: '1' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise)).toBe(true); @@ -344,7 +344,7 @@ describe('createStreamingBatchedFunction()', () => { const promise2 = of(fn({ a: '2' })); const promise3 = of(fn({ a: '3' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -353,7 +353,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); stream.next( JSON.stringify({ @@ -362,7 +362,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); stream.next( JSON.stringify({ @@ -371,7 +371,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [result1] = await promise1; const [, error2] = await promise2; @@ -395,11 +395,11 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.complete(); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [, error2] = await promise2; @@ -425,7 +425,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -435,7 +435,7 @@ describe('createStreamingBatchedFunction()', () => { ); stream.complete(); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [result1] = await promise2; @@ -462,13 +462,13 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.error({ message: 'something went wrong', }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [, error2] = await promise2; @@ -494,7 +494,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -504,7 +504,7 @@ describe('createStreamingBatchedFunction()', () => { ); stream.error('oops'); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [result1] = await promise2; diff --git a/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts b/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts index 07d5724a2520d..f80a97137d1ab 100644 --- a/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts +++ b/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts @@ -91,7 +91,7 @@ export const createStreamingBatchedFunction = ( }; return [future.promise, entry]; }, - onBatch: async items => { + onBatch: async (items) => { try { let responsesReceived = 0; const batch = items.map(({ payload }) => payload); @@ -111,7 +111,7 @@ export const createStreamingBatchedFunction = ( items[response.id].future.resolve(response.result); } }, - error: error => { + error: (error) => { const normalizedError = normalizeError(error); normalizedError.code = 'STREAM'; for (const { future } of items) future.reject(normalizedError); diff --git a/src/plugins/bfetch/public/plugin.ts b/src/plugins/bfetch/public/plugin.ts index 783c448c567e5..5f01957c0908e 100644 --- a/src/plugins/bfetch/public/plugin.ts +++ b/src/plugins/bfetch/public/plugin.ts @@ -78,7 +78,7 @@ export class BfetchPublicPlugin private fetchStreaming = ( version: string, basePath: string - ): BfetchPublicSetup['fetchStreaming'] => params => + ): BfetchPublicSetup['fetchStreaming'] => (params) => fetchStreamingStatic({ ...params, url: `${basePath}/${removeLeadingSlash(params.url)}`, @@ -91,7 +91,7 @@ export class BfetchPublicPlugin private batchedFunction = ( fetchStreaming: BfetchPublicContract['fetchStreaming'] - ): BfetchPublicContract['batchedFunction'] => params => + ): BfetchPublicContract['batchedFunction'] => (params) => createStreamingBatchedFunction({ ...params, fetchStreaming: params.fetchStreaming || fetchStreaming, diff --git a/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts b/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts index 7845616026ea1..27adc6dc8b549 100644 --- a/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts +++ b/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts @@ -20,7 +20,7 @@ import { fetchStreaming } from './fetch_streaming'; import { mockXMLHttpRequest } from '../test_helpers/xhr'; -const tick = () => new Promise(resolve => setTimeout(resolve, 1)); +const tick = () => new Promise((resolve) => setTimeout(resolve, 1)); const setup = () => { const { xhr, XMLHttpRequest } = mockXMLHttpRequest(); diff --git a/src/plugins/bfetch/public/streaming/split.test.ts b/src/plugins/bfetch/public/streaming/split.test.ts index 6eb3e27ad8598..fb9dcfb210d36 100644 --- a/src/plugins/bfetch/public/streaming/split.test.ts +++ b/src/plugins/bfetch/public/streaming/split.test.ts @@ -26,7 +26,7 @@ test('splits a single IP address', () => { const subject = new Subject(); const splitted = split('.')(subject); - splitted.subscribe(value => list.push(value)); + splitted.subscribe((value) => list.push(value)); subject.next(ip); subject.complete(); @@ -56,7 +56,7 @@ for (const stream of streams) { const list: string[] = []; const subject = new Subject(); const splitted = split('.')(subject); - splitted.subscribe(value => list.push(value)); + splitted.subscribe((value) => list.push(value)); let i = 0; while (i < stream.length) { const len = Math.round(Math.random() * 10); diff --git a/src/plugins/bfetch/public/streaming/split.ts b/src/plugins/bfetch/public/streaming/split.ts index 665411f472ac3..c970e07c97e9f 100644 --- a/src/plugins/bfetch/public/streaming/split.ts +++ b/src/plugins/bfetch/public/streaming/split.ts @@ -40,7 +40,7 @@ export const split = (delimiter: string = '\n') => ( let startingText = ''; in$.subscribe( - chunk => { + (chunk) => { const messages = (startingText + chunk).split(delimiter); // We don't want to send the last message here, since it may or diff --git a/src/plugins/bfetch/server/plugin.ts b/src/plugins/bfetch/server/plugin.ts index 0502781e34ce2..c27f34b8233cb 100644 --- a/src/plugins/bfetch/server/plugin.ts +++ b/src/plugins/bfetch/server/plugin.ts @@ -161,7 +161,7 @@ export class BfetchServerPlugin logger, }: { logger: Logger; - }): BfetchServerSetup['createStreamingRequestHandler'] => streamHandler => async ( + }): BfetchServerSetup['createStreamingRequestHandler'] => (streamHandler) => async ( context, request, response @@ -186,7 +186,7 @@ export class BfetchServerPlugin addStreamingResponseRoute< BatchRequestData, BatchResponseItem - >(path, request => { + >(path, (request) => { const handlerInstance = handler(request); return { getResponseStream: ({ batch }) => { diff --git a/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts b/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts index c567784becd16..2f476e95497e5 100644 --- a/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts +++ b/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts @@ -39,7 +39,7 @@ export const createNDJSONStream = ( logger.error(error); } }, - error: error => { + error: (error) => { stream.end(); logger.error(error); }, diff --git a/src/plugins/charts/public/services/colors/color_palette.ts b/src/plugins/charts/public/services/colors/color_palette.ts index 7b8e93bbde240..464e9e3a66101 100644 --- a/src/plugins/charts/public/services/colors/color_palette.ts +++ b/src/plugins/charts/public/services/colors/color_palette.ts @@ -24,7 +24,7 @@ import { seedColors } from './seed_colors'; const offset = 300; // Hue offset to start at -const fraction = function(goal: number) { +const fraction = function (goal: number) { const walkTree = (numerator: number, denominator: number, bytes: number[]): number => { if (bytes.length) { return walkTree(numerator * 2 + (bytes.pop() ? 1 : -1), denominator * 2, bytes); @@ -36,7 +36,7 @@ const fraction = function(goal: number) { const b = (goal + 2) .toString(2) .split('') - .map(function(num) { + .map(function (num) { return parseInt(num, 10); }); b.shift(); @@ -57,7 +57,7 @@ export function createColorPalette(num?: any): string[] { const colors = seedColors; const seedLength = seedColors.length; - _.times(num - seedLength, function(i) { + _.times(num - seedLength, function (i) { colors.push(d3.hsl((fraction(i + seedLength + 1) * 360 + offset) % 360, 0.5, 0.5).toString()); }); diff --git a/src/plugins/charts/public/services/colors/colors.test.ts b/src/plugins/charts/public/services/colors/colors.test.ts index e3f99f2407f75..a4d7a0781eabd 100644 --- a/src/plugins/charts/public/services/colors/colors.test.ts +++ b/src/plugins/charts/public/services/colors/colors.test.ts @@ -28,7 +28,7 @@ const config = new Map(); describe('Vislib Color Service', () => { const colors = new ColorsService(); const mockUiSettings = coreMock.createSetup().uiSettings; - mockUiSettings.get.mockImplementation(a => config.get(a)); + mockUiSettings.get.mockImplementation((a) => config.get(a)); mockUiSettings.set.mockImplementation((...a) => config.set(...a) as any); colors.init(mockUiSettings); diff --git a/src/plugins/charts/public/services/colors/colors.ts b/src/plugins/charts/public/services/colors/colors.ts index 3c12adf84d8b2..7a1ffc433ee87 100644 --- a/src/plugins/charts/public/services/colors/colors.ts +++ b/src/plugins/charts/public/services/colors/colors.ts @@ -57,7 +57,7 @@ export class ColorsService { ); } - arrayOfStringsOrNumbers.forEach(function(val) { + arrayOfStringsOrNumbers.forEach(function (val) { if (!_.isString(val) && !_.isNumber(val) && !_.isUndefined(val)) { throw new TypeError( 'createColorLookupFunction expects an array of strings, numbers, or undefined values' diff --git a/src/plugins/charts/public/services/colors/mapped_colors.test.ts b/src/plugins/charts/public/services/colors/mapped_colors.test.ts index c3b9b0909051c..2c9f37afc14c5 100644 --- a/src/plugins/charts/public/services/colors/mapped_colors.test.ts +++ b/src/plugins/charts/public/services/colors/mapped_colors.test.ts @@ -30,7 +30,7 @@ const config = new Map(); describe('Mapped Colors', () => { const mockUiSettings = coreMock.createSetup().uiSettings; - mockUiSettings.get.mockImplementation(a => config.get(a)); + mockUiSettings.get.mockImplementation((a) => config.get(a)); mockUiSettings.set.mockImplementation((...a) => config.set(...a) as any); const mappedColors = new MappedColors(mockUiSettings); @@ -50,12 +50,7 @@ describe('Mapped Colors', () => { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(arr.length); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(arr.length); }); it('should not include colors used by the config', () => { @@ -77,15 +72,8 @@ describe('Mapped Colors', () => { const arr = ['foo', 'bar', 'baz', 'qux']; mappedColors.mapKeys(arr); - const expectedSize = _(arr) - .difference(_.keys(newConfig)) - .size(); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(expectedSize); + const expectedSize = _(arr).difference(_.keys(newConfig)).size(); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(expectedSize); expect(mappedColors.get(arr[0])).not.toBe(seedColors[0]); }); @@ -98,20 +86,13 @@ describe('Mapped Colors', () => { const arr = ['foo', 'bar', 'baz', 'qux']; mappedColors.mapKeys(arr); - const expectedSize = _(arr) - .difference(_.keys(newConfig)) - .size(); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(expectedSize); + const expectedSize = _(arr).difference(_.keys(newConfig)).size(); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(expectedSize); expect(mappedColors.get(arr[0])).not.toBe(seedColors[0]); expect(mappedColors.get('bar')).toBe(seedColors[0]); }); - it('should have a flush method that moves the current map to the old map', function() { + it('should have a flush method that moves the current map to the old map', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); expect(_.keys(mappedColors.mapping).length).toBe(5); @@ -128,7 +109,7 @@ describe('Mapped Colors', () => { expect(_.keys(mappedColors.mapping).length).toBe(0); }); - it('should use colors in the oldMap if they are available', function() { + it('should use colors in the oldMap if they are available', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); expect(_.keys(mappedColors.mapping).length).toBe(5); @@ -147,7 +128,7 @@ describe('Mapped Colors', () => { expect(mappedColors.mapping[5]).toEqual(mappedColors.oldMap[5]); }); - it('should have a purge method that clears both maps', function() { + it('should have a purge method that clears both maps', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); mappedColors.flush(); diff --git a/src/plugins/charts/public/services/colors/mapped_colors.ts b/src/plugins/charts/public/services/colors/mapped_colors.ts index 1469d357e7e79..fe0deac734e6b 100644 --- a/src/plugins/charts/public/services/colors/mapped_colors.ts +++ b/src/plugins/charts/public/services/colors/mapped_colors.ts @@ -73,7 +73,7 @@ export class MappedColors { const oldColors = _.values(this._oldMap); const keysToMap: Array = []; - _.each(keys, key => { + _.each(keys, (key) => { // If this key is mapped in the config, it's unnecessary to have it mapped here if (configMapping[key]) delete this._mapping[key]; @@ -88,11 +88,7 @@ export class MappedColors { }); // Generate a color palette big enough that all new keys can have unique color values - const allColors = _(this._mapping) - .values() - .union(configColors) - .union(oldColors) - .value(); + const allColors = _(this._mapping).values().union(configColors).union(oldColors).value(); const colorPalette = createColorPalette(allColors.length + keysToMap.length); let newColors = _.difference(colorPalette, allColors); diff --git a/src/plugins/charts/public/services/colors/seed_colors.test.ts b/src/plugins/charts/public/services/colors/seed_colors.test.ts index c4aac726e49e7..51a96409a4ec1 100644 --- a/src/plugins/charts/public/services/colors/seed_colors.test.ts +++ b/src/plugins/charts/public/services/colors/seed_colors.test.ts @@ -19,8 +19,8 @@ import { seedColors } from './seed_colors'; -describe('Seed Colors', function() { - it('should return an array', function() { +describe('Seed Colors', function () { + it('should return an array', function () { expect(seedColors).toBeInstanceOf(Array); }); }); diff --git a/src/plugins/charts/public/services/theme/theme.ts b/src/plugins/charts/public/services/theme/theme.ts index 65d4dc3393658..166e1c539688a 100644 --- a/src/plugins/charts/public/services/theme/theme.ts +++ b/src/plugins/charts/public/services/theme/theme.ts @@ -57,7 +57,7 @@ export class ThemeService { this._chartsTheme$ = uiSettings .get$('theme:darkMode') .pipe( - map(darkMode => (darkMode ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme)) + map((darkMode) => (darkMode ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme)) ); } } diff --git a/src/plugins/charts/public/static/color_maps/heatmap_color.ts b/src/plugins/charts/public/static/color_maps/heatmap_color.ts index afc649b68826e..9c3067fd8d6ac 100644 --- a/src/plugins/charts/public/static/color_maps/heatmap_color.ts +++ b/src/plugins/charts/public/static/color_maps/heatmap_color.ts @@ -37,7 +37,7 @@ function interpolateLinearly(x: number, values: RawColorSchema['value']) { const rValues: number[] = []; const gValues: number[] = []; const bValues: number[] = []; - values.forEach(value => { + values.forEach((value) => { xValues.push(value[0]); rValues.push(value[1][0]); gValues.push(value[1][1]); diff --git a/src/plugins/charts/public/static/components/number_input.tsx b/src/plugins/charts/public/static/components/number_input.tsx index b614e00ba8cd0..8c2874f522902 100644 --- a/src/plugins/charts/public/static/components/number_input.tsx +++ b/src/plugins/charts/public/static/components/number_input.tsx @@ -65,7 +65,7 @@ function NumberInputOption({ max={max} min={min} value={value} - onChange={ev => + onChange={(ev) => setValue(paramName, isNaN(ev.target.valueAsNumber) ? '' : ev.target.valueAsNumber) } /> diff --git a/src/plugins/charts/public/static/components/select.tsx b/src/plugins/charts/public/static/components/select.tsx index 8ce7f4d640898..31cc1cd14e2f6 100644 --- a/src/plugins/charts/public/static/components/select.tsx +++ b/src/plugins/charts/public/static/components/select.tsx @@ -63,7 +63,7 @@ function SelectOption setValue(paramName, ev.target.value as ValidParamValues)} + onChange={(ev) => setValue(paramName, ev.target.value as ValidParamValues)} fullWidth={true} data-test-subj={dataTestSubj} /> diff --git a/src/plugins/charts/public/static/components/switch.tsx b/src/plugins/charts/public/static/components/switch.tsx index bdaf602cad5c6..a873e6d15feeb 100644 --- a/src/plugins/charts/public/static/components/switch.tsx +++ b/src/plugins/charts/public/static/components/switch.tsx @@ -49,7 +49,7 @@ function SwitchOption({ checked={value} disabled={disabled} data-test-subj={dataTestSubj} - onChange={ev => setValue(paramName, ev.target.checked)} + onChange={(ev) => setValue(paramName, ev.target.checked)} /> diff --git a/src/plugins/charts/public/static/components/text_input.tsx b/src/plugins/charts/public/static/components/text_input.tsx index 0ab004102bdb8..03486c7056d62 100644 --- a/src/plugins/charts/public/static/components/text_input.tsx +++ b/src/plugins/charts/public/static/components/text_input.tsx @@ -47,7 +47,7 @@ function TextInputOption({ data-test-subj={dataTestSubj} disabled={disabled} value={value} - onChange={ev => setValue(paramName, ev.target.value)} + onChange={(ev) => setValue(paramName, ev.target.value)} /> ); diff --git a/src/plugins/console/public/application/components/console_menu.tsx b/src/plugins/console/public/application/components/console_menu.tsx index 7842c15be267f..df0c8145fd5ce 100644 --- a/src/plugins/console/public/application/components/console_menu.tsx +++ b/src/plugins/console/public/application/components/console_menu.tsx @@ -48,7 +48,7 @@ export class ConsoleMenu extends Component { mouseEnter = () => { if (this.state.isPopoverOpen) return; - this.props.getCurl().then(text => { + this.props.getCurl().then((text) => { this.setState({ curlCode: text }); }); }; @@ -75,7 +75,7 @@ export class ConsoleMenu extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/console/public/application/components/settings_modal.tsx b/src/plugins/console/public/application/components/settings_modal.tsx index 3cd20bf1bc343..377e739a0c59a 100644 --- a/src/plugins/console/public/application/components/settings_modal.tsx +++ b/src/plugins/console/public/application/components/settings_modal.tsx @@ -87,7 +87,7 @@ export function DevToolsSettingsModal(props: Props) { }; const onAutocompleteChange = (optionId: AutocompleteOptions) => { - const option = _.find(autoCompleteCheckboxes, item => item.id === optionId); + const option = _.find(autoCompleteCheckboxes, (item) => item.id === optionId); if (option) { option.stateSetter(!checkboxIdToSelectedMap[optionId]); } @@ -136,7 +136,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.pollingLabelText" /> } - onChange={e => setPolling(e.target.checked)} + onChange={(e) => setPolling(e.target.checked)} /> @@ -158,9 +158,7 @@ export function DevToolsSettingsModal(props: Props) { /> - ) : ( - undefined - ); + ) : undefined; return ( @@ -193,7 +191,7 @@ export function DevToolsSettingsModal(props: Props) { value={fontSize} min={6} max={50} - onChange={e => { + onChange={(e) => { const val = parseInt(e.target.value, 10); if (!val) return; setFontSize(val); @@ -212,7 +210,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.wrapLongLinesLabelText" /> } - onChange={e => setWrapMode(e.target.checked)} + onChange={(e) => setWrapMode(e.target.checked)} /> @@ -234,7 +232,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.tripleQuotesMessage" /> } - onChange={e => setTripleQuotes(e.target.checked)} + onChange={(e) => setTripleQuotes(e.target.checked)} /> @@ -248,7 +246,7 @@ export function DevToolsSettingsModal(props: Props) { } > { + options={autoCompleteCheckboxes.map((opts) => { const { stateSetter, ...rest } = opts; return rest; })} diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx index 47f7aa1635205..6d4f532887cd9 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx @@ -119,7 +119,7 @@ function EditorUI({ initialTextValue }: EditorProps) { } // Fire and forget. - $.ajax(loadFrom).done(async data => { + $.ajax(loadFrom).done(async (data) => { const coreEditor = editor.getCoreEditor(); await editor.update(data, true); editor.moveToNextRequestEdge(false); @@ -188,10 +188,7 @@ function EditorUI({ initialTextValue }: EditorProps) { const { current: editor } = editorInstanceRef; applyCurrentSettings(editor!.getCoreEditor(), settings); // Preserve legacy focus behavior after settings have updated. - editor! - .getCoreEditor() - .getContainer() - .focus(); + editor!.getCoreEditor().getContainer().focus(); }, [settings]); useEffect(() => { diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx index 8510aaebfaa1e..dd5ef5209a244 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx @@ -72,8 +72,8 @@ function EditorOutputUI() { editor.session.setMode(mode); editor.update( data - .map(d => d.response.value as string) - .map(readOnlySettings.tripleQuotes ? expandLiteralStrings : a => a) + .map((d) => d.response.value as string) + .map(readOnlySettings.tripleQuotes ? expandLiteralStrings : (a) => a) .join('\n') ); } else if (error) { diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts b/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts index 2bbe49cd53eac..a10458aaf28bd 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts +++ b/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts @@ -23,17 +23,14 @@ import { SenseEditor } from '../../../models/sense_editor'; export async function autoIndent(editor: SenseEditor, event: Event) { event.preventDefault(); await editor.autoIndent(); - editor - .getCoreEditor() - .getContainer() - .focus(); + editor.getCoreEditor().getContainer().focus(); } export function getDocumentation( editor: SenseEditor, docLinkVersion: string ): Promise { - return editor.getRequestsInRange().then(requests => { + return editor.getRequestsInRange().then((requests) => { if (!requests || requests.length === 0) { return null; } diff --git a/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts b/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts index 2d992aadbf15a..01233a7c42d52 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts +++ b/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts @@ -22,7 +22,7 @@ import { ResizeChecker } from '../../../../../../kibana_utils/public'; export function subscribeResizeChecker(el: HTMLElement, ...editors: any[]) { const checker = new ResizeChecker(el); checker.on('resize', () => - editors.forEach(e => { + editors.forEach((e) => { if (e.getCoreEditor) { e.getCoreEditor().resize(); } else { diff --git a/src/plugins/console/public/application/containers/settings.tsx b/src/plugins/console/public/application/containers/settings.tsx index 81938a83435de..acd9b88d8b5b9 100644 --- a/src/plugins/console/public/application/containers/settings.tsx +++ b/src/plugins/console/public/application/containers/settings.tsx @@ -26,7 +26,7 @@ import { useServicesContext, useEditorActionContext } from '../contexts'; import { DevToolsSettings, Settings as SettingsService } from '../../services'; const getAutocompleteDiff = (newSettings: DevToolsSettings, prevSettings: DevToolsSettings) => { - return Object.keys(newSettings.autocomplete).filter(key => { + return Object.keys(newSettings.autocomplete).filter((key) => { // @ts-ignore return prevSettings.autocomplete[key] !== newSettings.autocomplete[key]; }); diff --git a/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx b/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx index d5ed44e3f6ba2..884ad7d7e3585 100644 --- a/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx +++ b/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx @@ -31,7 +31,7 @@ export interface EditorContextArgs { } export function EditorContextProvider({ children, settings }: EditorContextArgs) { - const [state, dispatch] = useReducer(editor.reducer, editor.initialValue, value => ({ + const [state, dispatch] = useReducer(editor.reducer, editor.initialValue, (value) => ({ ...value, settings, })); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js index a68a2b3939864..81171c2bd26fe 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js @@ -81,7 +81,7 @@ describe('Input', () => { data = prefix; } - test('Token test ' + testCount++ + ' prefix: ' + prefix, async function() { + test('Token test ' + testCount++ + ' prefix: ' + prefix, async function () { await coreEditor.setValue(data, true); const tokens = tokensAsList(); const normTokenList = []; @@ -473,7 +473,7 @@ describe('Input', () => { data = prefix; } - test('States test ' + testCount++ + ' prefix: ' + prefix, async function() { + test('States test ' + testCount++ + ' prefix: ' + prefix, async function () { await coreEditor.setValue(data, true); const modes = statesAsList(); expect(modes).toEqual(statesList); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js index 1db9ca7bc0a86..ea7530bd21387 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js @@ -57,8 +57,8 @@ describe('Output Tokenization', () => { data = JSON.stringify(data, null, 3); } - test('Token test ' + testCount++, async function(done) { - output.update(data, function() { + test('Token test ' + testCount++, async function (done) { + output.update(data, function () { const tokens = tokensAsList(); const normTokenList = []; for (let i = 0; i < tokenList.length; i++) { diff --git a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts index 66673ff42e4e8..f90b803a77004 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts @@ -22,7 +22,7 @@ jest.mock('./mode/worker', () => { }); // @ts-ignore -window.Worker = function() { +window.Worker = function () { this.postMessage = () => {}; (this as any).terminate = () => {}; }; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts index fc419b0f10dca..396356f98500d 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts @@ -74,7 +74,7 @@ export class LegacyCoreEditor implements CoreEditor { // dirty check for tokenizer state, uses a lot less cycles // than listening for tokenizerUpdate waitForLatestTokens(): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { const session = this.editor.getSession(); const checkInterval = 25; @@ -239,9 +239,9 @@ export class LegacyCoreEditor implements CoreEditor { private forceRetokenize() { const session = this.editor.getSession(); - return new Promise(resolve => { + return new Promise((resolve) => { // force update of tokens, but not on this thread to allow for ace rendering. - setTimeout(function() { + setTimeout(function () { let i; for (i = 0; i < session.getLength(); i++) { session.getTokens(i); @@ -368,11 +368,11 @@ export class LegacyCoreEditor implements CoreEditor { // disable standard context based autocompletion. // @ts-ignore - ace.define('ace/autocomplete/text_completer', ['require', 'exports', 'module'], function( + ace.define('ace/autocomplete/text_completer', ['require', 'exports', 'module'], function ( require: any, exports: any ) { - exports.getCompletions = function( + exports.getCompletions = function ( innerEditor: any, session: any, pos: any, diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js index 77b4ba8cea6ff..4031167f72c91 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js @@ -43,13 +43,13 @@ export function Mode() { } oop.inherits(Mode, TextMode); -(function() { - this.getCompletions = function() { +(function () { + this.getCompletions = function () { // autocomplete is done by the autocomplete module. return []; }; - this.getNextLineIndent = function(state, line, tab) { + this.getNextLineIndent = function (state, line, tab) { let indent = this.$getIndent(line); if (state !== 'string_literal') { @@ -62,21 +62,21 @@ oop.inherits(Mode, TextMode); return indent; }; - this.checkOutdent = function(state, line, input) { + this.checkOutdent = function (state, line, input) { return this.$outdent.checkOutdent(line, input); }; - this.autoOutdent = function(state, doc, row) { + this.autoOutdent = function (state, doc, row) { this.$outdent.autoOutdent(doc, row); }; - this.createWorker = function(session) { + this.createWorker = function (session) { const worker = new WorkerClient(['ace', 'sense_editor'], workerModule, 'SenseWorker'); worker.attachToDocument(session.getDocument()); - worker.on('error', function(e) { + worker.on('error', function (e) { session.setAnnotations([e.data]); }); - worker.on('ok', function(anno) { + worker.on('ok', function (anno) { session.setAnnotations(anno.data); }); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js index 5ad34532d1861..da9ce41611671 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js @@ -37,8 +37,8 @@ export function Mode() { } oop.inherits(Mode, JSONMode); -(function() { - this.createWorker = function() { +(function () { + this.createWorker = function () { return null; }; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js index 89adea8921c07..6079c9db40eef 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js @@ -35,10 +35,10 @@ export function ScriptMode() { oop.inherits(ScriptMode, TextMode); -(function() { +(function () { this.HighlightRules = ScriptHighlightRules; - this.getNextLineIndent = function(state, line, tab) { + this.getNextLineIndent = function (state, line, tab) { let indent = this.$getIndent(line); const match = line.match(/^.*[\{\[]\s*$/); if (match) { @@ -48,11 +48,11 @@ oop.inherits(ScriptMode, TextMode); return indent; }; - this.checkOutdent = function(state, line, input) { + this.checkOutdent = function (state, line, input) { return this.$outdent.checkOutdent(line, input); }; - this.autoOutdent = function(state, doc, row) { + this.autoOutdent = function (state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }.call(ScriptMode.prototype)); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts b/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts index 7c4d871c4d73e..e6d7d8272b35b 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts @@ -20,7 +20,7 @@ import { get, throttle } from 'lodash'; // eslint-disable-next-line import/no-default-export -export default function(editor: any) { +export default function (editor: any) { const resize = editor.resize; const throttledResize = throttle(() => { diff --git a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js index 8a0eb9a03480b..86d17933c746f 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js @@ -20,7 +20,7 @@ /* eslint import/no-unresolved: 0 */ import ace from 'brace'; -ace.define('ace/theme/sense-dark', ['require', 'exports', 'module'], function(require, exports) { +ace.define('ace/theme/sense-dark', ['require', 'exports', 'module'], function (require, exports) { exports.isDark = true; exports.cssClass = 'ace-sense-dark'; exports.cssText = diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js index edd09885c1ad2..b7cc8f2f4b72f 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js @@ -41,7 +41,7 @@ describe('Integration', () => { }); function processContextTest(data, mapping, kbSchemes, requestLine, testToRun) { - test(testToRun.name, async function(done) { + test(testToRun.name, async function (done) { let lineOffset = 0; // add one for the extra method line let editorValue = data; if (requestLine != null) { @@ -67,7 +67,7 @@ describe('Integration', () => { // }); // } if (kbSchemes.endpoints) { - $.each(kbSchemes.endpoints, function(endpoint, scheme) { + $.each(kbSchemes.endpoints, function (endpoint, scheme) { testApi.addEndpointDescription(endpoint, scheme); }); } @@ -81,10 +81,10 @@ describe('Integration', () => { //setTimeout(function () { senseEditor.completer = { base: {}, - changeListener: function() {}, + changeListener: function () {}, }; // mimic auto complete - senseEditor.autocomplete._test.getCompletions(senseEditor, null, cursor, '', function( + senseEditor.autocomplete._test.getCompletions(senseEditor, null, cursor, '', function ( err, terms ) { @@ -110,7 +110,7 @@ describe('Integration', () => { } if (testToRun.autoCompleteSet) { - const expectedTerms = _.map(testToRun.autoCompleteSet, function(t) { + const expectedTerms = _.map(testToRun.autoCompleteSet, function (t) { if (typeof t !== 'object') { t = { name: t }; } @@ -119,10 +119,10 @@ describe('Integration', () => { if (terms.length !== expectedTerms.length) { expect(_.pluck(terms, 'name')).toEqual(_.pluck(expectedTerms, 'name')); } else { - const filteredActualTerms = _.map(terms, function(actualTerm, i) { + const filteredActualTerms = _.map(terms, function (actualTerm, i) { const expectedTerm = expectedTerms[i]; const filteredTerm = {}; - _.each(expectedTerm, function(v, p) { + _.each(expectedTerm, function (v, p) { filteredTerm[p] = actualTerm[p]; }); return filteredTerm; @@ -739,7 +739,7 @@ describe('Integration', () => { }, ], g: { - __scope_link: function() { + __scope_link: function () { return { a: 1, b: 2, diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js index 219e6262ab346..c3fb879f2eeeb 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js @@ -28,7 +28,7 @@ import editorInput1 from './editor_input1.txt'; describe('Editor', () => { let input; - beforeEach(function() { + beforeEach(function () { // Set up our document body document.body.innerHTML = `
@@ -40,14 +40,14 @@ describe('Editor', () => { $(input.getCoreEditor().getContainer()).show(); input.autocomplete._test.removeChangeListener(); }); - afterEach(function() { + afterEach(function () { $(input.getCoreEditor().getContainer()).hide(); input.autocomplete._test.addChangeListener(); }); let testCount = 0; - const callWithEditorMethod = (editorMethod, fn) => async done => { + const callWithEditorMethod = (editorMethod, fn) => async (done) => { const results = await input[editorMethod](); fn(results, done); }; @@ -69,7 +69,7 @@ describe('Editor', () => { data = prefix; } - test('Utils test ' + id + ' : ' + name, async function(done) { + test('Utils test ' + id + ' : ' + name, async function (done) { await input.update(data, true); testToRun(done); }); @@ -81,7 +81,7 @@ describe('Editor', () => { expected = [expected]; } - _.each(requests, function(r) { + _.each(requests, function (r) { delete r.range; }); expect(requests).toEqual(expected); @@ -340,10 +340,10 @@ describe('Editor', () => { ); function multiReqTest(name, editorInput, range, expected) { - utilsTest('multi request select - ' + name, editorInput, async function(done) { + utilsTest('multi request select - ' + name, editorInput, async function (done) { const requests = await input.getRequestsInRange(range, false); // convert to format returned by request. - _.each(expected, function(req) { + _.each(expected, function (req) { req.data = req.data == null ? [] : [JSON.stringify(req.data, null, 2)]; }); @@ -451,7 +451,7 @@ describe('Editor', () => { ); function multiReqCopyAsCurlTest(name, editorInput, range, expected) { - utilsTest('multi request copy as curl - ' + name, editorInput, async function(done) { + utilsTest('multi request copy as curl - ' + name, editorInput, async function (done) { const curl = await input.getRequestsAsCURL('http://localhost:9200', range); expect(curl).toEqual(expected); done(); diff --git a/src/plugins/console/public/application/models/sense_editor/sense_editor.ts b/src/plugins/console/public/application/models/sense_editor/sense_editor.ts index d326543bbe00b..dbf4f1adcba0a 100644 --- a/src/plugins/console/public/application/models/sense_editor/sense_editor.ts +++ b/src/plugins/console/public/application/models/sense_editor/sense_editor.ts @@ -425,8 +425,8 @@ export class SenseEditor { } const column = - (this.coreEditor.getLineValue(curLineNumber) || '').length + - 1 /* Range goes to 1 after last char */; + (this.coreEditor.getLineValue(curLineNumber) || '').length + + 1; /* Range goes to 1 after last char */ return { lineNumber: curLineNumber, @@ -467,7 +467,7 @@ export class SenseEditor { getRequestsAsCURL = async (elasticsearchBaseUrl: string, range?: Range): Promise => { const requests = await this.getRequestsInRange(range, true); - const result = _.map(requests, req => { + const result = _.map(requests, (req) => { if (typeof req === 'string') { // no request block return req; diff --git a/src/plugins/console/public/application/stores/editor.ts b/src/plugins/console/public/application/stores/editor.ts index 73c29e7ff8575..c8a5b2421d52d 100644 --- a/src/plugins/console/public/application/stores/editor.ts +++ b/src/plugins/console/public/application/stores/editor.ts @@ -44,7 +44,7 @@ export type Action = | { type: 'updateSettings'; payload: DevToolsSettings }; export const reducer: Reducer = (state, action) => - produce(state, draft => { + produce(state, (draft) => { if (action.type === 'setInputEditor') { if (action.payload) { draft.ready = true; diff --git a/src/plugins/console/public/application/stores/request.ts b/src/plugins/console/public/application/stores/request.ts index f711330df3911..4ec9eae7e10d4 100644 --- a/src/plugins/console/public/application/stores/request.ts +++ b/src/plugins/console/public/application/stores/request.ts @@ -50,7 +50,7 @@ export const initialValue: Store = produce( ); export const reducer: Reducer = (state, action) => - produce(state, draft => { + produce(state, (draft) => { if (action.type === 'sendRequest') { draft.requestInFlight = true; draft.lastResult = initialResultValue; diff --git a/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts b/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts index d5465ebe96514..75b1bb802327e 100644 --- a/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts +++ b/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts @@ -74,7 +74,7 @@ describe('Ace (legacy) token provider', () => { }; describe('base cases', () => { - test('case 1 - only url', done => { + test('case 1 - only url', (done) => { runTest({ input: `GET http://somehost/_search`, expectedTokens: [ @@ -92,7 +92,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 2 - basic auth in host name', done => { + test('case 2 - basic auth in host name', (done) => { runTest({ input: `GET http://test:user@somehost/`, expectedTokens: [ @@ -109,7 +109,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 3 - handles empty lines', done => { + test('case 3 - handles empty lines', (done) => { runTest({ input: `POST abc @@ -128,7 +128,7 @@ describe('Ace (legacy) token provider', () => { }); describe('with newlines', () => { - test('case 1 - newlines base case', done => { + test('case 1 - newlines base case', (done) => { runTest({ input: `GET http://test:user@somehost/ { @@ -148,7 +148,7 @@ describe('Ace (legacy) token provider', () => { }); describe('edge cases', () => { - test('case 1 - getting token outside of document', done => { + test('case 1 - getting token outside of document', (done) => { runTest({ input: `GET http://test:user@somehost/ { @@ -160,7 +160,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 2 - empty lines', done => { + test('case 2 - empty lines', (done) => { runTest({ input: `GET http://test:user@somehost/ @@ -193,7 +193,7 @@ describe('Ace (legacy) token provider', () => { }; describe('base cases', () => { - it('case 1 - gets a token from the url', done => { + it('case 1 - gets a token from the url', (done) => { const input = `GET http://test:user@somehost/`; runTest({ input, @@ -219,7 +219,7 @@ describe('Ace (legacy) token provider', () => { }); describe('special cases', () => { - it('case 1 - handles input outside of range', done => { + it('case 1 - handles input outside of range', (done) => { runTest({ input: `GET abc`, expectedToken: null, diff --git a/src/plugins/console/public/lib/ace_token_provider/token_provider.ts b/src/plugins/console/public/lib/ace_token_provider/token_provider.ts index 134ab6c0e82d5..93bf7ce4c76d5 100644 --- a/src/plugins/console/public/lib/ace_token_provider/token_provider.ts +++ b/src/plugins/console/public/lib/ace_token_provider/token_provider.ts @@ -36,7 +36,7 @@ const toToken = (lineNumber: number, column: number, token: TokenInfo): Token => const toTokens = (lineNumber: number, tokens: TokenInfo[]): Token[] => { let acc = ''; - return tokens.map(token => { + return tokens.map((token) => { const column = acc.length + 1; acc += token.value; return toToken(lineNumber, column, token); diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js index ebde8c39cffbc..0c3fcbafbe9f9 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js @@ -28,11 +28,11 @@ import { populateContext } from '../../autocomplete/engine'; describe('Url autocomplete', () => { function patternsTest(name, endpoints, tokenPath, expectedContext, globalUrlComponentFactories) { - test(name, function() { + test(name, function () { const patternMatcher = new UrlPatternMatcher(globalUrlComponentFactories); - _.each(endpoints, function(e, id) { + _.each(endpoints, function (e, id) { e.id = id; - _.each(e.patterns, function(p) { + _.each(e.patterns, function (p) { patternMatcher.addEndpoint(p, e); }); }); @@ -40,7 +40,7 @@ describe('Url autocomplete', () => { if (tokenPath[tokenPath.length - 1] === '$') { tokenPath = tokenPath.substr(0, tokenPath.length - 1) + '/' + URL_PATH_END_MARKER; } - tokenPath = _.map(tokenPath.split('/'), function(p) { + tokenPath = _.map(tokenPath.split('/'), function (p) { p = p.split(','); if (p.length === 1) { return p[0]; @@ -50,7 +50,7 @@ describe('Url autocomplete', () => { } if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -91,7 +91,7 @@ describe('Url autocomplete', () => { return name; } - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b'], @@ -123,7 +123,7 @@ describe('Url autocomplete', () => { patternsTest('simple single path - different path', endpoints, 'a/c', {}); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b', 'a/b/{p}'], @@ -174,7 +174,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/{p}'], @@ -228,7 +228,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/{p}'], @@ -254,7 +254,7 @@ describe('Url autocomplete', () => { }, }; const globalFactories = { - p: function(name, parent) { + p: function (name, parent) { return new ListComponent(name, ['g1', 'g2'], parent); }, getComponent(name) { @@ -313,7 +313,7 @@ describe('Url autocomplete', () => { ); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b/{p}/c/e'], @@ -343,7 +343,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1_param': { patterns: ['a/{p}'], @@ -378,7 +378,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1_GET': { patterns: ['a'], diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js index 286aefcd133a0..e624e7ba57b61 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js @@ -22,10 +22,10 @@ import { populateContext } from '../../autocomplete/engine'; describe('Url params', () => { function paramTest(name, description, tokenPath, expectedContext, globalParams) { - test(name, function() { + test(name, function () { const urlParams = new UrlParams(description, globalParams || {}); if (typeof tokenPath === 'string') { - tokenPath = _.map(tokenPath.split('/'), function(p) { + tokenPath = _.map(tokenPath.split('/'), function (p) { p = p.split(','); if (p.length === 1) { return p[0]; @@ -35,7 +35,7 @@ describe('Url params', () => { } if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -79,7 +79,7 @@ describe('Url params', () => { return r; } - (function() { + (function () { const params = { a: ['1', '2'], b: '__flag__', diff --git a/src/plugins/console/public/lib/autocomplete/autocomplete.ts b/src/plugins/console/public/lib/autocomplete/autocomplete.ts index d4f10ff4e4277..b05c7ddbb020d 100644 --- a/src/plugins/console/public/lib/autocomplete/autocomplete.ts +++ b/src/plugins/console/public/lib/autocomplete/autocomplete.ts @@ -321,7 +321,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } function addMetaToTermsList(list: any, meta: any, template?: string) { - return _.map(list, function(t: any) { + return _.map(list, function (t: any) { if (typeof t !== 'object') { t = { name: t }; } @@ -955,7 +955,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } else { const terms = _.map( context.autoCompleteSet.filter((term: any) => Boolean(term) && term.name != null), - function(term: any) { + function (term: any) { if (typeof term !== 'object') { term = { name: term, @@ -981,7 +981,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } ); - terms.sort(function(t1: any, t2: any) { + terms.sort(function (t1: any, t2: any) { /* score sorts from high to low */ if (t1.score > t2.score) { return -1; @@ -1001,7 +1001,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor callback( null, - _.map(terms, function(t: any, i: any) { + _.map(terms, function (t: any, i: any) { t.insertValue = t.insertValue || t.value; t.value = '' + t.value; // normalize to strings t.score = -i; diff --git a/src/plugins/console/public/lib/autocomplete/body_completer.js b/src/plugins/console/public/lib/autocomplete/body_completer.js index 9bb1f14a6266a..f37b3ac0cca9c 100644 --- a/src/plugins/console/public/lib/autocomplete/body_completer.js +++ b/src/plugins/console/public/lib/autocomplete/body_completer.js @@ -104,7 +104,7 @@ class ScopeResolver extends SharedComponent { getTerms(context, editor) { const options = []; const components = this.resolveLinkToComponents(context, editor); - _.each(components, function(component) { + _.each(components, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); return options; @@ -115,7 +115,7 @@ class ScopeResolver extends SharedComponent { next: [], }; const components = this.resolveLinkToComponents(context, editor); - _.each(components, function(component) { + _.each(components, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); @@ -193,7 +193,7 @@ function compileDescription(description, compilingContext) { } if (description.__one_of) { return _.flatten( - _.map(description.__one_of, function(d) { + _.map(description.__one_of, function (d) { return compileDescription(d, compilingContext); }) ); @@ -228,7 +228,7 @@ function compileObject(objDescription, compilingContext) { const objectC = new ConstantComponent('{'); const constants = []; const patterns = []; - _.each(objDescription, function(desc, key) { + _.each(objDescription, function (desc, key) { if (key.indexOf('__') === 0) { // meta key return; @@ -247,7 +247,7 @@ function compileObject(objDescription, compilingContext) { component = new ConstantComponent(key, null, [options]); constants.push(component); } - _.map(compileDescription(desc, compilingContext), function(subComponent) { + _.map(compileDescription(desc, compilingContext), function (subComponent) { component.addComponent(subComponent); }); }); @@ -257,8 +257,8 @@ function compileObject(objDescription, compilingContext) { function compileList(listRule, compilingContext) { const listC = new ConstantComponent('['); - _.each(listRule, function(desc) { - _.each(compileDescription(desc, compilingContext), function(component) { + _.each(listRule, function (desc) { + _.each(compileDescription(desc, compilingContext), function (component) { listC.addComponent(component); }); }); @@ -268,7 +268,7 @@ function compileList(listRule, compilingContext) { /** takes a compiled object and wraps in a {@link ConditionalProxy }*/ function compileCondition(description, compiledObject) { if (description.lines_regex) { - return new ConditionalProxy(function(context, editor) { + return new ConditionalProxy(function (context, editor) { const lines = editor .getLines(context.requestStartRow, editor.getCurrentPosition().lineNumber) .join('\n'); diff --git a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js index 80f65406cf5d3..05c72ea8a8dc5 100644 --- a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js @@ -21,7 +21,7 @@ import { getFields } from '../../mappings/mappings'; import { ListComponent } from './list_component'; function FieldGenerator(context) { - return _.map(getFields(context.indices, context.types), function(field) { + return _.map(getFields(context.indices, context.types), function (field) { return { name: field.name, meta: field.type }; }); } @@ -35,7 +35,7 @@ export class FieldAutocompleteComponent extends ListComponent { return false; } - return !_.find(tokens, function(token) { + return !_.find(tokens, function (token) { return token.match(/[^\w.?*]/); }); } diff --git a/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js index d6deadc75ed74..88b9320b3c45e 100644 --- a/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js @@ -33,7 +33,7 @@ export class IdAutocompleteComponent extends SharedComponent { } token = Array.isArray(token) ? token : [token]; if ( - _.find(token, function(t) { + _.find(token, function (t) { return t.match(/[\/,]/); }) ) { diff --git a/src/plugins/console/public/lib/autocomplete/components/list_component.js b/src/plugins/console/public/lib/autocomplete/components/list_component.js index 2f443ffaf6c93..b770638a61ff7 100644 --- a/src/plugins/console/public/lib/autocomplete/components/list_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/list_component.js @@ -24,7 +24,7 @@ export class ListComponent extends SharedComponent { constructor(name, list, parent, multiValued, allowNonValidValues) { super(name, parent); this.listGenerator = Array.isArray(list) - ? function() { + ? function () { return list; } : list; @@ -44,7 +44,7 @@ export class ListComponent extends SharedComponent { if (this.getDefaultTermMeta()) { const meta = this.getDefaultTermMeta(); - ret = _.map(ret, function(term) { + ret = _.map(ret, function (term) { if (_.isString(term)) { term = { name: term }; } @@ -62,7 +62,7 @@ export class ListComponent extends SharedComponent { // verify we have all tokens const list = this.listGenerator(); - const notFound = _.any(tokens, function(token) { + const notFound = _.any(tokens, function (token) { return list.indexOf(token) === -1; }); diff --git a/src/plugins/console/public/lib/autocomplete/components/object_component.js b/src/plugins/console/public/lib/autocomplete/components/object_component.js index f73625cccf38b..34cfb892a65d9 100644 --- a/src/plugins/console/public/lib/autocomplete/components/object_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/object_component.js @@ -32,10 +32,10 @@ export class ObjectComponent extends SharedComponent { } getTerms(context, editor) { const options = []; - _.each(this.constants, function(component) { + _.each(this.constants, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); - _.each(this.patternsAndWildCards, function(component) { + _.each(this.patternsAndWildCards, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); return options; @@ -45,7 +45,7 @@ export class ObjectComponent extends SharedComponent { const result = { next: [], }; - _.each(this.constants, function(component) { + _.each(this.constants, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); @@ -61,7 +61,7 @@ export class ObjectComponent extends SharedComponent { if (result.next.length) { return result; } - _.each(this.patternsAndWildCards, function(component) { + _.each(this.patternsAndWildCards, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); diff --git a/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js b/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js index 5921a910f4175..79a332624e5e1 100644 --- a/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js +++ b/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js @@ -43,7 +43,7 @@ export class UrlPatternMatcher { // We'll group endpoints by the methods which are attached to them, //to avoid suggesting endpoints that are incompatible with the //method that the user has entered. - ['HEAD', 'GET', 'PUT', 'POST', 'DELETE'].forEach(method => { + ['HEAD', 'GET', 'PUT', 'POST', 'DELETE'].forEach((method) => { this[method] = { rootComponent: new SharedComponent('ROOT'), parametrizedComponentFactories: parametrizedComponentFactories || { @@ -53,7 +53,7 @@ export class UrlPatternMatcher { }); } addEndpoint(pattern, endpoint) { - endpoint.methods.forEach(method => { + endpoint.methods.forEach((method) => { let c; let activeComponent = this[method].rootComponent; if (endpoint.template) { @@ -63,7 +63,7 @@ export class UrlPatternMatcher { const partList = pattern.split('/'); _.each( partList, - function(part, partIndex) { + function (part, partIndex) { if (part.search(/^{.+}$/) >= 0) { part = part.substr(1, part.length - 2); if (activeComponent.getComponent(part)) { @@ -133,7 +133,7 @@ export class UrlPatternMatcher { }); } - getTopLevelComponents = function(method) { + getTopLevelComponents = function (method) { const methodRoot = this[method]; if (!methodRoot) { return []; diff --git a/src/plugins/console/public/lib/autocomplete/engine.js b/src/plugins/console/public/lib/autocomplete/engine.js index ae943a74ffb3a..38be0d8a7e4c9 100644 --- a/src/plugins/console/public/lib/autocomplete/engine.js +++ b/src/plugins/console/public/lib/autocomplete/engine.js @@ -21,14 +21,14 @@ import _ from 'lodash'; export function wrapComponentWithDefaults(component, defaults) { const originalGetTerms = component.getTerms; - component.getTerms = function(context, editor) { + component.getTerms = function (context, editor) { let result = originalGetTerms.call(component, context, editor); if (!result) { return result; } result = _.map( result, - function(term) { + function (term) { if (!_.isObject(term)) { term = { name: term }; } @@ -41,7 +41,7 @@ export function wrapComponentWithDefaults(component, defaults) { return component; } -const tracer = function() { +const tracer = function () { if (window.engine_trace) { console.log.call(console, ...arguments); } @@ -77,9 +77,9 @@ export function walkTokenPath(tokenPath, walkingStates, context, editor) { tracer('starting token evaluation [' + token + ']'); - _.each(walkingStates, function(ws) { + _.each(walkingStates, function (ws) { const contextForState = passThroughContext(context, ws.contextExtensionList); - _.each(ws.components, function(component) { + _.each(ws.components, function (component) { tracer('evaluating [' + token + '] with [' + component.name + ']', component); const result = component.match(token, contextForState, editor); if (result && !_.isEmpty(result)) { @@ -117,7 +117,7 @@ export function walkTokenPath(tokenPath, walkingStates, context, editor) { if (nextWalkingStates.length === 0) { // no where to go, still return context variables returned so far.. - return _.map(walkingStates, function(ws) { + return _.map(walkingStates, function (ws) { return new WalkingState(ws.name, [], ws.contextExtensionList); }); } @@ -134,10 +134,10 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, ); if (includeAutoComplete) { let autoCompleteSet = []; - _.each(walkStates, function(ws) { + _.each(walkStates, function (ws) { const contextForState = passThroughContext(context, ws.contextExtensionList); - _.each(ws.components, function(component) { - _.each(component.getTerms(contextForState, editor), function(term) { + _.each(ws.components, function (component) { + _.each(component.getTerms(contextForState, editor), function (term) { if (!_.isObject(term)) { term = { name: term }; } @@ -152,10 +152,10 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, // apply what values were set so far to context, selecting the deepest on which sets the context if (walkStates.length !== 0) { let wsToUse; - walkStates = _.sortBy(walkStates, function(ws) { + walkStates = _.sortBy(walkStates, function (ws) { return _.isNumber(ws.priority) ? ws.priority : Number.MAX_VALUE; }); - wsToUse = _.find(walkStates, function(ws) { + wsToUse = _.find(walkStates, function (ws) { return _.isEmpty(ws.components); }); @@ -170,7 +170,7 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, wsToUse = walkStates[0]; } - _.each(wsToUse.contextExtensionList, function(extension) { + _.each(wsToUse.contextExtensionList, function (extension) { _.assign(context, extension); }); } diff --git a/src/plugins/console/public/lib/autocomplete/url_params.js b/src/plugins/console/public/lib/autocomplete/url_params.js index 0519a2daade87..a237fe5dd59d6 100644 --- a/src/plugins/console/public/lib/autocomplete/url_params.js +++ b/src/plugins/console/public/lib/autocomplete/url_params.js @@ -52,7 +52,7 @@ export class UrlParams { _.defaults(description, defaults); _.each( description, - function(pDescription, param) { + function (pDescription, param) { const component = new ParamComponent(param, this.rootComponent, pDescription); if (Array.isArray(pDescription)) { new ListComponent(param, pDescription, component); diff --git a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js index 6a8caebfc6874..068dd68be4ba8 100644 --- a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js +++ b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js @@ -23,13 +23,13 @@ import curlTests from './curl_parsing.txt'; describe('CURL', () => { const notCURLS = ['sldhfsljfhs', 's;kdjfsldkfj curl -XDELETE ""', '{ "hello": 1 }']; - _.each(notCURLS, function(notCURL, i) { - test('cURL Detection - broken strings ' + i, function() { + _.each(notCURLS, function (notCURL, i) { + test('cURL Detection - broken strings ' + i, function () { expect(detectCURL(notCURL)).toEqual(false); }); }); - curlTests.split(/^=+$/m).forEach(function(fixture) { + curlTests.split(/^=+$/m).forEach(function (fixture) { if (fixture.trim() === '') { return; } @@ -38,7 +38,7 @@ describe('CURL', () => { const curlText = fixture[1]; const response = fixture[2].trim(); - test('cURL Detection - ' + name, function() { + test('cURL Detection - ' + name, function () { expect(detectCURL(curlText)).toBe(true); const r = parseCURL(curlText); expect(r).toEqual(response); diff --git a/src/plugins/console/public/lib/kb/__tests__/kb.test.js b/src/plugins/console/public/lib/kb/__tests__/kb.test.js index c80f5671449b3..eaf5023053880 100644 --- a/src/plugins/console/public/lib/kb/__tests__/kb.test.js +++ b/src/plugins/console/public/lib/kb/__tests__/kb.test.js @@ -58,7 +58,7 @@ describe('Knowledge base', () => { function testUrlContext(tokenPath, otherTokenValues, expectedContext) { if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -111,7 +111,7 @@ describe('Knowledge base', () => { } function indexTest(name, tokenPath, otherTokenValues, expectedContext) { - test(name, function() { + test(name, function () { // eslint-disable-next-line new-cap const testApi = new kb._test.loadApisFromJson( { @@ -161,7 +161,7 @@ describe('Knowledge base', () => { }); function typeTest(name, tokenPath, otherTokenValues, expectedContext) { - test(name, function() { + test(name, function () { const testApi = kb._test.loadApisFromJson( { typeTest: { diff --git a/src/plugins/console/public/lib/kb/api.js b/src/plugins/console/public/lib/kb/api.js index c418a7cb414ef..aafb234b0f446 100644 --- a/src/plugins/console/public/lib/kb/api.js +++ b/src/plugins/console/public/lib/kb/api.js @@ -41,8 +41,8 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori this.name = ''; } -(function(cls) { - cls.addGlobalAutocompleteRules = function(parentNode, rules) { +(function (cls) { + cls.addGlobalAutocompleteRules = function (parentNode, rules) { this.globalRules[parentNode] = compileBodyDescription( 'GLOBAL.' + parentNode, rules, @@ -50,7 +50,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori ); }; - cls.getGlobalAutocompleteComponents = function(term, throwOnMissing) { + cls.getGlobalAutocompleteComponents = function (term, throwOnMissing) { const result = this.globalRules[term]; if (_.isUndefined(result) && (throwOnMissing || _.isUndefined(throwOnMissing))) { throw new Error("failed to resolve global components for ['" + term + "']"); @@ -58,7 +58,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori return result; }; - cls.addEndpointDescription = function(endpoint, description) { + cls.addEndpointDescription = function (endpoint, description) { const copiedDescription = {}; _.extend(copiedDescription, description || {}); _.defaults(copiedDescription, { @@ -68,7 +68,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori }); _.each( copiedDescription.patterns, - function(p) { + function (p) { this.urlPatternMatcher.addEndpoint(p, copiedDescription); }, this @@ -84,19 +84,19 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori this.endpoints[endpoint] = copiedDescription; }; - cls.getEndpointDescriptionByEndpoint = function(endpoint) { + cls.getEndpointDescriptionByEndpoint = function (endpoint) { return this.endpoints[endpoint]; }; - cls.getTopLevelUrlCompleteComponents = function(method) { + cls.getTopLevelUrlCompleteComponents = function (method) { return this.urlPatternMatcher.getTopLevelComponents(method); }; - cls.getUnmatchedEndpointComponents = function() { + cls.getUnmatchedEndpointComponents = function () { return globalsOnlyAutocompleteComponents(); }; - cls.clear = function() { + cls.clear = function () { this.endpoints = {}; this.globalRules = {}; }; diff --git a/src/plugins/console/public/lib/kb/kb.js b/src/plugins/console/public/lib/kb/kb.js index 0d0f42319d0d8..e0bf1ef09c4d3 100644 --- a/src/plugins/console/public/lib/kb/kb.js +++ b/src/plugins/console/public/lib/kb/kb.js @@ -32,68 +32,68 @@ import _ from 'lodash'; import Api from './api'; let ACTIVE_API = new Api(); -const isNotAnIndexName = name => name[0] === '_' && name !== '_all'; +const isNotAnIndexName = (name) => name[0] === '_' && name !== '_all'; const idAutocompleteComponentFactory = (name, parent) => { return new IdAutocompleteComponent(name, parent); }; const parametrizedComponentFactories = { - getComponent: function(name, parent, provideDefault) { + getComponent: function (name, parent, provideDefault) { if (this[name]) { return this[name]; } else if (provideDefault) { return idAutocompleteComponentFactory; } }, - index: function(name, parent) { + index: function (name, parent) { if (isNotAnIndexName(name)) return; return new IndexAutocompleteComponent(name, parent, false); }, - indices: function(name, parent) { + indices: function (name, parent) { if (isNotAnIndexName(name)) return; return new IndexAutocompleteComponent(name, parent, true); }, - type: function(name, parent) { + type: function (name, parent) { return new TypeAutocompleteComponent(name, parent, false); }, - types: function(name, parent) { + types: function (name, parent) { return new TypeAutocompleteComponent(name, parent, true); }, - id: function(name, parent) { + id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - transform_id: function(name, parent) { + transform_id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - username: function(name, parent) { + username: function (name, parent) { return new UsernameAutocompleteComponent(name, parent); }, - user: function(name, parent) { + user: function (name, parent) { return new UsernameAutocompleteComponent(name, parent); }, - template: function(name, parent) { + template: function (name, parent) { return new TemplateAutocompleteComponent(name, parent); }, - task_id: function(name, parent) { + task_id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - ids: function(name, parent) { + ids: function (name, parent) { return idAutocompleteComponentFactory(name, parent, true); }, - fields: function(name, parent) { + fields: function (name, parent) { return new FieldAutocompleteComponent(name, parent, true); }, - field: function(name, parent) { + field: function (name, parent) { return new FieldAutocompleteComponent(name, parent, false); }, - nodes: function(name, parent) { + nodes: function (name, parent) { return new ListComponent( name, ['_local', '_master', 'data:true', 'data:false', 'master:true', 'master:false'], parent ); }, - node: function(name, parent) { + node: function (name, parent) { return new ListComponent(name, [], parent, false); }, }; @@ -133,12 +133,12 @@ function loadApisFromJson( bodyParametrizedComponentFactories || urlParametrizedComponentFactories; const api = new Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactories); const names = []; - _.each(json, function(apiJson, name) { + _.each(json, function (apiJson, name) { names.unshift(name); - _.each(apiJson.globals || {}, function(globalJson, globalName) { + _.each(apiJson.globals || {}, function (globalJson, globalName) { api.addGlobalAutocompleteRules(globalName, globalJson); }); - _.each(apiJson.endpoints || {}, function(endpointJson, endpointName) { + _.each(apiJson.endpoints || {}, function (endpointJson, endpointName) { api.addEndpointDescription(endpointName, endpointJson); }); }); @@ -159,10 +159,10 @@ export function setActiveApi(api) { 'kbn-xsrf': 'kibana', }, }).then( - function(data) { + function (data) { setActiveApi(loadApisFromJson(data)); }, - function(jqXHR) { + function (jqXHR) { console.log("failed to load API '" + api + "': " + jqXHR.responseText); } ); diff --git a/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts b/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts index 8eac345898f9a..a6b47559a4ef5 100644 --- a/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts +++ b/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts @@ -40,7 +40,7 @@ export class LocalObjectStorage implements ObjectStorage } async findAll(): Promise { - const allLocalKeys = this.client.keys().filter(key => { + const allLocalKeys = this.client.keys().filter((key) => { return key.includes(this.prefix); }); diff --git a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js index 292b1b4fb1bf5..ce52b060f418f 100644 --- a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js +++ b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js @@ -41,7 +41,7 @@ describe('Mappings', () => { return { name: name, type: type || 'string' }; } - test('Multi fields 1.0 style', function() { + test('Multi fields 1.0 style', function () { mappings.loadMappings({ index: { properties: { @@ -72,7 +72,7 @@ describe('Mappings', () => { ]); }); - test('Simple fields', function() { + test('Simple fields', function () { mappings.loadMappings({ index: { properties: { @@ -89,7 +89,7 @@ describe('Mappings', () => { expect(mappings.getFields('index').sort(fc)).toEqual([f('number', 'int'), f('str', 'string')]); }); - test('Simple fields - 1.0 style', function() { + test('Simple fields - 1.0 style', function () { mappings.loadMappings({ index: { mappings: { @@ -108,7 +108,7 @@ describe('Mappings', () => { expect(mappings.getFields('index').sort(fc)).toEqual([f('number', 'int'), f('str', 'string')]); }); - test('Nested fields', function() { + test('Nested fields', function () { mappings.loadMappings({ index: { properties: { @@ -137,7 +137,7 @@ describe('Mappings', () => { ]); }); - test('Enabled fields', function() { + test('Enabled fields', function () { mappings.loadMappings({ index: { properties: { @@ -159,7 +159,7 @@ describe('Mappings', () => { expect(mappings.getFields('index', []).sort(fc)).toEqual([f('message'), f('person.sid')]); }); - test('Path tests', function() { + test('Path tests', function () { mappings.loadMappings({ index: { properties: { @@ -191,7 +191,7 @@ describe('Mappings', () => { ]); }); - test('Use index_name tests', function() { + test('Use index_name tests', function () { mappings.loadMappings({ index: { properties: { @@ -203,7 +203,7 @@ describe('Mappings', () => { expect(mappings.getFields().sort(fc)).toEqual([f('i_last_1')]); }); - test('Aliases', function() { + test('Aliases', function () { mappings.loadAliases({ test_index1: { aliases: { diff --git a/src/plugins/console/public/lib/mappings/mappings.js b/src/plugins/console/public/lib/mappings/mappings.js index b5bcc2b105996..22aae8da030d4 100644 --- a/src/plugins/console/public/lib/mappings/mappings.js +++ b/src/plugins/console/public/lib/mappings/mappings.js @@ -43,7 +43,7 @@ export function expandAliases(indicesOrAliases) { if (typeof indicesOrAliases === 'string') { indicesOrAliases = [indicesOrAliases]; } - indicesOrAliases = $.map(indicesOrAliases, function(iOrA) { + indicesOrAliases = $.map(indicesOrAliases, function (iOrA) { if (perAliasIndexes[iOrA]) { return perAliasIndexes[iOrA]; } @@ -52,7 +52,7 @@ export function expandAliases(indicesOrAliases) { let ret = [].concat.apply([], indicesOrAliases); ret.sort(); let last; - ret = $.map(ret, function(v) { + ret = $.map(ret, function (v) { const r = last === v ? null : v; last = v; return r; @@ -80,7 +80,7 @@ export function getFields(indices, types) { ret = f ? f : []; } else { // filter what we need - $.each(typeDict, function(type, fields) { + $.each(typeDict, function (type, fields) { if (!types || types.length === 0 || $.inArray(type, types) !== -1) { ret.push(fields); } @@ -90,7 +90,7 @@ export function getFields(indices, types) { } } else { // multi index mode. - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { if (!indices || indices.length === 0 || $.inArray(index, indices) !== -1) { ret.push(getFields(index, types)); } @@ -98,7 +98,7 @@ export function getFields(indices, types) { ret = [].concat.apply([], ret); } - return _.uniq(ret, function(f) { + return _.uniq(ret, function (f) { return f.name + ':' + f.type; }); } @@ -113,12 +113,12 @@ export function getTypes(indices) { } // filter what we need - $.each(typeDict, function(type) { + $.each(typeDict, function (type) { ret.push(type); }); } else { // multi index mode. - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { if (!indices || $.inArray(index, indices) !== -1) { ret.push(getTypes(index)); } @@ -131,11 +131,11 @@ export function getTypes(indices) { export function getIndices(includeAliases) { const ret = []; - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { ret.push(index); }); if (typeof includeAliases === 'undefined' ? true : includeAliases) { - $.each(perAliasIndexes, function(alias) { + $.each(perAliasIndexes, function (alias) { ret.push(alias); }); } @@ -151,7 +151,7 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { function applyPathSettings(nestedFieldNames) { const pathType = fieldMapping.path || 'full'; if (pathType === 'full') { - return $.map(nestedFieldNames, function(f) { + return $.map(nestedFieldNames, function (f) { f.name = fieldName + '.' + f.name; return f; }); @@ -174,7 +174,7 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { } if (fieldMapping.fields) { - nestedFields = $.map(fieldMapping.fields, function(fieldMapping, fieldName) { + nestedFields = $.map(fieldMapping.fields, function (fieldMapping, fieldName) { return getFieldNamesFromFieldMapping(fieldName, fieldMapping); }); nestedFields = applyPathSettings(nestedFields); @@ -186,12 +186,12 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { } function getFieldNamesFromProperties(properties = {}) { - const fieldList = $.map(properties, function(fieldMapping, fieldName) { + const fieldList = $.map(properties, function (fieldMapping, fieldName) { return getFieldNamesFromFieldMapping(fieldName, fieldMapping); }); // deduping - return _.uniq(fieldList, function(f) { + return _.uniq(fieldList, function (f) { return f.name + ':' + f.type; }); } @@ -203,7 +203,7 @@ function loadTemplates(templatesObject = {}) { export function loadMappings(mappings) { perIndexTypes = {}; - $.each(mappings, function(index, indexMapping) { + $.each(mappings, function (index, indexMapping) { const normalizedIndexMappings = {}; // Migrate 1.0.0 mappings. This format has changed, so we need to extract the underlying mapping. @@ -211,7 +211,7 @@ export function loadMappings(mappings) { indexMapping = indexMapping.mappings; } - $.each(indexMapping, function(typeName, typeMapping) { + $.each(indexMapping, function (typeName, typeMapping) { if (typeName === 'properties') { const fieldList = getFieldNamesFromProperties(typeMapping); normalizedIndexMappings[typeName] = fieldList; @@ -226,11 +226,11 @@ export function loadMappings(mappings) { export function loadAliases(aliases) { perAliasIndexes = {}; - $.each(aliases || {}, function(index, omdexAliases) { + $.each(aliases || {}, function (index, omdexAliases) { // verify we have an index defined. useful when mapping loading is disabled perIndexTypes[index] = perIndexTypes[index] || {}; - $.each(omdexAliases.aliases || {}, function(alias) { + $.each(omdexAliases.aliases || {}, function (alias) { if (alias === index) { return; } // alias which is identical to index means no index. diff --git a/src/plugins/console/public/lib/token_iterator/token_iterator.ts b/src/plugins/console/public/lib/token_iterator/token_iterator.ts index 643938536b306..5939741bc96e6 100644 --- a/src/plugins/console/public/lib/token_iterator/token_iterator.ts +++ b/src/plugins/console/public/lib/token_iterator/token_iterator.ts @@ -33,7 +33,7 @@ export class TokenIterator { constructor(private readonly provider: TokensProvider, startPosition: Position) { this.tokensLineCache = this.provider.getTokens(startPosition.lineNumber) || []; - const tokenIdx = this.tokensLineCache.findIndex(token => + const tokenIdx = this.tokensLineCache.findIndex((token) => isColumnInTokenRange(startPosition.column, token) ); if (tokenIdx > -1) { diff --git a/src/plugins/console/public/lib/utils/__tests__/utils.test.js b/src/plugins/console/public/lib/utils/__tests__/utils.test.js index 3a2e6a54c1328..e47e71c742a81 100644 --- a/src/plugins/console/public/lib/utils/__tests__/utils.test.js +++ b/src/plugins/console/public/lib/utils/__tests__/utils.test.js @@ -20,7 +20,7 @@ import * as utils from '../'; describe('Utils class', () => { - test('extract deprecation messages', function() { + test('extract deprecation messages', function () { expect( utils.extractDeprecationMessages( '299 Elasticsearch-6.0.0-alpha1-SNAPSHOT-abcdef1 "this is a warning" "Mon, 27 Feb 2017 14:52:14 GMT"' @@ -70,7 +70,7 @@ describe('Utils class', () => { ]); }); - test('unescape', function() { + test('unescape', function () { expect(utils.unescape('escaped backslash \\\\')).toEqual('escaped backslash \\'); expect(utils.unescape('a pair of \\"escaped quotes\\"')).toEqual('a pair of "escaped quotes"'); expect(utils.unescape('escaped quotes do not have to come in pairs: \\"')).toEqual( @@ -78,7 +78,7 @@ describe('Utils class', () => { ); }); - test('split on unquoted comma followed by space', function() { + test('split on unquoted comma followed by space', function () { expect(utils.splitOnUnquotedCommaSpace('a, b')).toEqual(['a', 'b']); expect(utils.splitOnUnquotedCommaSpace('a,b, c')).toEqual(['a,b', 'c']); expect(utils.splitOnUnquotedCommaSpace('"a, b"')).toEqual(['"a, b"']); diff --git a/src/plugins/console/public/lib/utils/index.ts b/src/plugins/console/public/lib/utils/index.ts index 0ebea0f9d4055..917988e0e811b 100644 --- a/src/plugins/console/public/lib/utils/index.ts +++ b/src/plugins/console/public/lib/utils/index.ts @@ -61,7 +61,7 @@ export function extractDeprecationMessages(warnings: string) { // pattern for valid warning header const re = /\d{3} [0-9a-zA-Z!#$%&'*+-.^_`|~]+ \"((?:\t| |!|[\x23-\x5b]|[\x5d-\x7e]|[\x80-\xff]|\\\\|\\")*)\"(?: \"[^"]*\")?/; // split on any comma that is followed by an even number of quotes - return _.map(splitOnUnquotedCommaSpace(warnings), warning => { + return _.map(splitOnUnquotedCommaSpace(warnings), (warning) => { const match = re.exec(warning); // extract the actual warning if there was a match return '#! Deprecation: ' + (match !== null ? unescape(match[1]) : warning); diff --git a/src/plugins/console/public/services/history.ts b/src/plugins/console/public/services/history.ts index 04dae0beacefe..440014b362c7a 100644 --- a/src/plugins/console/public/services/history.ts +++ b/src/plugins/console/public/services/history.ts @@ -34,7 +34,7 @@ export class History { } getHistory() { - return this.getHistoryKeys().map(key => this.storage.get(key)); + return this.getHistoryKeys().map((key) => this.storage.get(key)); } // This is used as an optimization mechanism so that different components @@ -50,7 +50,7 @@ export class History { addToHistory(endpoint: string, method: string, data: any) { const keys = this.getHistoryKeys(); keys.splice(0, 500); // only maintain most recent X; - keys.forEach(key => { + keys.forEach((key) => { this.storage.delete(key); }); @@ -89,7 +89,7 @@ export class History { } clearHistory() { - this.getHistoryKeys().forEach(key => this.storage.delete(key)); + this.getHistoryKeys().forEach((key) => this.storage.delete(key)); } } diff --git a/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js b/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js index df8b49b0a089e..fcf385165a591 100644 --- a/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js +++ b/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js @@ -31,9 +31,9 @@ const getDefaultElasticsearchConfig = () => { }; }; -describe('plugins/console', function() { - describe('#getElasticsearchProxyConfig', function() { - it('sets timeout', function() { +describe('plugins/console', function () { + describe('#getElasticsearchProxyConfig', function () { + it('sets timeout', function () { const value = 1000; const proxyConfig = getElasticsearchProxyConfig({ ...getDefaultElasticsearchConfig(), @@ -42,7 +42,7 @@ describe('plugins/console', function() { expect(proxyConfig.timeout).to.be(value); }); - it(`uses https.Agent when url's protocol is https`, function() { + it(`uses https.Agent when url's protocol is https`, function () { const { agent } = getElasticsearchProxyConfig({ ...getDefaultElasticsearchConfig(), hosts: ['https://localhost:9200'], @@ -50,21 +50,21 @@ describe('plugins/console', function() { expect(agent).to.be.a(https.Agent); }); - it(`uses http.Agent when url's protocol is http`, function() { + it(`uses http.Agent when url's protocol is http`, function () { const { agent } = getElasticsearchProxyConfig(getDefaultElasticsearchConfig()); expect(agent).to.be.a(http.Agent); }); - describe('ssl', function() { + describe('ssl', function () { let config; - beforeEach(function() { + beforeEach(function () { config = { ...getDefaultElasticsearchConfig(), hosts: ['https://localhost:9200'], }; }); - it('sets rejectUnauthorized to false when verificationMode is none', function() { + it('sets rejectUnauthorized to false when verificationMode is none', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'none' }, @@ -72,7 +72,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(false); }); - it('sets rejectUnauthorized to true when verificationMode is certificate', function() { + it('sets rejectUnauthorized to true when verificationMode is certificate', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'certificate' }, @@ -80,7 +80,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(true); }); - it('sets checkServerIdentity to not check hostname when verificationMode is certificate', function() { + it('sets checkServerIdentity to not check hostname when verificationMode is certificate', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'certificate' }, @@ -99,7 +99,7 @@ describe('plugins/console', function() { expect(result).to.be(undefined); }); - it('sets rejectUnauthorized to true when verificationMode is full', function() { + it('sets rejectUnauthorized to true when verificationMode is full', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'full' }, @@ -108,7 +108,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(true); }); - it(`doesn't set checkServerIdentity when verificationMode is full`, function() { + it(`doesn't set checkServerIdentity when verificationMode is full`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'full' }, @@ -117,7 +117,7 @@ describe('plugins/console', function() { expect(agent.options.checkServerIdentity).to.be(undefined); }); - it(`sets ca when certificateAuthorities are specified`, function() { + it(`sets ca when certificateAuthorities are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, certificateAuthorities: ['content-of-some-path'] }, @@ -127,7 +127,7 @@ describe('plugins/console', function() { }); describe('when alwaysPresentCertificate is false', () => { - it(`doesn't set cert and key when certificate and key paths are specified`, function() { + it(`doesn't set cert and key when certificate and key paths are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -142,7 +142,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be(undefined); }); - it(`doesn't set passphrase when certificate, key and keyPassphrase are specified`, function() { + it(`doesn't set passphrase when certificate, key and keyPassphrase are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -159,7 +159,7 @@ describe('plugins/console', function() { }); describe('when alwaysPresentCertificate is true', () => { - it(`sets cert and key when certificate and key are specified`, async function() { + it(`sets cert and key when certificate and key are specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -174,7 +174,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be('content-of-another-path'); }); - it(`sets passphrase when certificate, key and keyPassphrase are specified`, function() { + it(`sets passphrase when certificate, key and keyPassphrase are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -189,7 +189,7 @@ describe('plugins/console', function() { expect(agent.options.passphrase).to.be('secret'); }); - it(`doesn't set cert when only certificate path is specified`, async function() { + it(`doesn't set cert when only certificate path is specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -204,7 +204,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be(undefined); }); - it(`doesn't set key when only key path is specified`, async function() { + it(`doesn't set key when only key path is specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { diff --git a/src/plugins/console/server/__tests__/proxy_config.js b/src/plugins/console/server/__tests__/proxy_config.js index b0b85e6bb7d06..1f3a94c4fe20f 100644 --- a/src/plugins/console/server/__tests__/proxy_config.js +++ b/src/plugins/console/server/__tests__/proxy_config.js @@ -34,17 +34,17 @@ const matchGoogle = { const parsedGoogle = parseUrl('https://google.com/search'); const parsedLocalEs = parseUrl('https://localhost:5601/search'); -describe('ProxyConfig', function() { - describe('constructor', function() { - beforeEach(function() { +describe('ProxyConfig', function () { + describe('constructor', function () { + beforeEach(function () { sinon.stub(https, 'Agent'); }); - afterEach(function() { + afterEach(function () { https.Agent.restore(); }); - it('uses ca to create sslAgent', function() { + it('uses ca to create sslAgent', function () { const config = new ProxyConfig({ ssl: { ca: ['content-of-some-path'], @@ -62,7 +62,7 @@ describe('ProxyConfig', function() { }); }); - it('uses cert, and key to create sslAgent', function() { + it('uses cert, and key to create sslAgent', function () { const config = new ProxyConfig({ ssl: { cert: 'content-of-some-path', @@ -81,7 +81,7 @@ describe('ProxyConfig', function() { }); }); - it('uses ca, cert, and key to create sslAgent', function() { + it('uses ca, cert, and key to create sslAgent', function () { const config = new ProxyConfig({ ssl: { ca: ['content-of-some-path'], @@ -103,9 +103,9 @@ describe('ProxyConfig', function() { }); }); - describe('#getForParsedUri', function() { - describe('parsed url does not match', function() { - it('returns {}', function() { + describe('#getForParsedUri', function () { + describe('parsed url does not match', function () { + it('returns {}', function () { const config = new ProxyConfig({ match: matchGoogle, timeout: 100, @@ -115,8 +115,8 @@ describe('ProxyConfig', function() { }); }); - describe('parsed url does match', function() { - it('assigns timeout value', function() { + describe('parsed url does match', function () { + it('assigns timeout value', function () { const football = {}; const config = new ProxyConfig({ match: matchGoogle, @@ -126,7 +126,7 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri(parsedGoogle).timeout).to.be(football); }); - it('assigns ssl.verify to rejectUnauthorized', function() { + it('assigns ssl.verify to rejectUnauthorized', function () { const football = {}; const config = new ProxyConfig({ match: matchGoogle, @@ -138,9 +138,9 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri(parsedGoogle).rejectUnauthorized).to.be(football); }); - describe('uri us http', function() { - describe('ca is set', function() { - it('creates but does not output the agent', function() { + describe('uri us http', function () { + describe('ca is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { ca: ['path/to/ca'], @@ -151,8 +151,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('cert is set', function() { - it('creates but does not output the agent', function() { + describe('cert is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -163,8 +163,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('key is set', function() { - it('creates but does not output the agent', function() { + describe('key is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { key: 'path/to/key', @@ -175,8 +175,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('cert + key are set', function() { - it('creates but does not output the agent', function() { + describe('cert + key are set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -190,9 +190,9 @@ describe('ProxyConfig', function() { }); }); - describe('uri us https', function() { - describe('ca is set', function() { - it('creates and outputs the agent', function() { + describe('uri us https', function () { + describe('ca is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { ca: ['path/to/ca'], @@ -203,8 +203,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('cert is set', function() { - it('creates and outputs the agent', function() { + describe('cert is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -215,8 +215,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('key is set', function() { - it('creates and outputs the agent', function() { + describe('key is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { key: 'path/to/key', @@ -227,8 +227,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('cert + key are set', function() { - it('creates and outputs the agent', function() { + describe('cert + key are set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', diff --git a/src/plugins/console/server/__tests__/proxy_config_collection.js b/src/plugins/console/server/__tests__/proxy_config_collection.js index e1bc099ac1e85..729972399f0bb 100644 --- a/src/plugins/console/server/__tests__/proxy_config_collection.js +++ b/src/plugins/console/server/__tests__/proxy_config_collection.js @@ -26,12 +26,12 @@ import { Agent as HttpsAgent } from 'https'; import { ProxyConfigCollection } from '../lib/proxy_config_collection'; -describe('ProxyConfigCollection', function() { - beforeEach(function() { +describe('ProxyConfigCollection', function () { + beforeEach(function () { sinon.stub(fs, 'readFileSync').callsFake(() => Buffer.alloc(0)); }); - afterEach(function() { + afterEach(function () { fs.readFileSync.restore(); }); @@ -86,67 +86,67 @@ describe('ProxyConfigCollection', function() { return collection.configForUri(uri).timeout; } - describe('http://localhost:5601', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5601', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5601')).to.be(3); }); }); - describe('https://localhost:5601/.kibana', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/.kibana', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/.kibana')).to.be(1); }); }); - describe('http://localhost:5602', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5602', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5602')).to.be(4); }); }); - describe('https://localhost:5602', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5602', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5602')).to.be(4); }); }); - describe('http://localhost:5603', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5603', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5603')).to.be(4); }); }); - describe('https://localhost:5603', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5603', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5603')).to.be(4); }); }); - describe('https://localhost:5601/index', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/index', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/index')).to.be(2); }); }); - describe('http://localhost:5601/index', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5601/index', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5601/index')).to.be(3); }); }); - describe('https://localhost:5601/index/type', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/index/type', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/index/type')).to.be(2); }); }); - describe('http://notlocalhost', function() { - it('defaults to the first matching timeout', function() { + describe('http://notlocalhost', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://notlocalhost')).to.be(5); }); }); - describe('collection with ssl config and root level verify:false', function() { + describe('collection with ssl config and root level verify:false', function () { function makeCollection() { return new ProxyConfigCollection([ { @@ -160,13 +160,13 @@ describe('ProxyConfigCollection', function() { ]); } - it('verifies for config that produces ssl agent', function() { + it('verifies for config that produces ssl agent', function () { const conf = makeCollection().configForUri('https://es.internal.org/_search'); expect(conf.agent.options).to.have.property('rejectUnauthorized', true); expect(conf.agent).to.be.an(HttpsAgent); }); - it('disabled verification for * config', function() { + it('disabled verification for * config', function () { const conf = makeCollection().configForUri('https://extenal.org/_search'); expect(conf).to.have.property('rejectUnauthorized', false); expect(conf.agent).to.be(undefined); diff --git a/src/plugins/console/server/__tests__/proxy_route/body.test.ts b/src/plugins/console/server/__tests__/proxy_route/body.test.ts index 252009a8977f3..526c2e4c78ea4 100644 --- a/src/plugins/console/server/__tests__/proxy_route/body.test.ts +++ b/src/plugins/console/server/__tests__/proxy_route/body.test.ts @@ -46,9 +46,9 @@ describe('Console Proxy Route', () => { }); const readStream = (s: Readable) => - new Promise(resolve => { + new Promise((resolve) => { let v = ''; - s.on('data', data => { + s.on('data', (data) => { v += data; }); s.on('end', () => resolve(v)); diff --git a/src/plugins/console/server/__tests__/set_headers.js b/src/plugins/console/server/__tests__/set_headers.js index 1f349cbbb571e..3ddd30777bb5b 100644 --- a/src/plugins/console/server/__tests__/set_headers.js +++ b/src/plugins/console/server/__tests__/set_headers.js @@ -20,18 +20,18 @@ import expect from '@kbn/expect'; import { setHeaders } from '../lib'; -describe('#set_headers', function() { - it('throws if not given an object as the first argument', function() { +describe('#set_headers', function () { + it('throws if not given an object as the first argument', function () { const fn = () => setHeaders(null, {}); expect(fn).to.throwError(); }); - it('throws if not given an object as the second argument', function() { + it('throws if not given an object as the second argument', function () { const fn = () => setHeaders({}, null); expect(fn).to.throwError(); }); - it('returns a new object', function() { + it('returns a new object', function () { const originalHeaders = {}; const newHeaders = {}; const returnedHeaders = setHeaders(originalHeaders, newHeaders); @@ -39,14 +39,14 @@ describe('#set_headers', function() { expect(returnedHeaders).not.to.be(newHeaders); }); - it('returns object with newHeaders merged with originalHeaders', function() { + it('returns object with newHeaders merged with originalHeaders', function () { const originalHeaders = { foo: 'bar' }; const newHeaders = { one: 'two' }; const returnedHeaders = setHeaders(originalHeaders, newHeaders); expect(returnedHeaders).to.eql({ foo: 'bar', one: 'two' }); }); - it('returns object where newHeaders takes precedence for any matching keys', function() { + it('returns object where newHeaders takes precedence for any matching keys', function () { const originalHeaders = { foo: 'bar' }; const newHeaders = { one: 'two', foo: 'notbar' }; const returnedHeaders = setHeaders(originalHeaders, newHeaders); diff --git a/src/plugins/console/server/__tests__/wildcard_matcher.js b/src/plugins/console/server/__tests__/wildcard_matcher.js index ccf68f3c16ca3..3e0e06efad50f 100644 --- a/src/plugins/console/server/__tests__/wildcard_matcher.js +++ b/src/plugins/console/server/__tests__/wildcard_matcher.js @@ -32,8 +32,8 @@ function shouldNot(candidate, ...constructorArgs) { } } -describe('WildcardMatcher', function() { - describe('pattern = *', function() { +describe('WildcardMatcher', function () { + describe('pattern = *', function () { it('matches http', () => should('http', '*')); it('matches https', () => should('https', '*')); it('matches nothing', () => should('', '*')); @@ -41,12 +41,12 @@ describe('WildcardMatcher', function() { it('matches localhost', () => should('localhost', '*')); it('matches a path', () => should('/index/_search', '*')); - describe('defaultValue = /', function() { + describe('defaultValue = /', function () { it('matches /', () => should('/', '*', '/')); }); }); - describe('pattern = http', function() { + describe('pattern = http', function () { it('matches http', () => should('http', 'http')); it('does not match https', () => shouldNot('https', 'http')); it('does not match nothing', () => shouldNot('', 'http')); @@ -54,7 +54,7 @@ describe('WildcardMatcher', function() { it('does not match a path', () => shouldNot('/index/_search', 'http')); }); - describe('pattern = 560{1..9}', function() { + describe('pattern = 560{1..9}', function () { it('does not match http', () => shouldNot('http', '560{1..9}')); it('does not matches 5600', () => shouldNot('5600', '560{1..9}')); it('matches 5601', () => should('5601', '560{1..9}')); diff --git a/src/plugins/console/server/lib/proxy_config_collection.ts b/src/plugins/console/server/lib/proxy_config_collection.ts index 5d0b02fed5b18..36f4f8359c5fe 100644 --- a/src/plugins/console/server/lib/proxy_config_collection.ts +++ b/src/plugins/console/server/lib/proxy_config_collection.ts @@ -26,7 +26,7 @@ export class ProxyConfigCollection { private configs: ProxyConfig[]; constructor(configs: Array<{ match: any; timeout: number }> = []) { - this.configs = configs.map(settings => new ProxyConfig(settings)); + this.configs = configs.map((settings) => new ProxyConfig(settings)); } hasConfig() { @@ -35,7 +35,7 @@ export class ProxyConfigCollection { configForUri(uri: string): object { const parsedUri = parseUrl(uri); - const settings = this.configs.map(config => config.getForParsedUri(parsedUri as any)); + const settings = this.configs.map((config) => config.getForParsedUri(parsedUri as any)); return defaultsDeep({}, ...settings); } } diff --git a/src/plugins/console/server/lib/proxy_request.ts b/src/plugins/console/server/lib/proxy_request.ts index cc957551e47a7..4c6c7c21f32a4 100644 --- a/src/plugins/console/server/lib/proxy_request.ts +++ b/src/plugins/console/server/lib/proxy_request.ts @@ -58,7 +58,7 @@ export const proxyRequest = ({ }); const finalUserHeaders = { ...headers }; - const hasHostHeader = Object.keys(finalUserHeaders).some(key => key.toLowerCase() === 'host'); + const hasHostHeader = Object.keys(finalUserHeaders).some((key) => key.toLowerCase() === 'host'); if (!hasHostHeader) { finalUserHeaders.host = hostname; } @@ -79,7 +79,7 @@ export const proxyRequest = ({ agent, }); - req.once('response', res => { + req.once('response', (res) => { resolved = true; resolve(res); }); diff --git a/src/plugins/console/server/lib/spec_definitions/js/mappings.ts b/src/plugins/console/server/lib/spec_definitions/js/mappings.ts index 8491bc17a2ff6..fbc9a822e509c 100644 --- a/src/plugins/console/server/lib/spec_definitions/js/mappings.ts +++ b/src/plugins/console/server/lib/spec_definitions/js/mappings.ts @@ -177,7 +177,7 @@ export const mappings = (specService: SpecDefinitionsService) => { 'week_date_time', 'week_date_time_no_millis', ], - function(s) { + function (s) { return ['basic_' + s, 'strict_' + s]; } ), diff --git a/src/plugins/console/server/plugin.ts b/src/plugins/console/server/plugin.ts index 85b728ea83891..eedd1541e8898 100644 --- a/src/plugins/console/server/plugin.ts +++ b/src/plugins/console/server/plugin.ts @@ -45,10 +45,7 @@ export class ConsoleServerPlugin implements Plugin { }, })); - const config = await this.ctx.config - .create() - .pipe(first()) - .toPromise(); + const config = await this.ctx.config.create().pipe(first()).toPromise(); const { elasticsearch } = await this.ctx.config.legacy.globalConfig$.pipe(first()).toPromise(); diff --git a/src/plugins/console/server/routes/api/console/proxy/create_handler.ts b/src/plugins/console/server/routes/api/console/proxy/create_handler.ts index 9446289ff03ea..272f63322ffaa 100644 --- a/src/plugins/console/server/routes/api/console/proxy/create_handler.ts +++ b/src/plugins/console/server/routes/api/console/proxy/create_handler.ts @@ -57,7 +57,7 @@ function toURL(base: string, path: string) { } function filterHeaders(originalHeaders: object, headersToKeep: string[]): object { - const normalizeHeader = function(header: any) { + const normalizeHeader = function (header: any) { if (!header) { return ''; } @@ -131,7 +131,7 @@ export const createHandler = ({ const { body, query } = request; const { path, method } = query; - if (!pathFilters.some(re => re.test(path))) { + if (!pathFilters.some((re) => re.test(path))) { return response.forbidden({ body: `Error connecting to '${path}':\n\nUnable to send requests to that path.`, headers: { diff --git a/src/plugins/console/server/routes/api/console/proxy/validation_config.ts b/src/plugins/console/server/routes/api/console/proxy/validation_config.ts index f2372e9ee80d0..c46fc5c808a42 100644 --- a/src/plugins/console/server/routes/api/console/proxy/validation_config.ts +++ b/src/plugins/console/server/routes/api/console/proxy/validation_config.ts @@ -22,9 +22,9 @@ export type Query = TypeOf; export type Body = TypeOf; const acceptedHttpVerb = schema.string({ - validate: method => { + validate: (method) => { return ['HEAD', 'GET', 'POST', 'PUT', 'DELETE'].some( - verb => verb.toLowerCase() === method.toLowerCase() + (verb) => verb.toLowerCase() === method.toLowerCase() ) ? undefined : `Method must be one of, case insensitive ['HEAD', 'GET', 'POST', 'PUT', 'DELETE']. Received '${method}'.`; @@ -32,7 +32,7 @@ const acceptedHttpVerb = schema.string({ }); const nonEmptyString = schema.string({ - validate: s => (s === '' ? 'Expected non-empty string' : undefined), + validate: (s) => (s === '' ? 'Expected non-empty string' : undefined), }); export const routeValidationConfig = { diff --git a/src/plugins/console/server/services/spec_definitions_service.ts b/src/plugins/console/server/services/spec_definitions_service.ts index 39a8d5094bd5c..ccd3b6b1c0a82 100644 --- a/src/plugins/console/server/services/spec_definitions_service.ts +++ b/src/plugins/console/server/services/spec_definitions_service.ts @@ -45,7 +45,7 @@ export class SpecDefinitionsService { copiedDescription = { ...this.endpoints[endpoint] }; } let urlParamsDef: any; - _.each(description.patterns || [], function(p) { + _.each(description.patterns || [], function (p) { if (p.indexOf('{indices}') >= 0) { urlParamsDef = urlParamsDef || {}; urlParamsDef.ignore_unavailable = '__flag__'; @@ -114,7 +114,7 @@ export class SpecDefinitionsService { const overrideFiles = glob.sync(join(dirname, 'overrides', '*.json')); return generatedFiles.reduce((acc, file) => { - const overrideFile = overrideFiles.find(f => basename(f) === basename(file)); + const overrideFile = overrideFiles.find((f) => basename(f) === basename(file)); const loadedSpec = JSON.parse(readFileSync(file, 'utf8')); if (overrideFile) { merge(loadedSpec, JSON.parse(readFileSync(overrideFile, 'utf8'))); @@ -135,16 +135,16 @@ export class SpecDefinitionsService { private loadJsonSpec() { const result = this.loadJSONSpecInDir(PATH_TO_OSS_JSON_SPEC); - this.extensionSpecFilePaths.forEach(extensionSpecFilePath => { + this.extensionSpecFilePaths.forEach((extensionSpecFilePath) => { merge(result, this.loadJSONSpecInDir(extensionSpecFilePath)); }); - Object.keys(result).forEach(endpoint => { + Object.keys(result).forEach((endpoint) => { this.addEndpointDescription(endpoint, result[endpoint]); }); } private loadJSSpec() { - jsSpecLoaders.forEach(addJsSpec => addJsSpec(this)); + jsSpecLoaders.forEach((addJsSpec) => addJsSpec(this)); } } diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts b/src/plugins/dashboard/common/migrate_to_730_panels.test.ts index 0867909225ddb..f7a03a54376ca 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts +++ b/src/plugins/dashboard/common/migrate_to_730_panels.test.ts @@ -134,7 +134,7 @@ test('6.0 migrates old panel data in the right order', () => { false, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); @@ -195,7 +195,7 @@ test('6.0 migrates old panel data in the right order without margins', () => { false, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); @@ -239,7 +239,7 @@ test('6.0 migrates old panel data in the right order with margins', () => { true, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.ts b/src/plugins/dashboard/common/migrate_to_730_panels.ts index b89345f0a872c..d870e3c87d6ab 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.ts +++ b/src/plugins/dashboard/common/migrate_to_730_panels.ts @@ -150,7 +150,7 @@ function migrate610PanelToLatest( useMargins: boolean, uiState?: { [key: string]: { [key: string]: unknown } } ): RawSavedDashboardPanel730ToLatest { - (['w', 'x', 'h', 'y'] as Array).forEach(key => { + (['w', 'x', 'h', 'y'] as Array).forEach((key) => { if (panel.gridData[key] === undefined) { throw new Error( i18n.translate('dashboard.panel.unableToMigratePanelDataForSixThreeZeroErrorMessage', { @@ -285,7 +285,7 @@ export function migratePanelsTo730( useMargins: boolean, uiState?: { [key: string]: { [key: string]: unknown } } ): RawSavedDashboardPanel730ToLatest[] { - return panels.map(panel => { + return panels.map((panel) => { if (isPre61Panel(panel)) { return migratePre61PanelToLatest(panel, version, useMargins, uiState); } diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx index 17943333d25b0..e7534fa09aa3f 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx @@ -96,7 +96,7 @@ test('Clone adds a new embeddable', async () => { await action.execute({ embeddable }); expect(Object.keys(container.getInput().panels).length).toEqual(originalPanelCount + 1); const newPanelId = Object.keys(container.getInput().panels).find( - key => !originalPanelKeySet.has(key) + (key) => !originalPanelKeySet.has(key) ); expect(newPanelId).toBeDefined(); const newPanel = container.getInput().panels[newPanelId!]; diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx index ff4e50ba8c327..96210358c05e4 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx @@ -97,10 +97,7 @@ export class ClonePanelAction implements ActionByType }); const cloneRegex = new RegExp(`\\(${clonedTag}\\)`, 'g'); const cloneNumberRegex = new RegExp(`\\(${clonedTag} [0-9]+\\)`, 'g'); - const baseTitle = rawTitle - .replace(cloneNumberRegex, '') - .replace(cloneRegex, '') - .trim(); + const baseTitle = rawTitle.replace(cloneNumberRegex, '').replace(cloneRegex, '').trim(); const similarSavedObjects = await this.core.savedObjects.client.find({ type: embeddableType, diff --git a/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx b/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx index fe9a19030602e..57fe4acf08145 100644 --- a/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx +++ b/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx @@ -107,7 +107,7 @@ export class ReplacePanelFlyout extends React.Component { })} savedObjectMetaData={[...this.props.getEmbeddableFactories()] .filter( - embeddableFactory => + (embeddableFactory) => Boolean(embeddableFactory.savedObjectMetaData) && !embeddableFactory.isContainerType ) .map(({ savedObjectMetaData }) => savedObjectMetaData as any)} diff --git a/src/plugins/dashboard/public/application/application.ts b/src/plugins/dashboard/public/application/application.ts index 8e29d2734065e..543450916c505 100644 --- a/src/plugins/dashboard/public/application/application.ts +++ b/src/plugins/dashboard/public/application/application.ts @@ -134,7 +134,7 @@ function createLocalAngularModule() { function createLocalIconModule() { angular .module('app/dashboard/icon', ['react']) - .directive('icon', reactDirective => reactDirective(EuiIcon)); + .directive('icon', (reactDirective) => reactDirective(EuiIcon)); } function createLocalI18nModule() { diff --git a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx index fa2f06bfcdcdd..8dd0a766da97b 100644 --- a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx @@ -160,7 +160,7 @@ export class DashboardAppController { set: ({ filters }) => dashboardStateManager.setFilters(filters || []), get: () => ({ filters: dashboardStateManager.appState.filters }), state$: dashboardStateManager.appState$.pipe( - map(state => ({ + map((state) => ({ filters: state.filters, })) ), @@ -228,7 +228,7 @@ export class DashboardAppController { } let panelIndexPatterns: IndexPattern[] = []; - Object.values(container.getChildIds()).forEach(id => { + Object.values(container.getChildIds()).forEach((id) => { const embeddableInstance = container.getChild(id); if (isErrorEmbeddable(embeddableInstance)) return; const embeddableIndexPatterns = (embeddableInstance.getOutput() as any).indexPatterns; @@ -242,7 +242,7 @@ export class DashboardAppController { $scope.indexPatterns = panelIndexPatterns; }); } else { - indexPatterns.getDefault().then(defaultIndexPattern => { + indexPatterns.getDefault().then((defaultIndexPattern) => { $scope.$evalAsync(() => { $scope.indexPatterns = [defaultIndexPattern as IndexPattern]; }); @@ -421,7 +421,7 @@ export class DashboardAppController { dirty: !dash.id, }; - dashboardStateManager.registerChangeListener(status => { + dashboardStateManager.registerChangeListener((status) => { this.appStatus.dirty = status.dirty || !dash.id; updateState(); }); @@ -484,7 +484,7 @@ export class DashboardAppController { differences.filters = appStateDashboardInput.filters; } - Object.keys(_.omit(containerInput, 'filters')).forEach(key => { + Object.keys(_.omit(containerInput, 'filters')).forEach((key) => { const containerValue = (containerInput as { [key: string]: unknown })[key]; const appStateValue = ((appStateDashboardInput as unknown) as { [key: string]: unknown })[ key @@ -506,7 +506,7 @@ export class DashboardAppController { } }; - $scope.updateQueryAndFetch = function({ query, dateRange }) { + $scope.updateQueryAndFetch = function ({ query, dateRange }) { if (dateRange) { timefilter.setTime(dateRange); } @@ -554,7 +554,7 @@ export class DashboardAppController { () => { return dashboardStateManager.getSavedQueryId(); }, - newSavedQueryId => { + (newSavedQueryId) => { if (!newSavedQueryId) { $scope.savedQuery = undefined; return; @@ -579,7 +579,7 @@ export class DashboardAppController { $scope.$watch( () => dashboardCapabilities.saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability as boolean; } ); @@ -712,7 +712,7 @@ export class DashboardAppController { }), } ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { revertChangesAndExitEditMode(); } @@ -735,7 +735,7 @@ export class DashboardAppController { */ function save(saveOptions: SavedObjectSaveOpts): Promise { return saveDashboard(angular.toJson, timefilter, dashboardStateManager, saveOptions) - .then(function(id) { + .then(function (id) { if (id) { notifications.toasts.addSuccess({ title: i18n.translate('dashboard.dashboardWasSavedSuccessMessage', { @@ -758,7 +758,7 @@ export class DashboardAppController { } return { id }; }) - .catch(error => { + .catch((error) => { notifications.toasts.addDanger({ title: i18n.translate('dashboard.dashboardWasNotSavedDangerMessage', { defaultMessage: `Dashboard '{dashTitle}' was not saved. Error: {errorMessage}`, @@ -904,7 +904,7 @@ export class DashboardAppController { } }; - navActions[TopNavIds.OPTIONS] = anchorElement => { + navActions[TopNavIds.OPTIONS] = (anchorElement) => { showOptionsPopover({ anchorElement, useMargins: dashboardStateManager.getUseMargins(), @@ -920,7 +920,7 @@ export class DashboardAppController { if (share) { // the share button is only availabale if "share" plugin contract enabled - navActions[TopNavIds.SHARE] = anchorElement => { + navActions[TopNavIds.SHARE] = (anchorElement) => { share.toggleShareContextMenu({ anchorElement, allowEmbed: true, @@ -950,7 +950,7 @@ export class DashboardAppController { }, }); - const visibleSubscription = chrome.getIsVisible$().subscribe(isVisible => { + const visibleSubscription = chrome.getIsVisible$().subscribe((isVisible) => { $scope.$evalAsync(() => { $scope.isVisible = isVisible; showSearchBar = isVisible || showFilterBar(); diff --git a/src/plugins/dashboard/public/application/dashboard_state.test.ts b/src/plugins/dashboard/public/application/dashboard_state.test.ts index cfb7fc7e56e42..e32bb9b9ecabe 100644 --- a/src/plugins/dashboard/public/application/dashboard_state.test.ts +++ b/src/plugins/dashboard/public/application/dashboard_state.test.ts @@ -24,7 +24,7 @@ import { InputTimeRange, TimefilterContract, TimeRange } from 'src/plugins/data/ import { ViewMode } from 'src/plugins/embeddable/public'; import { createKbnUrlStateStorage } from 'src/plugins/kibana_utils/public'; -describe('DashboardState', function() { +describe('DashboardState', function () { let dashboardState: DashboardStateManager; const savedDashboard = getSavedDashboardMock(); @@ -48,8 +48,8 @@ describe('DashboardState', function() { }); } - describe('syncTimefilterWithDashboard', function() { - test('syncs quick time', function() { + describe('syncTimefilterWithDashboard', function () { + test('syncs quick time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = 'now/w'; savedDashboard.timeTo = 'now/w'; @@ -64,7 +64,7 @@ describe('DashboardState', function() { expect(mockTime.from).toBe('now/w'); }); - test('syncs relative time', function() { + test('syncs relative time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = 'now-13d'; savedDashboard.timeTo = 'now'; @@ -79,7 +79,7 @@ describe('DashboardState', function() { expect(mockTime.from).toBe('now-13d'); }); - test('syncs absolute time', function() { + test('syncs absolute time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = '2015-09-19 06:31:44.000'; savedDashboard.timeTo = '2015-09-29 06:31:44.000'; @@ -95,7 +95,7 @@ describe('DashboardState', function() { }); }); - describe('isDirty', function() { + describe('isDirty', function () { beforeAll(() => { initDashboardState(); }); diff --git a/src/plugins/dashboard/public/application/dashboard_state_manager.ts b/src/plugins/dashboard/public/application/dashboard_state_manager.ts index b03ea95069a3d..5fed38487dc54 100644 --- a/src/plugins/dashboard/public/application/dashboard_state_manager.ts +++ b/src/plugins/dashboard/public/application/dashboard_state_manager.ts @@ -139,8 +139,8 @@ export class DashboardStateManager { this.stateContainer = createStateContainer( initialState, { - set: state => (prop, value) => ({ ...state, [prop]: value }), - setOption: state => (option, value) => ({ + set: (state) => (prop, value) => ({ ...state, [prop]: value }), + setOption: (state) => (option, value) => ({ ...state, options: { ...state.options, @@ -162,7 +162,7 @@ export class DashboardStateManager { this.stateContainerChangeSub = this.stateContainer.state$.subscribe(() => { this.isDirty = this.checkIsDirty(); - this.changeListeners.forEach(listener => listener({ dirty: this.isDirty })); + this.changeListeners.forEach((listener) => listener({ dirty: this.isDirty })); }); // setup state syncing utils. state container will be synced with url into `this.STATE_STORAGE_KEY` query param @@ -218,7 +218,7 @@ export class DashboardStateManager { const savedDashboardPanelMap: { [key: string]: SavedDashboardPanel } = {}; const input = dashboardContainer.getInput(); - this.getPanels().forEach(savedDashboardPanel => { + this.getPanels().forEach((savedDashboardPanel) => { if (input.panels[savedDashboardPanel.panelIndex] !== undefined) { savedDashboardPanelMap[savedDashboardPanel.panelIndex] = savedDashboardPanel; } else { @@ -229,7 +229,7 @@ export class DashboardStateManager { const convertedPanelStateMap: { [key: string]: SavedDashboardPanel } = {}; - Object.values(input.panels).forEach(panelState => { + Object.values(input.panels).forEach((panelState) => { if (savedDashboardPanelMap[panelState.explicitInput.id] === undefined) { dirty = true; } @@ -271,7 +271,7 @@ export class DashboardStateManager { this.setQuery(input.query); } - this.changeListeners.forEach(listener => listener({ dirty })); + this.changeListeners.forEach((listener) => listener({ dirty })); } public getFullScreenMode() { diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx index 6785a373c065b..3cebe2b847155 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx @@ -53,7 +53,7 @@ beforeEach(() => { options.embeddable = doStart(); }); -test('DashboardContainer initializes embeddables', async done => { +test('DashboardContainer initializes embeddables', async (done) => { const initialInput = getSampleDashboardInput({ panels: { '123': getSampleDashboardPanel({ @@ -64,7 +64,7 @@ test('DashboardContainer initializes embeddables', async done => { }); const container = new DashboardContainer(initialInput, options); - const subscription = container.getOutput$().subscribe(output => { + const subscription = container.getOutput$().subscribe((output) => { if (container.getOutput().embeddableLoaded['123']) { const embeddable = container.getChild('123'); expect(embeddable).toBeDefined(); diff --git a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx index 948e22e86a302..9b7cec2f182ba 100644 --- a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx @@ -167,7 +167,7 @@ test('DashboardGrid renders expanded panel', () => { ).toBeUndefined(); }); -test('DashboardGrid unmount unsubscribes', async done => { +test('DashboardGrid unmount unsubscribes', async (done) => { const { props, options } = prepare(); const component = mountWithIntl( diff --git a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx index f8632011002d0..19d9ad34e729c 100644 --- a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx +++ b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx @@ -199,7 +199,7 @@ class DashboardGridUi extends React.Component { } public buildLayoutFromPanels = (): GridData[] => { - return _.map(this.state.panels, panel => { + return _.map(this.state.panels, (panel) => { return panel.gridData; }); }; @@ -250,7 +250,7 @@ class DashboardGridUi extends React.Component { } }); - return _.map(panelsInOrder, panel => { + return _.map(panelsInOrder, (panel) => { const expandPanel = expandedPanelId !== undefined && expandedPanelId === panel.explicitInput.id; const hidePanel = expandedPanelId !== undefined && expandedPanelId !== panel.explicitInput.id; @@ -264,7 +264,7 @@ class DashboardGridUi extends React.Component { className={classes} key={panel.explicitInput.id} data-test-subj="dashboardPanel" - ref={reactGridItem => { + ref={(reactGridItem) => { this.gridItems[panel.explicitInput.id] = reactGridItem; }} > diff --git a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts index b95b7f394a27d..62a39ee898d3a 100644 --- a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts +++ b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts @@ -44,7 +44,7 @@ export function findTopLeftMostOpenSpace({ let maxY = -1; const currentPanelsArray = Object.values(currentPanels); - currentPanelsArray.forEach(panel => { + currentPanelsArray.forEach((panel) => { maxY = Math.max(panel.gridData.y + panel.gridData.h, maxY); }); @@ -58,7 +58,7 @@ export function findTopLeftMostOpenSpace({ grid[y] = new Array(DASHBOARD_GRID_COLUMN_COUNT).fill(0); } - currentPanelsArray.forEach(panel => { + currentPanelsArray.forEach((panel) => { for (let x = panel.gridData.x; x < panel.gridData.x + panel.gridData.w; x++) { for (let y = panel.gridData.y; y < panel.gridData.y + panel.gridData.h; y++) { const row = grid[y]; diff --git a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx index b3fc462fd1c50..1b257880b9401 100644 --- a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx @@ -153,23 +153,17 @@ test('renders exit full screen button when in full screen mode', async () => { ); - expect( - (component - .find('.dshDashboardViewport') - .childAt(0) - .type() as any).name - ).toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardViewport').childAt(0).type() as any).name).toBe( + 'ExitFullScreenButton' + ); props.container.updateInput({ isFullScreenMode: false }); component.update(); await nextTick(); - expect( - (component - .find('.dshDashboardViewport') - .childAt(0) - .type() as any).name - ).not.toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardViewport').childAt(0).type() as any).name).not.toBe( + 'ExitFullScreenButton' + ); component.unmount(); }); @@ -186,28 +180,22 @@ test('renders exit full screen button when in full screen mode and empty screen' ); - expect( - (component - .find('.dshDashboardEmptyScreen') - .childAt(0) - .type() as any).name - ).toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardEmptyScreen').childAt(0).type() as any).name).toBe( + 'ExitFullScreenButton' + ); props.container.updateInput({ isFullScreenMode: false }); component.update(); await nextTick(); - expect( - (component - .find('.dshDashboardEmptyScreen') - .childAt(0) - .type() as any).name - ).not.toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardEmptyScreen').childAt(0).type() as any).name).not.toBe( + 'ExitFullScreenButton' + ); component.unmount(); }); -test('DashboardViewport unmount unsubscribes', async done => { +test('DashboardViewport unmount unsubscribes', async (done) => { const { props, options } = getProps(); const component = mount( diff --git a/src/plugins/dashboard/public/application/legacy_app.js b/src/plugins/dashboard/public/application/legacy_app.js index 4e3cc15d93ece..2d99a2c6a2253 100644 --- a/src/plugins/dashboard/public/application/legacy_app.js +++ b/src/plugins/dashboard/public/application/legacy_app.js @@ -38,7 +38,7 @@ import { syncQueryStateWithUrl } from '../../../data/public'; export function initDashboardApp(app, deps) { initDashboardAppDirective(app, deps); - app.directive('dashboardListing', function(reactDirective) { + app.directive('dashboardListing', function (reactDirective) { return reactDirective(DashboardListing, [ ['core', { watchDepth: 'reference' }], ['createItem', { watchDepth: 'reference' }], @@ -61,14 +61,14 @@ export function initDashboardApp(app, deps) { } app.factory('history', () => createHashHistory()); - app.factory('kbnUrlStateStorage', history => + app.factory('kbnUrlStateStorage', (history) => createKbnUrlStateStorage({ history, useHash: deps.uiSettings.get('state:storeInSessionStorage'), }) ); - app.config(function($routeProvider) { + app.config(function ($routeProvider) { const defaults = { reloadOnSearch: false, requireUICapability: 'dashboard.show', @@ -96,7 +96,7 @@ export function initDashboardApp(app, deps) { .when(DashboardConstants.LANDING_PAGE_PATH, { ...defaults, template: dashboardListingTemplate, - controller: function($scope, kbnUrlStateStorage, history) { + controller: function ($scope, kbnUrlStateStorage, history) { deps.core.chrome.docTitle.change( i18n.translate('dashboard.dashboardPageTitle', { defaultMessage: 'Dashboards' }) ); @@ -114,7 +114,7 @@ export function initDashboardApp(app, deps) { $scope.create = () => { history.push(DashboardConstants.CREATE_NEW_DASHBOARD_URL); }; - $scope.find = search => { + $scope.find = (search) => { return service.find(search, $scope.listingLimit); }; $scope.editItem = ({ id }) => { @@ -123,8 +123,8 @@ export function initDashboardApp(app, deps) { $scope.getViewUrl = ({ id }) => { return deps.addBasePath(`#${createDashboardEditUrl(id)}`); }; - $scope.delete = dashboards => { - return service.delete(dashboards.map(d => d.id)); + $scope.delete = (dashboards) => { + return service.delete(dashboards.map((d) => d.id)); }; $scope.hideWriteControls = dashboardConfig.getHideWriteControls(); $scope.initialFilter = parse(history.location.search).filter || EMPTY_FILTER; @@ -143,7 +143,7 @@ export function initDashboardApp(app, deps) { }); }, resolve: { - dash: function($route, history) { + dash: function ($route, history) { return deps.data.indexPatterns.ensureDefaultIndexPattern(history).then(() => { const savedObjectsClient = deps.savedObjectsClient; const title = $route.current.params.title; @@ -154,10 +154,11 @@ export function initDashboardApp(app, deps) { search_fields: 'title', type: 'dashboard', }) - .then(results => { + .then((results) => { // The search isn't an exact match, lets see if we can find a single exact match to use const matchingDashboards = results.savedObjects.filter( - dashboard => dashboard.attributes.title.toLowerCase() === title.toLowerCase() + (dashboard) => + dashboard.attributes.title.toLowerCase() === title.toLowerCase() ); if (matchingDashboards.length === 1) { history.replace(createDashboardEditUrl(matchingDashboards[0].id)); @@ -178,7 +179,7 @@ export function initDashboardApp(app, deps) { controller: createNewDashboardCtrl, requireUICapability: 'dashboard.createNew', resolve: { - dash: history => + dash: (history) => deps.data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => deps.savedDashboards.get()) @@ -199,13 +200,13 @@ export function initDashboardApp(app, deps) { template: dashboardTemplate, controller: createNewDashboardCtrl, resolve: { - dash: function($route, history) { + dash: function ($route, history) { const id = $route.current.params.id; return deps.data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => deps.savedDashboards.get(id)) - .then(savedDashboard => { + .then((savedDashboard) => { deps.chrome.recentlyAccessed.add( savedDashboard.getFullPath(), savedDashboard.title, @@ -213,7 +214,7 @@ export function initDashboardApp(app, deps) { ); return savedDashboard; }) - .catch(error => { + .catch((error) => { // Preserve BWC of v5.3.0 links for new, unsaved dashboards. // See https://github.com/elastic/kibana/issues/10951 for more context. if (error instanceof SavedObjectNotFound && id === 'create') { @@ -242,7 +243,7 @@ export function initDashboardApp(app, deps) { }) .otherwise({ template: '', - controller: function() { + controller: function () { deps.navigateToDefaultApp(); }, }); diff --git a/src/plugins/dashboard/public/application/lib/filter_utils.ts b/src/plugins/dashboard/public/application/lib/filter_utils.ts index 775bf90643a21..b6b935d6050ae 100644 --- a/src/plugins/dashboard/public/application/lib/filter_utils.ts +++ b/src/plugins/dashboard/public/application/lib/filter_utils.ts @@ -37,9 +37,7 @@ export class FilterUtils { */ public static convertTimeToUTCString(time?: string | Moment): undefined | string { if (moment(time).isValid()) { - return moment(time) - .utc() - .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'); + return moment(time).utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'); } else { // If it's not a valid moment date, then it should be a string representing a relative time // like 'now' or 'now-15m'. @@ -66,7 +64,7 @@ export class FilterUtils { * @returns {Array.} */ public static cleanFiltersForComparison(filters: Filter[]) { - return _.map(filters, filter => { + return _.map(filters, (filter) => { const f: Partial = _.omit(filter, ['$$hashKey', '$state']); if (f.meta) { // f.meta.value is the value displayed in the filter bar. diff --git a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts index f4d97578adebf..6632eafc51f30 100644 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts +++ b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts @@ -58,7 +58,7 @@ export function migrateAppState( | SavedDashboardPanel630 | SavedDashboardPanel640To720 | SavedDashboardPanel730ToLatest - >).some(panel => { + >).some((panel) => { if ((panel as { version?: string }).version === undefined) return true; const version = (panel as SavedDashboardPanel730ToLatest).version; diff --git a/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts b/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts index fc519327b41ee..e3b6725ce7449 100644 --- a/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts +++ b/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts @@ -53,6 +53,6 @@ export function updateSavedDashboard( // save only unpinned filters const unpinnedFilters = savedDashboard .getFilters() - .filter(filter => !esFilters.isFilterPinned(filter)); + .filter((filter) => !esFilters.isFilterPinned(filter)); savedDashboard.searchSource.setField('filter', unpinnedFilters); } diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js index 0cdefff6a738e..dccac4e7c3c76 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js @@ -22,7 +22,7 @@ jest.mock( () => ({ ...require.requireActual('lodash'), // mock debounce to fire immediately with no internal timer - debounce: func => { + debounce: (func) => { function debounced(...args) { return func.apply(this, args); } @@ -37,7 +37,7 @@ import { shallow } from 'enzyme'; import { DashboardListing } from './dashboard_listing'; -const find = num => { +const find = (num) => { const hits = []; for (let i = 0; i < num; i++) { hits.push({ @@ -85,7 +85,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -107,7 +107,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -129,7 +129,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -151,7 +151,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -173,7 +173,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index b4419adfe58da..08740b21f39a4 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -174,7 +174,7 @@ export class DashboardPlugin }, []); }; - const ExitFullScreenButton: React.FC = props => { + const ExitFullScreenButton: React.FC = (props) => { useHideChrome(); return ; }; @@ -290,7 +290,7 @@ export class DashboardPlugin kibanaLegacy.forwardApp( DashboardConstants.DASHBOARD_ID, DashboardConstants.DASHBOARDS_ID, - path => { + (path) => { const [, id, tail] = /dashboard\/?(.*?)($|\?.*)/.exec(path) || []; if (!id && !tail) { // unrecognized sub url @@ -307,7 +307,7 @@ export class DashboardPlugin kibanaLegacy.forwardApp( DashboardConstants.DASHBOARDS_ID, DashboardConstants.DASHBOARDS_ID, - path => { + (path) => { const [, tail] = /(\?.*)/.exec(path) || []; // carry over query if it exists return `#/list${tail || ''}`; diff --git a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts index 3e49b6636f562..3df9e64887725 100644 --- a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts +++ b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts @@ -70,11 +70,11 @@ export function injectReferences( if (!Array.isArray(panels)) { return; } - panels.forEach(panel => { + panels.forEach((panel) => { if (!panel.panelRefName) { return; } - const reference = references.find(ref => ref.name === panel.panelRefName); + const reference = references.find((ref) => ref.name === panel.panelRefName); if (!reference) { // Throw an error since "panelRefName" means the reference exists within // "references" and in this scenario we have bad data. diff --git a/src/plugins/dashboard/public/url_generator.ts b/src/plugins/dashboard/public/url_generator.ts index 08ba6a6ca921d..d6805b2d94119 100644 --- a/src/plugins/dashboard/public/url_generator.ts +++ b/src/plugins/dashboard/public/url_generator.ts @@ -83,7 +83,7 @@ export const createDashboardUrlGenerator = ( }> ): UrlGeneratorsDefinition => ({ id: DASHBOARD_APP_URL_GENERATOR, - createUrl: async state => { + createUrl: async (state) => { const startServices = await getStartServices(); const useHash = state.useHash ?? startServices.useHashedUrl; const appBasePath = startServices.appBasePath; @@ -103,7 +103,7 @@ export const createDashboardUrlGenerator = ( }; const cleanEmptyKeys = (stateObj: Record) => { - Object.keys(stateObj).forEach(key => { + Object.keys(stateObj).forEach((key) => { if (stateObj[key] === undefined) { delete stateObj[key]; } @@ -122,7 +122,7 @@ export const createDashboardUrlGenerator = ( STATE_STORAGE_KEY, cleanEmptyKeys({ query: state.query, - filters: filters?.filter(f => !esFilters.isFilterPinned(f)), + filters: filters?.filter((f) => !esFilters.isFilterPinned(f)), }), { useHash }, `${appBasePath}#/${hash}` @@ -132,7 +132,7 @@ export const createDashboardUrlGenerator = ( GLOBAL_STATE_STORAGE_KEY, cleanEmptyKeys({ time: state.timeRange, - filters: filters?.filter(f => esFilters.isFilterPinned(f)), + filters: filters?.filter((f) => esFilters.isFilterPinned(f)), refreshInterval: state.refreshInterval, }), { useHash }, diff --git a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts index db2fbeb278802..75e169b79f320 100644 --- a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts +++ b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts @@ -21,7 +21,7 @@ import { SavedObjectMigrationFn } from 'kibana/server'; import { get } from 'lodash'; import { DEFAULT_QUERY_LANGUAGE } from '../../../data/common'; -export const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { +export const migrateMatchAllQuery: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (searchSourceJSON) { diff --git a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts b/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts index 01a66445e4fc2..071568831d835 100644 --- a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts +++ b/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts @@ -61,7 +61,7 @@ export function moveFiltersToQuery( searchSource.filter = []; } - searchSource.filter.forEach(filter => { + searchSource.filter.forEach((filter) => { if (isQueryFilter(filter)) { searchSource730.query = { query: filter.query.query_string ? filter.query.query_string.query : '', diff --git a/src/plugins/data/common/es_query/es_query/build_es_query.ts b/src/plugins/data/common/es_query/es_query/build_es_query.ts index e4f5f1f9e216c..66d44f5e0747f 100644 --- a/src/plugins/data/common/es_query/es_query/build_es_query.ts +++ b/src/plugins/data/common/es_query/es_query/build_es_query.ts @@ -53,7 +53,7 @@ export function buildEsQuery( queries = Array.isArray(queries) ? queries : [queries]; filters = Array.isArray(filters) ? filters : [filters]; - const validQueries = queries.filter(query => has(query, 'query')); + const validQueries = queries.filter((query) => has(query, 'query')); const queriesByLanguage = groupBy(validQueries, 'language'); const kueryQuery = buildQueryFromKuery( indexPattern, diff --git a/src/plugins/data/common/es_query/es_query/from_filters.ts b/src/plugins/data/common/es_query/es_query/from_filters.ts index ed91d391fc1fd..d2d52efedd085 100644 --- a/src/plugins/data/common/es_query/es_query/from_filters.ts +++ b/src/plugins/data/common/es_query/es_query/from_filters.ts @@ -58,16 +58,18 @@ export const buildQueryFromFilters = ( indexPattern: IIndexPattern | undefined, ignoreFilterIfFieldNotInIndex: boolean = false ) => { - filters = filters.filter(filter => filter && !isFilterDisabled(filter)); + filters = filters.filter((filter) => filter && !isFilterDisabled(filter)); const filtersToESQueries = (negate: boolean) => { return filters .filter(filterNegate(negate)) - .filter(filter => !ignoreFilterIfFieldNotInIndex || filterMatchesIndex(filter, indexPattern)) - .map(filter => { + .filter( + (filter) => !ignoreFilterIfFieldNotInIndex || filterMatchesIndex(filter, indexPattern) + ) + .map((filter) => { return migrateFilter(filter, indexPattern); }) - .map(filter => handleNestedFilter(filter, indexPattern)) + .map((filter) => handleNestedFilter(filter, indexPattern)) .map(translateToQuery) .map(cleanFilter); }; diff --git a/src/plugins/data/common/es_query/es_query/from_kuery.test.ts b/src/plugins/data/common/es_query/es_query/from_kuery.test.ts index 4574cd5ffd0cb..7ddd4dee743c5 100644 --- a/src/plugins/data/common/es_query/es_query/from_kuery.test.ts +++ b/src/plugins/data/common/es_query/es_query/from_kuery.test.ts @@ -46,7 +46,7 @@ describe('build query', () => { { query: 'machine.os:osx', language: 'kuery' }, ] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern); }); @@ -57,7 +57,7 @@ describe('build query', () => { test("should accept a specific date format for a kuery query into an ES query in the bool's filter clause", () => { const queries = [{ query: '@timestamp:"2018-04-03T19:04:17"', language: 'kuery' }] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern, { dateFormatTZ: 'America/Phoenix', }); @@ -72,7 +72,7 @@ describe('build query', () => { const queries = [ { query: '@timestamp:"2018-04-03T19:04:17Z"', language: 'kuery' }, ] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern); }); diff --git a/src/plugins/data/common/es_query/es_query/from_kuery.ts b/src/plugins/data/common/es_query/es_query/from_kuery.ts index f4ec0fe0b34c5..8af319704067b 100644 --- a/src/plugins/data/common/es_query/es_query/from_kuery.ts +++ b/src/plugins/data/common/es_query/es_query/from_kuery.ts @@ -27,7 +27,7 @@ export function buildQueryFromKuery( allowLeadingWildcards: boolean = false, dateFormatTZ?: string ) { - const queryASTs = queries.map(query => { + const queryASTs = queries.map((query) => { return fromKueryExpression(query.query, { allowLeadingWildcards }); }); diff --git a/src/plugins/data/common/es_query/es_query/from_lucene.test.ts b/src/plugins/data/common/es_query/es_query/from_lucene.test.ts index fc85404a5060c..53edeec37e0b3 100644 --- a/src/plugins/data/common/es_query/es_query/from_lucene.test.ts +++ b/src/plugins/data/common/es_query/es_query/from_lucene.test.ts @@ -41,7 +41,7 @@ describe('build query', () => { { query: 'foo:bar', language: 'lucene' }, { query: 'bar:baz', language: 'lucene' }, ] as unknown) as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}); }); @@ -64,7 +64,7 @@ describe('build query', () => { { query: 'bar:baz', language: 'lucene' }, ] as unknown) as Query[]; const dateFormatTZ = 'America/Phoenix'; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}, dateFormatTZ); }); const result = buildQueryFromLucene(queries, {}, dateFormatTZ); diff --git a/src/plugins/data/common/es_query/es_query/from_lucene.ts b/src/plugins/data/common/es_query/es_query/from_lucene.ts index 8babb6df4fba5..18c2b24872e32 100644 --- a/src/plugins/data/common/es_query/es_query/from_lucene.ts +++ b/src/plugins/data/common/es_query/es_query/from_lucene.ts @@ -25,7 +25,7 @@ export function buildQueryFromLucene( queryStringOptions: Record, dateFormatTZ?: string ) { - const combinedQueries = (queries || []).map(query => { + const combinedQueries = (queries || []).map((query) => { const queryDsl = luceneStringToDsl(query.query); return decorateQuery(queryDsl, queryStringOptions, dateFormatTZ); diff --git a/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts b/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts index 594b2641c39be..ad1ad34741d20 100644 --- a/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts +++ b/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts @@ -22,7 +22,7 @@ import { fields } from '../../index_patterns/mocks'; import { buildPhraseFilter, buildQueryFilter } from '../filters'; import { IFieldType, IIndexPattern } from '../../index_patterns'; -describe('handleNestedFilter', function() { +describe('handleNestedFilter', function () { const indexPattern: IIndexPattern = ({ id: 'logstash-*', fields, @@ -86,6 +86,6 @@ describe('handleNestedFilter', function() { }); function getField(name: string) { - return indexPattern.fields.find(field => field.name === name); + return indexPattern.fields.find((field) => field.name === name); } }); diff --git a/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts b/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts index 27be7925fe00c..a0f4abb514b22 100644 --- a/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts +++ b/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts @@ -28,7 +28,9 @@ export const handleNestedFilter = (filter: Filter, indexPattern?: IIndexPattern) return filter; } - const field = indexPattern.fields.find(indexPatternField => indexPatternField.name === fieldName); + const field = indexPattern.fields.find( + (indexPatternField) => indexPatternField.name === fieldName + ); if (!field || !field.subType || !field.subType.nested || !field.subType.nested.path) { return filter; } diff --git a/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts b/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts index 698d7bb48e685..ae9d1c7921955 100644 --- a/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts +++ b/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts @@ -21,7 +21,7 @@ import { isEqual, clone } from 'lodash'; import { migrateFilter, DeprecatedMatchPhraseFilter } from './migrate_filter'; import { PhraseFilter, MatchAllFilter } from '../filters'; -describe('migrateFilter', function() { +describe('migrateFilter', function () { const oldMatchPhraseFilter = ({ query: { match: { @@ -45,13 +45,13 @@ describe('migrateFilter', function() { meta: {}, } as unknown) as PhraseFilter; - it('should migrate match filters of type phrase', function() { + it('should migrate match filters of type phrase', function () { const migratedFilter = migrateFilter(oldMatchPhraseFilter, undefined); expect(migratedFilter).toEqual(newMatchPhraseFilter); }); - it('should not modify the original filter', function() { + it('should not modify the original filter', function () { const oldMatchPhraseFilterCopy = clone(oldMatchPhraseFilter, true); migrateFilter(oldMatchPhraseFilter, undefined); @@ -59,7 +59,7 @@ describe('migrateFilter', function() { expect(isEqual(oldMatchPhraseFilter, oldMatchPhraseFilterCopy)).toBe(true); }); - it('should return the original filter if no migration is necessary', function() { + it('should return the original filter if no migration is necessary', function () { const originalFilter = { match_all: {}, } as MatchAllFilter; diff --git a/src/plugins/data/common/es_query/es_query/migrate_filter.ts b/src/plugins/data/common/es_query/es_query/migrate_filter.ts index a0529d585879e..498763be538de 100644 --- a/src/plugins/data/common/es_query/es_query/migrate_filter.ts +++ b/src/plugins/data/common/es_query/es_query/migrate_filter.ts @@ -45,7 +45,7 @@ export function migrateFilter(filter: Filter, indexPattern?: IIndexPattern) { const params: Record = get(filter, ['query', 'match', fieldName]); let query = params.query; if (indexPattern) { - const field = indexPattern.fields.find(f => f.name === fieldName); + const field = indexPattern.fields.find((f) => f.name === fieldName); if (field) { query = getConvertedValueForField(field, params.query); diff --git a/src/plugins/data/common/es_query/filters/exists_filter.test.ts b/src/plugins/data/common/es_query/filters/exists_filter.test.ts index af52192dd85e4..065301986726d 100644 --- a/src/plugins/data/common/es_query/filters/exists_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/exists_filter.test.ts @@ -21,14 +21,14 @@ import { buildExistsFilter, getExistsFilterField } from './exists_filter'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('exists filter', function() { +describe('exists filter', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; - describe('getExistsFilterField', function() { + describe('getExistsFilterField', function () { it('should return the name of the field an exists query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildExistsFilter(field!, indexPattern); const result = getExistsFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts index 63c3a59044c1f..5d605c58a10d3 100644 --- a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts @@ -19,8 +19,8 @@ import { getGeoBoundingBoxFilterField } from './geo_bounding_box_filter'; -describe('geo_bounding_box filter', function() { - describe('getGeoBoundingBoxFilterField', function() { +describe('geo_bounding_box filter', function () { + describe('getGeoBoundingBoxFilterField', function () { it('should return the name of the field a geo_bounding_box query is targeting', () => { const filter = { geo_bounding_box: { diff --git a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts index 619903954ff55..e41e3f2978344 100644 --- a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts +++ b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts @@ -37,6 +37,6 @@ export const isGeoBoundingBoxFilter = (filter: any): filter is GeoBoundingBoxFil export const getGeoBoundingBoxFilterField = (filter: GeoBoundingBoxFilter) => { return ( filter.geo_bounding_box && - Object.keys(filter.geo_bounding_box).find(key => key !== 'ignore_unmapped') + Object.keys(filter.geo_bounding_box).find((key) => key !== 'ignore_unmapped') ); }; diff --git a/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts b/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts index ba8e43b0cea85..f309e72e24e5c 100644 --- a/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts @@ -19,8 +19,8 @@ import { getGeoPolygonFilterField } from './geo_polygon_filter'; -describe('geo_polygon filter', function() { - describe('getGeoPolygonFilterField', function() { +describe('geo_polygon filter', function () { + describe('getGeoPolygonFilterField', function () { it('should return the name of the field a geo_polygon query is targeting', () => { const filter = { geo_polygon: { diff --git a/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts b/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts index 03367feb83ee4..2b00f2e3cb99c 100644 --- a/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts +++ b/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts @@ -35,6 +35,6 @@ export const isGeoPolygonFilter = (filter: any): filter is GeoPolygonFilter => export const getGeoPolygonFilterField = (filter: GeoPolygonFilter) => { return ( - filter.geo_polygon && Object.keys(filter.geo_polygon).find(key => key !== 'ignore_unmapped') + filter.geo_polygon && Object.keys(filter.geo_polygon).find((key) => key !== 'ignore_unmapped') ); }; diff --git a/src/plugins/data/common/es_query/filters/get_filter_field.test.ts b/src/plugins/data/common/es_query/filters/get_filter_field.test.ts index 2fc8ffef9713b..4329a45f84ef9 100644 --- a/src/plugins/data/common/es_query/filters/get_filter_field.test.ts +++ b/src/plugins/data/common/es_query/filters/get_filter_field.test.ts @@ -23,14 +23,14 @@ import { getFilterField } from './get_filter_field'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('getFilterField', function() { +describe('getFilterField', function () { const indexPattern: IIndexPattern = ({ id: 'logstash-*', fields, } as unknown) as IIndexPattern; it('should return the field name from known filter types that target a specific field', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhraseFilter(field!, 'jpg', indexPattern); const result = getFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts b/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts index 43d4bdaf03bc1..93b91757e1dac 100644 --- a/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts +++ b/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts @@ -24,5 +24,5 @@ export function getIndexPatternFromFilter( filter: Filter, indexPatterns: IIndexPattern[] ): IIndexPattern | undefined { - return indexPatterns.find(indexPattern => indexPattern.id === filter.meta.index); + return indexPatterns.find((indexPattern) => indexPattern.id === filter.meta.index); } diff --git a/src/plugins/data/common/es_query/filters/missing_filter.test.ts b/src/plugins/data/common/es_query/filters/missing_filter.test.ts index 240d8fb26f3e0..28d2d3776d74c 100644 --- a/src/plugins/data/common/es_query/filters/missing_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/missing_filter.test.ts @@ -19,8 +19,8 @@ import { getMissingFilterField } from './missing_filter'; -describe('missing filter', function() { - describe('getMissingFilterField', function() { +describe('missing filter', function () { + describe('getMissingFilterField', function () { it('should return the name of the field an missing query is targeting', () => { const filter = { missing: { diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.test.ts b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts index 9f90097e55475..a3948777e6d65 100644 --- a/src/plugins/data/common/es_query/filters/phrase_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts @@ -100,13 +100,13 @@ describe('buildInlineScriptForPhraseFilter', () => { }); }); -describe('getPhraseFilterField', function() { +describe('getPhraseFilterField', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; it('should return the name of the field a phrase query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhraseFilter(field!, 'jpg', indexPattern); const result = getPhraseFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/phrases_filter.test.ts b/src/plugins/data/common/es_query/filters/phrases_filter.test.ts index 3a121eb9da034..7fbab263ac040 100644 --- a/src/plugins/data/common/es_query/filters/phrases_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/phrases_filter.test.ts @@ -21,14 +21,14 @@ import { buildPhrasesFilter, getPhrasesFilterField } from './phrases_filter'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('phrases filter', function() { +describe('phrases filter', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; - describe('getPhrasesFilterField', function() { + describe('getPhrasesFilterField', function () { it('should return the name of the field a phrases query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhrasesFilter(field!, ['jpg', 'png'], indexPattern); const result = getPhrasesFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/range_filter.test.ts b/src/plugins/data/common/es_query/filters/range_filter.test.ts index 45d59c97941b3..8accca5c29a45 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.test.ts @@ -173,13 +173,13 @@ describe('Range filter builder', () => { }); }); -describe('getRangeFilterField', function() { +describe('getRangeFilterField', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; test('should return the name of the field a range query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'bytes'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'bytes'); const filter = buildRangeFilter(field!, {}, indexPattern); const result = getRangeFilterField(filter); expect(result).toBe('bytes'); diff --git a/src/plugins/data/common/es_query/filters/range_filter.ts b/src/plugins/data/common/es_query/filters/range_filter.ts index b300539f4280a..c318a0f0c2c3d 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.ts @@ -112,7 +112,7 @@ export const buildRangeFilter = ( filter.meta.formattedValue = formattedValue; } - params = mapValues(params, value => (field.type === 'number' ? parseFloat(value) : value)); + params = mapValues(params, (value) => (field.type === 'number' ? parseFloat(value) : value)); if ('gte' in params && 'gt' in params) throw new Error('gte and gt are mutually exclusive'); if ('lte' in params && 'lt' in params) throw new Error('lte and lt are mutually exclusive'); diff --git a/src/plugins/data/common/es_query/kuery/functions/and.test.ts b/src/plugins/data/common/es_query/kuery/functions/and.test.ts index 133e691b27dba..6f27a6dcb30fa 100644 --- a/src/plugins/data/common/es_query/kuery/functions/and.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/and.test.ts @@ -61,7 +61,7 @@ describe('kuery functions', () => { expect(Object.keys(result.bool).length).toBe(1); expect(result.bool.filter).toEqual( - [childNode1, childNode2].map(childNode => + [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) ); diff --git a/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts b/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts index f382e5668bb9d..753fd4e0a5060 100644 --- a/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts +++ b/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts @@ -24,7 +24,7 @@ import { LiteralTypeBuildNode } from '../node_types/types'; export function buildNodeParams(fieldName: string, points: LatLon[]) { const fieldNameArg = nodeTypes.literal.buildNode(fieldName); - const args = points.map(point => { + const args = points.map((point) => { const latLon = `${point.lat}, ${point.lon}`; return nodeTypes.literal.buildNode(latLon); }); diff --git a/src/plugins/data/common/es_query/kuery/functions/or.test.ts b/src/plugins/data/common/es_query/kuery/functions/or.test.ts index a6590546e5fc5..5ef8610362ca9 100644 --- a/src/plugins/data/common/es_query/kuery/functions/or.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/or.test.ts @@ -60,7 +60,7 @@ describe('kuery functions', () => { expect(Object.keys(result).length).toBe(1); expect(result.bool).toHaveProperty('should'); expect(result.bool.should).toEqual( - [childNode1, childNode2].map(childNode => + [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) ); diff --git a/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts b/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts index 0e314ec778af8..cdd050b2647c1 100644 --- a/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts +++ b/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts @@ -26,13 +26,13 @@ export function getFields(node: KueryNode, indexPattern?: IIndexPattern) { if (!indexPattern) return []; if (node.type === 'literal') { const fieldName = literal.toElasticsearchQuery(node as LiteralTypeBuildNode); - const field = indexPattern.fields.find(fld => fld.name === fieldName); + const field = indexPattern.fields.find((fld) => fld.name === fieldName); if (!field) { return []; } return [field]; } else if (node.type === 'wildcard') { - const fields = indexPattern.fields.filter(fld => wildcard.test(node, fld.name)); + const fields = indexPattern.fields.filter((fld) => wildcard.test(node, fld.name)); return fields; } } diff --git a/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts b/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts index 200c5b51e4d27..abfdb2c363821 100644 --- a/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts @@ -24,7 +24,7 @@ import { IIndexPattern } from '../../../../index_patterns'; // @ts-ignore import { getFullFieldNameNode } from './get_full_field_name_node'; -describe('getFullFieldNameNode', function() { +describe('getFullFieldNameNode', function () { let indexPattern: IIndexPattern; beforeEach(() => { diff --git a/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts b/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts index 4ada139a10a0f..6aac1a3b3486d 100644 --- a/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts +++ b/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts @@ -55,7 +55,7 @@ export class KQLSyntaxError extends Error { constructor(error: KQLSyntaxErrorData, expression: any) { let message = error.message; if (error.expected) { - const translatedExpectations = error.expected.map(expected => { + const translatedExpectations = error.expected.map((expected) => { return grammarRuleTranslations[expected.description] || expected.description; }); diff --git a/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts b/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts index 87fcfa1ca2f64..160212c58f0fb 100644 --- a/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts +++ b/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts @@ -46,10 +46,7 @@ export function buildNode(value: string): WildcardTypeBuildNode | KueryNode { export function test(node: any, str: string): boolean { const { value } = node; - const regex = value - .split(wildcardSymbol) - .map(escapeRegExp) - .join('[\\s\\S]*'); + const regex = value.split(wildcardSymbol).map(escapeRegExp).join('[\\s\\S]*'); const regexp = new RegExp(`^${regex}$`); return regexp.test(str); } @@ -61,10 +58,7 @@ export function toElasticsearchQuery(node: any): string { export function toQueryStringQuery(node: any): string { const { value } = node; - return value - .split(wildcardSymbol) - .map(escapeQueryString) - .join('*'); + return value.split(wildcardSymbol).map(escapeQueryString).join('*'); } export function hasLeadingWildcard(node: any): boolean { diff --git a/src/plugins/data/common/field_formats/content_types/text_content_type.ts b/src/plugins/data/common/field_formats/content_types/text_content_type.ts index dc450086edc62..4a90ba6c0b203 100644 --- a/src/plugins/data/common/field_formats/content_types/text_content_type.ts +++ b/src/plugins/data/common/field_formats/content_types/text_content_type.ts @@ -27,7 +27,7 @@ export const setup = ( format: IFieldFormat, convert: TextContextTypeConvert = asPrettyString ): TextContextTypeConvert => { - const recurse: TextContextTypeConvert = value => { + const recurse: TextContextTypeConvert = (value) => { if (!value || !isFunction(value.map)) { return convert.call(format, value); } diff --git a/src/plugins/data/common/field_formats/converters/boolean.test.ts b/src/plugins/data/common/field_formats/converters/boolean.test.ts index 3650df6517611..cef7936aaaf13 100644 --- a/src/plugins/data/common/field_formats/converters/boolean.test.ts +++ b/src/plugins/data/common/field_formats/converters/boolean.test.ts @@ -63,7 +63,7 @@ describe('Boolean Format', () => { input: ' True ', // should handle trailing and mixed case expected: 'true', }, - ].forEach(data => { + ].forEach((data) => { test(`convert ${data.input} to boolean`, () => { expect(boolean.convert(data.input)).toBe(data.expected); }); diff --git a/src/plugins/data/common/field_formats/converters/boolean.ts b/src/plugins/data/common/field_formats/converters/boolean.ts index a824f9e73fb1e..f8304a396f83c 100644 --- a/src/plugins/data/common/field_formats/converters/boolean.ts +++ b/src/plugins/data/common/field_formats/converters/boolean.ts @@ -30,7 +30,7 @@ export class BoolFormat extends FieldFormat { }); static fieldType = [KBN_FIELD_TYPES.BOOLEAN, KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.STRING]; - textConvert: TextContextTypeConvert = value => { + textConvert: TextContextTypeConvert = (value) => { if (typeof value === 'string') { value = value.trim().toLowerCase(); } diff --git a/src/plugins/data/common/field_formats/converters/color.ts b/src/plugins/data/common/field_formats/converters/color.ts index babf3dbd8c451..ca659916f7671 100644 --- a/src/plugins/data/common/field_formats/converters/color.ts +++ b/src/plugins/data/common/field_formats/converters/color.ts @@ -60,7 +60,7 @@ export class ColorFormat extends FieldFormat { } } - htmlConvert: HtmlContextTypeConvert = val => { + htmlConvert: HtmlContextTypeConvert = (val) => { const color = this.findColorRuleForVal(val) as typeof DEFAULT_CONVERTER_COLOR; if (!color) return escape(asPrettyString(val)); diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts b/src/plugins/data/common/field_formats/converters/date_nanos.test.ts index ea755eb5d5bdf..267f023e9b69d 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos.test.ts @@ -67,7 +67,7 @@ describe('Date Nanos Format', () => { pattern: 'SSSSSSSSS', expected: '201900001', }, - ].forEach(fixture => { + ].forEach((fixture) => { const fracPattern = analysePatternForFract(fixture.pattern); const momentDate = moment(fixture.input).utc(); const value = formatWithNanos(momentDate, fixture.input, fracPattern); diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.ts b/src/plugins/data/common/field_formats/converters/date_nanos.ts index 93f3a62842749..3fa2b1c276cd7 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos.ts @@ -88,7 +88,7 @@ export class DateNanosFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so // we can hot-swap when config changes const pattern = this.param('pattern'); diff --git a/src/plugins/data/common/field_formats/converters/duration.ts b/src/plugins/data/common/field_formats/converters/duration.ts index 3b3b6f87f36f9..53c2aba98120e 100644 --- a/src/plugins/data/common/field_formats/converters/duration.ts +++ b/src/plugins/data/common/field_formats/converters/duration.ts @@ -186,7 +186,7 @@ export class DurationFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const inputFormat = this.param('inputFormat'); const outputFormat = this.param('outputFormat') as keyof Duration; const outputPrecision = this.param('outputPrecision'); diff --git a/src/plugins/data/common/field_formats/converters/ip.ts b/src/plugins/data/common/field_formats/converters/ip.ts index 8e65d9c12d6c8..da86cdbd6b051 100644 --- a/src/plugins/data/common/field_formats/converters/ip.ts +++ b/src/plugins/data/common/field_formats/converters/ip.ts @@ -29,7 +29,7 @@ export class IpFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.IP; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { if (val === undefined || val === null) return '-'; if (!isFinite(val)) return val; diff --git a/src/plugins/data/common/field_formats/converters/numeral.ts b/src/plugins/data/common/field_formats/converters/numeral.ts index d8e46a480294f..a483b5a1e4f99 100644 --- a/src/plugins/data/common/field_formats/converters/numeral.ts +++ b/src/plugins/data/common/field_formats/converters/numeral.ts @@ -61,7 +61,7 @@ export abstract class NumeralFormat extends FieldFormat { return formatted; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { return this.getConvertedValue(val); }; } diff --git a/src/plugins/data/common/field_formats/converters/percent.ts b/src/plugins/data/common/field_formats/converters/percent.ts index 8cbc2d36d0ef1..ef3b0a1503a98 100644 --- a/src/plugins/data/common/field_formats/converters/percent.ts +++ b/src/plugins/data/common/field_formats/converters/percent.ts @@ -36,7 +36,7 @@ export class PercentFormat extends NumeralFormat { fractional: true, }); - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const formatted = super.getConvertedValue(val); if (this.param('fractional')) { diff --git a/src/plugins/data/common/field_formats/converters/relative_date.ts b/src/plugins/data/common/field_formats/converters/relative_date.ts index 7c7f20ee9c411..e3bdf25da9076 100644 --- a/src/plugins/data/common/field_formats/converters/relative_date.ts +++ b/src/plugins/data/common/field_formats/converters/relative_date.ts @@ -30,7 +30,7 @@ export class RelativeDateFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.DATE; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { if (val === null || val === undefined) { return '-'; } diff --git a/src/plugins/data/common/field_formats/converters/source.ts b/src/plugins/data/common/field_formats/converters/source.ts index 7f13d5526cc15..9e50d47bb2624 100644 --- a/src/plugins/data/common/field_formats/converters/source.ts +++ b/src/plugins/data/common/field_formats/converters/source.ts @@ -56,7 +56,7 @@ export class SourceFormat extends FieldFormat { static title = '_source'; static fieldType = KBN_FIELD_TYPES._SOURCE; - textConvert: TextContextTypeConvert = value => JSON.stringify(value); + textConvert: TextContextTypeConvert = (value) => JSON.stringify(value); htmlConvert: HtmlContextTypeConvert = (value, options = {}) => { const { field, hit } = options; @@ -73,7 +73,7 @@ export class SourceFormat extends FieldFormat { const sourcePairs: any[] = []; const isShortDots = this.getConfig!('shortDots:enable'); - keys(formatted).forEach(key => { + keys(formatted).forEach((key) => { const pairs = highlights[key] ? highlightPairs : sourcePairs; const newField = isShortDots ? shortenDottedString(key) : key; const val = formatted[key]; diff --git a/src/plugins/data/common/field_formats/converters/static_lookup.ts b/src/plugins/data/common/field_formats/converters/static_lookup.ts index c835afd3db5ec..394bea5be4f25 100644 --- a/src/plugins/data/common/field_formats/converters/static_lookup.ts +++ b/src/plugins/data/common/field_formats/converters/static_lookup.ts @@ -51,7 +51,7 @@ export class StaticLookupFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const lookupEntries = this.param('lookupEntries'); const unknownKeyValue = this.param('unknownKeyValue'); diff --git a/src/plugins/data/common/field_formats/converters/string.ts b/src/plugins/data/common/field_formats/converters/string.ts index 22df9f1f88bfb..a543a46f965cc 100644 --- a/src/plugins/data/common/field_formats/converters/string.ts +++ b/src/plugins/data/common/field_formats/converters/string.ts @@ -105,12 +105,12 @@ export class StringFormat extends FieldFormat { } private toTitleCase(val: string) { - return val.replace(/\w\S*/g, txt => { + return val.replace(/\w\S*/g, (txt) => { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { switch (this.param('transform')) { case 'lower': return String(val).toLowerCase(); diff --git a/src/plugins/data/common/field_formats/converters/truncate.ts b/src/plugins/data/common/field_formats/converters/truncate.ts index 70b2a3dff18f2..a6c4a1133a2ed 100644 --- a/src/plugins/data/common/field_formats/converters/truncate.ts +++ b/src/plugins/data/common/field_formats/converters/truncate.ts @@ -32,7 +32,7 @@ export class TruncateFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.STRING; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const length = this.param('fieldLength'); if (length > 0) { return trunc(val, { diff --git a/src/plugins/data/common/field_formats/converters/url.ts b/src/plugins/data/common/field_formats/converters/url.ts index 60d7efdba34ff..a0a498b6cab34 100644 --- a/src/plugins/data/common/field_formats/converters/url.ts +++ b/src/plugins/data/common/field_formats/converters/url.ts @@ -111,7 +111,7 @@ export class UrlFormat extends FieldFormat { // trim all the odd bits, the variable names const parts = template.split(templateMatchRE).map((part, i) => (i % 2 ? part.trim() : part)); - return function(locals: Record): string { + return function (locals: Record): string { // replace all the odd bits with their local var let output = ''; let i = -1; @@ -139,7 +139,7 @@ export class UrlFormat extends FieldFormat { return `${imageLabel}`; } - textConvert: TextContextTypeConvert = value => this.formatLabel(value); + textConvert: TextContextTypeConvert = (value) => this.formatLabel(value); htmlConvert: HtmlContextTypeConvert = (rawValue, options = {}) => { const { field, hit } = options; @@ -161,7 +161,7 @@ export class UrlFormat extends FieldFormat { return this.generateImgHtml(url, imageLabel); default: - const inWhitelist = whitelistUrlSchemes.some(scheme => url.indexOf(scheme) === 0); + const inWhitelist = whitelistUrlSchemes.some((scheme) => url.indexOf(scheme) === 0); if (!inWhitelist && !parsedUrl) { return url; } diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 2eb9a3e593d1a..c04a371066de3 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -129,7 +129,7 @@ export class FieldFormatsRegistry { return undefined; } - return esTypes.find(type => this.defaultMap[type] && this.defaultMap[type].es); + return esTypes.find((type) => this.defaultMap[type] && this.defaultMap[type].es); }; /** @@ -231,7 +231,7 @@ export class FieldFormatsRegistry { parseDefaultTypeMap(value: any) { this.defaultMap = value; - forOwn(this, fn => { + forOwn(this, (fn) => { if (isFunction(fn) && fn.cache) { // clear all memoize caches // @ts-ignore @@ -241,7 +241,7 @@ export class FieldFormatsRegistry { } register(fieldFormats: FieldFormatInstanceType[]) { - fieldFormats.forEach(fieldFormat => this.fieldFormats.set(fieldFormat.id, fieldFormat)); + fieldFormats.forEach((fieldFormat) => this.fieldFormats.set(fieldFormat.id, fieldFormat)); } /** diff --git a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts index 6ada630851c1d..8df25a2f34269 100644 --- a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts +++ b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts @@ -21,7 +21,7 @@ import { highlightTags } from './highlight_tags'; import { htmlTags } from './html_tags'; import { getHighlightHtml } from './highlight_html'; -describe('getHighlightHtml', function() { +describe('getHighlightHtml', function () { const text = '' + 'Bacon ipsum dolor amet pork loin pork cow pig beef chuck ground round shankle sirloin landjaeger kevin ' + @@ -29,20 +29,20 @@ describe('getHighlightHtml', function() { 'sirloin, t-bone ham shoulder jerky turducken bresaola. Chicken cow beef picanha. Picanha hamburger alcatra ' + 'cupim. Salami capicola boudin pork belly shank picanha.'; - test('should not modify text if highlight is empty', function() { + test('should not modify text if highlight is empty', function () { expect(getHighlightHtml(text, undefined)).toBe(text); expect(getHighlightHtml(text, null)).toBe(text); expect(getHighlightHtml(text, [])).toBe(text); }); - test('should preserve escaped text', function() { + test('should preserve escaped text', function () { const highlights = ['']; const result = getHighlightHtml('<foo>', highlights); expect(result.indexOf('')).toBe(-1); expect(result.indexOf('<foo>')).toBeGreaterThan(-1); }); - test('should highlight a single result', function() { + test('should highlight a single result', function () { const highlights = [ highlightTags.pre + 'hamburger' + @@ -56,7 +56,7 @@ describe('getHighlightHtml', function() { ); }); - test('should highlight multiple results', function() { + test('should highlight multiple results', function () { const highlights = [ 'kevin venison sausage ribeye tongue. ' + highlightTags.pre + @@ -76,7 +76,7 @@ describe('getHighlightHtml', function() { ); }); - test('should highlight multiple hits in a result', function() { + test('should highlight multiple hits in a result', function () { const highlights = [ 'Bacon ipsum dolor amet ' + highlightTags.pre + @@ -114,7 +114,7 @@ describe('getHighlightHtml', function() { ); }); - test('should accept an object and return a string containing its properties', function() { + test('should accept an object and return a string containing its properties', function () { const obj = { foo: 1, bar: 2 }; const result = getHighlightHtml(obj, null); expect(result.indexOf('' + obj)).toBe(-1); diff --git a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts index c7c092941728e..23c72e94b120a 100644 --- a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts +++ b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts @@ -24,7 +24,7 @@ import { htmlTags } from './html_tags'; export function getHighlightHtml(fieldValue: any, highlights: any) { let highlightHtml = typeof fieldValue === 'object' ? JSON.stringify(fieldValue) : fieldValue; - _.each(highlights, function(highlight) { + _.each(highlights, function (highlight) { const escapedHighlight = _.escape(highlight); // Strip out the highlight tags to compare against the field text diff --git a/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts b/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts index c27ff42b1e9d2..ed778d0422054 100644 --- a/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts +++ b/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts @@ -318,4 +318,4 @@ export const fields: IFieldType[] = [ }, ]; -export const getField = (name: string) => fields.find(field => field.name === name) as IFieldType; +export const getField = (name: string) => fields.find((field) => field.name === name) as IFieldType; diff --git a/src/plugins/data/common/index_patterns/utils.test.ts b/src/plugins/data/common/index_patterns/utils.test.ts index e2707d469a317..43d6fadb336ff 100644 --- a/src/plugins/data/common/index_patterns/utils.test.ts +++ b/src/plugins/data/common/index_patterns/utils.test.ts @@ -30,20 +30,20 @@ const mockField = { describe('isFilterable', () => { describe('types', () => { it('should return true for filterable types', () => { - ['string', 'number', 'date', 'ip', 'boolean'].forEach(type => { + ['string', 'number', 'date', 'ip', 'boolean'].forEach((type) => { expect(isFilterable({ ...mockField, type })).toBe(true); }); }); it('should return false for filterable types if the field is not searchable', () => { - ['string', 'number', 'date', 'ip', 'boolean'].forEach(type => { + ['string', 'number', 'date', 'ip', 'boolean'].forEach((type) => { expect(isFilterable({ ...mockField, type, searchable: false })).toBe(false); }); }); it('should return false for un-filterable types', () => { ['geo_point', 'geo_shape', 'attachment', 'murmur3', '_source', 'unknown', 'conflict'].forEach( - type => { + (type) => { expect(isFilterable({ ...mockField, type })).toBe(false); } ); diff --git a/src/plugins/data/common/kbn_field_types/kbn_field_types.ts b/src/plugins/data/common/kbn_field_types/kbn_field_types.ts index 91d3b7404e5b0..ce05dc796bbab 100644 --- a/src/plugins/data/common/kbn_field_types/kbn_field_types.ts +++ b/src/plugins/data/common/kbn_field_types/kbn_field_types.ts @@ -31,7 +31,7 @@ const registeredKbnTypes = createKbnFieldTypes(); * @return {KbnFieldType} */ export const getKbnFieldType = (typeName: string): KbnFieldType | undefined => - registeredKbnTypes.find(t => t.name === typeName); + registeredKbnTypes.find((t) => t.name === typeName); /** * Get the esTypes known by all kbnFieldTypes @@ -39,7 +39,7 @@ export const getKbnFieldType = (typeName: string): KbnFieldType | undefined => * @return {Array} */ export const getKbnTypeNames = (): string[] => - registeredKbnTypes.filter(type => type.name).map(type => type.name); + registeredKbnTypes.filter((type) => type.name).map((type) => type.name); /** * Get the KbnFieldType name for an esType string @@ -48,7 +48,7 @@ export const getKbnTypeNames = (): string[] => * @return {string} */ export const castEsToKbnFieldTypeName = (esType: ES_FIELD_TYPES | string): KBN_FIELD_TYPES => { - const type = registeredKbnTypes.find(t => t.esTypes.includes(esType as ES_FIELD_TYPES)); + const type = registeredKbnTypes.find((t) => t.esTypes.includes(esType as ES_FIELD_TYPES)); return type && type.name ? (type.name as KBN_FIELD_TYPES) : KBN_FIELD_TYPES.UNKNOWN; }; @@ -59,4 +59,4 @@ export const castEsToKbnFieldTypeName = (esType: ES_FIELD_TYPES | string): KBN_F * @return {Array} */ export const getFilterableKbnTypeNames = (): string[] => - registeredKbnTypes.filter(type => type.filterable).map(type => type.name); + registeredKbnTypes.filter((type) => type.filterable).map((type) => type.name); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts index 9df17b4c24a98..fe8ea6e346ba7 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts @@ -69,7 +69,7 @@ export function leastCommonInterval(a: string, b: string): string { } // Otherwise find the biggest non-calendar unit that divides evenly - const lcmUnit = unitsDesc.find(unit => { + const lcmUnit = unitsDesc.find((unit) => { const unitInfo = unitsMap[unit]; return !!(unitInfo.type !== 'calendar' && lcmMs % unitInfo.base === 0); }); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts index c18ff4c7acead..b2e51faada2ac 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts @@ -45,7 +45,7 @@ describe('parseEsInterval', () => { const intervals = ['4w', '12M', '10y']; expect.assertions(intervals.length); - intervals.forEach(interval => { + intervals.forEach((interval) => { try { parseEsInterval(interval); } catch (error) { @@ -58,7 +58,7 @@ describe('parseEsInterval', () => { const intervals = ['1', 'h', '0m', '0.5h']; expect.assertions(intervals.length); - intervals.forEach(interval => { + intervals.forEach((interval) => { try { parseEsInterval(interval); } catch (error) { diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts index f53da19ef476f..7121b776b800e 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts @@ -48,9 +48,7 @@ export type ParsedInterval = ReturnType; * */ export function parseEsInterval(interval: string) { - const matches = String(interval) - .trim() - .match(ES_INTERVAL_STRING_REGEX); + const matches = String(interval).trim().match(ES_INTERVAL_STRING_REGEX); if (!matches) { throw new InvalidEsIntervalFormatError(interval); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts index 857c8594720ee..e9d708d7061d2 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts @@ -25,9 +25,7 @@ import dateMath from '@elastic/datemath'; const INTERVAL_STRING_RE = new RegExp('^([0-9\\.]*)\\s*(' + dateMath.units.join('|') + ')$'); export function parseInterval(interval: string): moment.Duration | null { - const matches = String(interval) - .trim() - .match(INTERVAL_STRING_RE); + const matches = String(interval).trim().match(INTERVAL_STRING_RE); if (!matches) return null; @@ -46,7 +44,7 @@ export function parseInterval(interval: string): moment.Duration | null { // a duration corresponding to 0.5 hours, we return a duration corresponding to 12 hours. const selectedUnit = find( dateMath.units, - u => Math.abs(duration.as(u)) >= 1 + (u) => Math.abs(duration.as(u)) >= 1 ) as unitOfTime.Base; // however if we do this fhe other way around it will also fail diff --git a/src/plugins/data/common/utils/abort_utils.test.ts b/src/plugins/data/common/utils/abort_utils.test.ts index d2a25f2c2dd52..cd78d95b2ab00 100644 --- a/src/plugins/data/common/utils/abort_utils.test.ts +++ b/src/plugins/data/common/utils/abort_utils.test.ts @@ -21,7 +21,7 @@ import { AbortError, toPromise, getCombinedSignal } from './abort_utils'; jest.useFakeTimers(); -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); describe('AbortUtils', () => { describe('AbortError', () => { diff --git a/src/plugins/data/common/utils/abort_utils.ts b/src/plugins/data/common/utils/abort_utils.ts index 9aec787170840..aef9802cecce9 100644 --- a/src/plugins/data/common/utils/abort_utils.ts +++ b/src/plugins/data/common/utils/abort_utils.ts @@ -61,7 +61,7 @@ export function toPromise(signal: AbortSignal, shouldReject: boolean = false) { * @param signals */ export function getCombinedSignal(signals: AbortSignal[]) { - const promises = signals.map(signal => toPromise(signal)); + const promises = signals.map((signal) => toPromise(signal)); const controller = new AbortController(); Promise.race(promises).then(() => controller.abort()); return controller.signal; diff --git a/src/plugins/data/public/actions/apply_filter_action.ts b/src/plugins/data/public/actions/apply_filter_action.ts index ebaac6b745bec..7e8ed5ec8fb22 100644 --- a/src/plugins/data/public/actions/apply_filter_action.ts +++ b/src/plugins/data/public/actions/apply_filter_action.ts @@ -62,12 +62,12 @@ export function createFilterAction( if (selectedFilters.length > 1) { const indexPatterns = await Promise.all( - filters.map(filter => { + filters.map((filter) => { return getIndexPatterns().get(filter.meta.index!); }) ); - const filterSelectionPromise: Promise = new Promise(resolve => { + const filterSelectionPromise: Promise = new Promise((resolve) => { const overlay = getOverlays().openModal( toMountPoint( applyFiltersPopover( diff --git a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts index 2b426813a98a4..2fdd746535519 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts @@ -42,16 +42,16 @@ const getOtherBucketFilterTerms = ( } // get only rows where cell value matches current row for all the fields before columnIndex - const rows = table.rows.filter(row => { + const rows = table.rows.filter((row) => { return table.columns.every((column, i) => { return row[column.id] === table.rows[rowIndex][column.id] || i >= columnIndex; }); }); - const terms: any[] = rows.map(row => row[table.columns[columnIndex].id]); + const terms: any[] = rows.map((row) => row[table.columns[columnIndex].id]); return [ ...new Set( - terms.filter(term => { + terms.filter((term) => { const notOther = term !== '__other__'; const notMissing = term !== '__missing__'; return notOther && notMissing; @@ -119,12 +119,12 @@ export const createFiltersFromValueClickAction = async ({ await Promise.all( data - .filter(point => point) - .map(async val => { + .filter((point) => point) + .map(async (val) => { const { table, column, row } = val; const filter: Filter[] = (await createFilter(table, column, row)) || []; if (filter) { - filter.forEach(f => { + filter.forEach((f) => { if (negate) { f = esFilters.toggleFilterNegated(f); } diff --git a/src/plugins/data/public/actions/value_click_action.ts b/src/plugins/data/public/actions/value_click_action.ts index 17c1b1b1e1769..5d4f1f5f1d6db 100644 --- a/src/plugins/data/public/actions/value_click_action.ts +++ b/src/plugins/data/public/actions/value_click_action.ts @@ -68,12 +68,12 @@ export function valueClickAction( if (filters.length > 1) { const indexPatterns = await Promise.all( - filters.map(filter => { + filters.map((filter) => { return getIndexPatterns().get(filter.meta.index!); }) ); - const filterSelectionPromise: Promise = new Promise(resolve => { + const filterSelectionPromise: Promise = new Promise((resolve) => { const overlay = getOverlays().openModal( toMountPoint( applyFiltersPopover( diff --git a/src/plugins/data/public/autocomplete/autocomplete_service.ts b/src/plugins/data/public/autocomplete/autocomplete_service.ts index bc557f31f7466..cf248adea0b05 100644 --- a/src/plugins/data/public/autocomplete/autocomplete_service.ts +++ b/src/plugins/data/public/autocomplete/autocomplete_service.ts @@ -34,7 +34,7 @@ export class AutocompleteService { } }; - private getQuerySuggestions: QuerySuggestionGetFn = args => { + private getQuerySuggestions: QuerySuggestionGetFn = (args) => { const { language } = args; const provider = this.querySuggestionProviders.get(language); diff --git a/src/plugins/data/public/field_formats/converters/date.ts b/src/plugins/data/public/field_formats/converters/date.ts index 3e1efdc69dec8..78ef8b293e8b9 100644 --- a/src/plugins/data/public/field_formats/converters/date.ts +++ b/src/plugins/data/public/field_formats/converters/date.ts @@ -45,7 +45,7 @@ export class DateFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so // we can hot-swap when config changes const pattern = this.param('pattern'); diff --git a/src/plugins/data/public/field_formats/utils/deserialize.ts b/src/plugins/data/public/field_formats/utils/deserialize.ts index 840e023a11589..d9c713c8b1eb4 100644 --- a/src/plugins/data/public/field_formats/utils/deserialize.ts +++ b/src/plugins/data/public/field_formats/utils/deserialize.ts @@ -60,7 +60,7 @@ const getFieldFormat = ( return new DefaultFieldFormat(); }; -export const deserializeFieldFormat: FormatFactory = function( +export const deserializeFieldFormat: FormatFactory = function ( this: DataPublicPluginStart['fieldFormats'], mapping?: SerializedFieldFormat ) { diff --git a/src/plugins/data/public/index_patterns/fields/field_list.ts b/src/plugins/data/public/index_patterns/fields/field_list.ts index 0631e00a1fb62..1aef0b1ccadaa 100644 --- a/src/plugins/data/public/index_patterns/fields/field_list.ts +++ b/src/plugins/data/public/index_patterns/fields/field_list.ts @@ -68,7 +68,7 @@ export const getIndexPatternFieldListCreator = ({ this.indexPattern = indexPattern; this.shortDotsEnable = shortDotsEnable; - specs.map(field => this.add(field)); + specs.map((field) => this.add(field)); } getByName = (name: Field['name']) => this.byName.get(name); @@ -96,7 +96,7 @@ export const getIndexPatternFieldListCreator = ({ fieldFormats, toastNotifications, }); - const index = this.findIndex(f => f.name === newField.name); + const index = this.findIndex((f) => f.name === newField.name); this.splice(index, 1, newField); this.setByName(newField); this.removeByGroup(newField); diff --git a/src/plugins/data/public/index_patterns/fields/obj_define.js b/src/plugins/data/public/index_patterns/fields/obj_define.js index bb32f93d6011a..9c9e5c8f3d55f 100644 --- a/src/plugins/data/public/index_patterns/fields/obj_define.js +++ b/src/plugins/data/public/index_patterns/fields/obj_define.js @@ -27,7 +27,7 @@ export function ObjDefine(defaults, prototype) { this.prototype = prototype || Object.prototype; } -ObjDefine.REDEFINE_SUPPORTED = (function() { +ObjDefine.REDEFINE_SUPPORTED = (function () { const a = Object.create(Object.prototype, { prop: { configurable: true, @@ -49,7 +49,7 @@ ObjDefine.REDEFINE_SUPPORTED = (function() { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.writ = function(name, val) { +ObjDefine.prototype.writ = function (name, val) { this._define(name, val, true, true); }; @@ -59,7 +59,7 @@ ObjDefine.prototype.writ = function(name, val) { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.fact = function(name, val) { +ObjDefine.prototype.fact = function (name, val) { this._define(name, val, true); }; @@ -69,7 +69,7 @@ ObjDefine.prototype.fact = function(name, val) { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.comp = function(name, val) { +ObjDefine.prototype.comp = function (name, val) { this._define(name, val); }; @@ -84,7 +84,7 @@ ObjDefine.prototype.comp = function(name, val) { * * @return {object} - created object */ -ObjDefine.prototype.create = function() { +ObjDefine.prototype.create = function () { const self = this; self.obj = Object.create(this.prototype, self.descs); @@ -94,10 +94,10 @@ ObjDefine.prototype.create = function() { // to include or trim manually. This is currently only in use in PhantomJS // due to https://github.com/ariya/phantomjs/issues/11856 // TODO: remove this: https://github.com/elastic/kibana/issues/27136 - self.obj.toJSON = function() { + self.obj.toJSON = function () { return _.transform( self.obj, - function(json, val, key) { + function (json, val, key) { const desc = self.descs[key]; if (desc && desc.enumerable && val == null) return; json[key] = val; @@ -114,12 +114,12 @@ ObjDefine.prototype.create = function() { * Private APIS */ -ObjDefine.prototype._define = function(name, val, exported, changeable) { +ObjDefine.prototype._define = function (name, val, exported, changeable) { val = val != null ? val : this.defaults[name]; this.descs[name] = this._describe(name, val, !!exported, !!changeable); }; -ObjDefine.prototype._describe = function(name, val, exported, changeable) { +ObjDefine.prototype._describe = function (name, val, exported, changeable) { const self = this; const exists = val != null; @@ -128,7 +128,7 @@ ObjDefine.prototype._describe = function(name, val, exported, changeable) { enumerable: exists, configurable: true, get: _.constant(val), - set: function(update) { + set: function (update) { if (!changeable) return false; // change the descriptor, since the value now exists. diff --git a/src/plugins/data/public/index_patterns/fields/obj_define.test.js b/src/plugins/data/public/index_patterns/fields/obj_define.test.js index 7bcd97ec06813..ec9a022253621 100644 --- a/src/plugins/data/public/index_patterns/fields/obj_define.test.js +++ b/src/plugins/data/public/index_patterns/fields/obj_define.test.js @@ -20,13 +20,13 @@ import expect from '@kbn/expect'; import { ObjDefine } from './obj_define'; -describe('ObjDefine Utility', function() { +describe('ObjDefine Utility', function () { function flatten(obj) { return JSON.parse(JSON.stringify(obj)); } - describe('#writ', function() { - it('creates writeable properties', function() { + describe('#writ', function () { + it('creates writeable properties', function () { const def = new ObjDefine(); def.writ('name', 'foo'); @@ -37,13 +37,13 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', 'bar'); }); - it('exports the property to JSON', function() { + it('exports the property to JSON', function () { const def = new ObjDefine(); def.writ('name', 'foo'); expect(flatten(def.create())).to.have.property('name', 'foo'); }); - it("does not export property to JSON it it's undefined or null", function() { + it("does not export property to JSON it it's undefined or null", function () { const def = new ObjDefine(); def.writ('name'); expect(flatten(def.create())).to.not.have.property('name'); @@ -52,7 +52,7 @@ describe('ObjDefine Utility', function() { expect(flatten(def.create())).to.not.have.property('name'); }); - it('switched to exporting if a value is written', function() { + it('switched to exporting if a value is written', function () { const def = new ObjDefine(); def.writ('name'); @@ -66,7 +66,7 @@ describe('ObjDefine Utility', function() { expect(flatten(obj)).to.have.property('name', 'foo'); }); - it('setting a writ value to null prevents it from exporting', function() { + it('setting a writ value to null prevents it from exporting', function () { const def = new ObjDefine(); def.writ('name', 'foo'); @@ -78,8 +78,8 @@ describe('ObjDefine Utility', function() { }); }); - describe('#fact', function() { - it('creates an immutable field', function() { + describe('#fact', function () { + it('creates an immutable field', function () { const def = new ObjDefine(); const val = 'foo'; const notval = 'bar'; @@ -90,37 +90,37 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', val); }); - it('exports the fact to JSON', function() { + it('exports the fact to JSON', function () { const def = new ObjDefine(); def.fact('name', 'foo'); expect(flatten(def.create())).to.have.property('name', 'foo'); }); }); - describe('#comp', function() { - it('creates an immutable field', function() { + describe('#comp', function () { + it('creates an immutable field', function () { const def = new ObjDefine(); const val = 'foo'; const notval = 'bar'; def.comp('name', val); const obj = def.create(); - expect(function() { + expect(function () { 'use strict'; // eslint-disable-line strict obj.name = notval; }).to.throwException(); }); - it('does not export the computed value to JSON', function() { + it('does not export the computed value to JSON', function () { const def = new ObjDefine(); def.comp('name', 'foo'); expect(flatten(def.create())).to.not.have.property('name'); }); }); - describe('#create', function() { - it('creates object that inherits from the prototype', function() { + describe('#create', function () { + it('creates object that inherits from the prototype', function () { function SomeClass() {} const def = new ObjDefine(null, SomeClass.prototype); @@ -129,7 +129,7 @@ describe('ObjDefine Utility', function() { expect(obj).to.be.a(SomeClass); }); - it('uses the defaults for property values', function() { + it('uses the defaults for property values', function () { const def = new ObjDefine({ name: 'bar' }); def.fact('name'); @@ -138,7 +138,7 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', 'bar'); }); - it('ignores default values that are not defined properties', function() { + it('ignores default values that are not defined properties', function () { const def = new ObjDefine({ name: 'foo', name2: 'bar' }); const obj = def.create(); diff --git a/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts b/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts index 18c6578e3142d..c194687b7c3bf 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts @@ -30,7 +30,7 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: const fields = indexPattern.fields.getByName; (function flatten(obj, keyPrefix = '') { keyPrefix = keyPrefix ? keyPrefix + '.' : ''; - _.forOwn(obj, function(val, key) { + _.forOwn(obj, function (val, key) { key = keyPrefix + key; if (deep) { @@ -38,7 +38,7 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: const isNestedField = field && field.type === 'nested'; const isArrayOfObjects = Array.isArray(val) && _.isPlainObject(_.first(val)); if (isArrayOfObjects && !isNestedField) { - _.each(val, v => flatten(v, key)); + _.each(val, (v) => flatten(v, key)); return; } } else if (flat[key] !== void 0) { @@ -68,15 +68,15 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: } function decorateFlattenedWrapper(hit: Record, metaFields: Record) { - return function(flattened: Record) { + return function (flattened: Record) { // assign the meta fields - _.each(metaFields, function(meta) { + _.each(metaFields, function (meta) { if (meta === '_source') return; flattened[meta] = hit[meta]; }); // unwrap computed fields - _.forOwn(hit.fields, function(val, key: any) { + _.forOwn(hit.fields, function (val, key: any) { if (key[0] === '_' && !_.contains(metaFields, key)) return; flattened[key] = Array.isArray(val) && val.length === 1 ? val[0] : val; }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts index 9b18fb98f3e02..a0597ed4b9026 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts @@ -64,7 +64,7 @@ export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any const cache: Record = {}; formattedCache.set(hit, cache); - _.forOwn(indexPattern.flattenHit(hit), function(val: any, fieldName?: string) { + _.forOwn(indexPattern.flattenHit(hit), function (val: any, fieldName?: string) { // sync the formatted and partial cache if (!fieldName) { return; @@ -77,7 +77,7 @@ export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any return cache; } - formatHit.formatField = function(hit: Record, fieldName: string) { + formatHit.formatField = function (hit: Record, fieldName: string) { let partials = partialFormattedCache.get(hit); if (partials && partials[fieldName] != null) { return partials[fieldName]; diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts index 305aa8575e4d7..e4058007e0a57 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts @@ -55,7 +55,7 @@ let mockFieldsFetcherResponse: any[] = []; jest.mock('./_fields_fetcher', () => ({ createFieldsFetcher: jest.fn().mockImplementation(() => ({ fetch: jest.fn().mockImplementation(() => { - return new Promise(resolve => resolve(mockFieldsFetcherResponse)); + return new Promise((resolve) => resolve(mockFieldsFetcherResponse)); }), every: jest.fn(), })), @@ -160,7 +160,7 @@ describe('IndexPattern', () => { }); describe('fields', () => { - test('should have expected properties on fields', function() { + test('should have expected properties on fields', function () { expect(indexPattern.fields[0]).toHaveProperty('displayName'); expect(indexPattern.fields[0]).toHaveProperty('filterable'); expect(indexPattern.fields[0]).toHaveProperty('format'); @@ -191,7 +191,7 @@ describe('IndexPattern', () => { test('should request date fields as docvalue_fields', () => { const { docvalueFields } = indexPattern.getComputedFields(); - const docValueFieldNames = docvalueFields.map(field => field.field); + const docValueFieldNames = docvalueFields.map((field) => field.field); expect(Object.keys(docValueFieldNames).length).toBe(3); expect(docValueFieldNames).toContain('@timestamp'); @@ -201,7 +201,7 @@ describe('IndexPattern', () => { test('should request date field doc values in date_time format', () => { const { docvalueFields } = indexPattern.getComputedFields(); - const timestampField = docvalueFields.find(field => field.field === '@timestamp'); + const timestampField = docvalueFields.find((field) => field.field === '@timestamp'); expect(timestampField).toHaveProperty('format', 'date_time'); }); @@ -237,7 +237,7 @@ describe('IndexPattern', () => { const newFields = indexPattern.getNonScriptedFields(); expect(newFields).toHaveLength(2); - expect(newFields.map(f => f.name)).toEqual(['foo', 'bar']); + expect(newFields.map((f) => f.name)).toEqual(['foo', 'bar']); }); test('should preserve the scripted fields', async () => { @@ -249,7 +249,7 @@ describe('IndexPattern', () => { // called to append scripted fields to the response from mapper.getFieldsForIndexPattern // sinon.assert.calledOnce(indexPattern.getScriptedFields); - expect(indexPattern.getScriptedFields().map(f => f.name)).toEqual( + expect(indexPattern.getScriptedFields().map((f) => f.name)).toEqual( mockLogStashFields() .filter((f: Field) => f.scripted) .map((f: Field) => f.name) @@ -313,7 +313,7 @@ describe('IndexPattern', () => { describe('popularizeField', () => { test('should increment the popularity count by default', () => { // const saveSpy = sinon.stub(indexPattern, 'save'); - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; await indexPattern.popularizeField(field.name); @@ -325,7 +325,7 @@ describe('IndexPattern', () => { test('should increment the popularity count', () => { // const saveSpy = sinon.stub(indexPattern, 'save'); - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; const incrementAmount = 4; @@ -337,7 +337,7 @@ describe('IndexPattern', () => { }); test('should decrement the popularity count', () => { - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; const incrementAmount = 4; const decrementAmount = -2; @@ -350,7 +350,7 @@ describe('IndexPattern', () => { }); test('should not go below 0', () => { - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const decrementAmount = -Number.MAX_VALUE; await indexPattern.popularizeField(field.name, decrementAmount); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts index 3780557db50d3..417d8227b121c 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts @@ -85,7 +85,7 @@ export class IndexPattern implements IIndexPattern { return _.isEmpty(serialized) ? undefined : JSON.stringify(serialized); }, _deserialize: (map = '{}') => { - return _.mapValues(JSON.parse(map), mapping => { + return _.mapValues(JSON.parse(map), (mapping) => { return this.deserializeFieldFormatMap(mapping); }); }, @@ -149,7 +149,7 @@ export class IndexPattern implements IIndexPattern { return true; } - return this.fields.every(field => { + return this.fields.every((field) => { // See https://github.com/elastic/kibana/pull/8421 const hasFieldCaps = 'aggregatable' in field && 'searchable' in field; @@ -220,7 +220,7 @@ export class IndexPattern implements IIndexPattern { } ); - each(this.getScriptedFields(), function(field) { + each(this.getScriptedFields(), function (field) { scriptFields[field.name] = { script: { source: field.script, @@ -424,7 +424,7 @@ export class IndexPattern implements IIndexPattern { const body = this.prepBody(); // What keys changed since they last pulled the index pattern const originalChangedKeys = Object.keys(body).filter( - key => body[key] !== this.originalBody[key] + (key) => body[key] !== this.originalBody[key] ); return this.savedObjectsClient .update(type, this.id, body, { version: this.version }) @@ -432,7 +432,7 @@ export class IndexPattern implements IIndexPattern { this.id = resp.id; this.version = resp._version; }) - .catch(err => { + .catch((err) => { if ( _.get(err, 'res.status') === 409 && saveAttempts++ < MAX_ATTEMPTS_TO_RESOLVE_CONFLICTS @@ -452,7 +452,7 @@ export class IndexPattern implements IIndexPattern { // and ensure we ignore the key if the server response // is the same as the original response (since that is expected // if we made a change in that key) - const serverChangedKeys = Object.keys(updatedBody).filter(key => { + const serverChangedKeys = Object.keys(updatedBody).filter((key) => { return updatedBody[key] !== body[key] && this.originalBody[key] !== updatedBody[key]; }); @@ -479,7 +479,7 @@ export class IndexPattern implements IIndexPattern { } // Set the updated response on this object - serverChangedKeys.forEach(key => { + serverChangedKeys.forEach((key) => { this[key] = samePattern[key]; }); this.version = samePattern.version; @@ -505,7 +505,7 @@ export class IndexPattern implements IIndexPattern { refreshFields() { return this._fetchFields() .then(() => this.save()) - .catch(err => { + .catch((err) => { // https://github.com/elastic/kibana/issues/9224 // This call will attempt to remap fields from the matching // ES index which may not actually exist. In that scenario, diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts index 515f2e7cf95ee..32b31d4f2758d 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts @@ -100,7 +100,7 @@ export class IndexPatternsService { if (!this.savedObjectsCache) { return []; } - return this.savedObjectsCache.map(obj => obj?.id); + return this.savedObjectsCache.map((obj) => obj?.id); }; getTitles = async (refresh: boolean = false): Promise => { @@ -110,7 +110,7 @@ export class IndexPatternsService { if (!this.savedObjectsCache) { return []; } - return this.savedObjectsCache.map(obj => obj?.attributes?.title); + return this.savedObjectsCache.map((obj) => obj?.attributes?.title); }; getFields = async (fields: IndexPatternCachedFieldType[], refresh: boolean = false) => { diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts index 2d3e357e96819..51f4fc7ce94b9 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts @@ -19,7 +19,7 @@ import { setup } from 'test_utils/http_test_setup'; -export const { http } = setup(injectedMetadata => { +export const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue('/hola/daro/'); }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts index 0dca025b2bf38..37ee80c2c29e4 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts @@ -29,7 +29,7 @@ describe('IndexPatternsApiClient', () => { indexPatternsApiClient = new IndexPatternsApiClient(http); }); - test('uses the right URI to fetch fields for time patterns', async function() { + test('uses the right URI to fetch fields for time patterns', async function () { const expectedPath = '/api/index_patterns/_fields_for_time_pattern'; await indexPatternsApiClient.getFieldsForTimePattern(); @@ -37,7 +37,7 @@ describe('IndexPatternsApiClient', () => { expect(fetchSpy).toHaveBeenCalledWith(expectedPath, expect.any(Object)); }); - test('uses the right URI to fetch fields for wildcard', async function() { + test('uses the right URI to fetch fields for wildcard', async function () { const expectedPath = '/api/index_patterns/_fields_for_wildcard'; await indexPatternsApiClient.getFieldsForWildcard(); @@ -45,7 +45,7 @@ describe('IndexPatternsApiClient', () => { expect(fetchSpy).toHaveBeenCalledWith(expectedPath, expect.any(Object)); }); - test('uses the right URI to fetch fields for wildcard given a type', async function() { + test('uses the right URI to fetch fields for wildcard given a type', async function () { const expectedPath = '/api/index_patterns/rollup/_fields_for_wildcard'; await indexPatternsApiClient.getFieldsForWildcard({ type: 'rollup' }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts index 0007d1780c25b..cd189ccf0135b 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts @@ -54,13 +54,7 @@ export class IndexPatternsApiClient { } _getUrl(path: string[]) { - return ( - API_BASE_URL + - path - .filter(Boolean) - .map(encodeURIComponent) - .join('/') - ); + return API_BASE_URL + path.filter(Boolean).map(encodeURIComponent).join('/'); } getFieldsForTimePattern(options: GetFieldsOptions = {}) { diff --git a/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts b/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts index 74e420ffeb5c0..87a702b3a012d 100644 --- a/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts @@ -29,7 +29,7 @@ describe('Index Pattern Utils', () => { }); it('should not allow illegal characters', () => { - ILLEGAL_CHARACTERS_VISIBLE.forEach(char => { + ILLEGAL_CHARACTERS_VISIBLE.forEach((char) => { const errors = validateIndexPattern(`pattern${char}`); expect(errors[ILLEGAL_CHARACTERS_KEY]).toEqual([char]); }); diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts index 3b4ca08cbbf14..3c69a498e74cd 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts @@ -154,7 +154,7 @@ describe('filter_manager', () => { expect(updateListener.callCount).toBe(2); }); - test('changing a disabled filter should fire only update event', async function() { + test('changing a disabled filter should fire only update event', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); const f1 = getFilter(FilterStateStore.GLOBAL_STATE, true, false, 'age', 34); @@ -178,7 +178,7 @@ describe('filter_manager', () => { expect(updateStub).toBeCalledTimes(1); }); - test('should merge multiple conflicting app filters', async function() { + test('should merge multiple conflicting app filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter1 = _.cloneDeep(readyFilters[1]); appFilter1.meta.negate = true; @@ -198,13 +198,13 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; }).length ).toBe(3); }); - test('should set app filters and merge them with duplicate global filters', async function() { + test('should set app filters and merge them with duplicate global filters', async function () { const [filter, ...otherFilters] = readyFilters; filterManager.addFilters(otherFilters, true); const appFilter1 = _.cloneDeep(readyFilters[1]); @@ -219,7 +219,7 @@ describe('filter_manager', () => { expect(newAppFilters).toHaveLength(1); }); - test('should set global filters and remove any duplicated app filters', async function() { + test('should set global filters and remove any duplicated app filters', async function () { filterManager.addFilters(readyFilters, false); const globalFilter1 = _.cloneDeep(readyFilters[1]); const globalFilter2 = _.cloneDeep(readyFilters[2]); @@ -273,7 +273,7 @@ describe('filter_manager', () => { }); describe('add filters', () => { - test('app state should accept a single filter', async function() { + test('app state should accept a single filter', async function () { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.addFilters(f1); @@ -398,7 +398,7 @@ describe('filter_manager', () => { } }); - test('should return app and global filters', async function() { + test('should return app and global filters', async function () { const filters = getFiltersArray(); filterManager.addFilters(filters[0], false); filterManager.addFilters(filters[1], true); @@ -421,7 +421,7 @@ describe('filter_manager', () => { expect(res).toHaveLength(3); }); - test('should skip appStateStub filters that match globalStateStub filters', async function() { + test('should skip appStateStub filters that match globalStateStub filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(appFilter, false); @@ -429,12 +429,12 @@ describe('filter_manager', () => { // global filters should be listed first const res = filterManager.getFilters(); expect(res).toHaveLength(3); - _.each(res, function(filter) { + _.each(res, function (filter) { expect(filter.$state && filter.$state.store).toBe(FilterStateStore.GLOBAL_STATE); }); }); - test('should allow overwriting a positive filter by a negated one', async function() { + test('should allow overwriting a positive filter by a negated one', async function () { // Add negate: false version of the filter const filter = _.cloneDeep(readyFilters[0]); filter.meta.negate = false; @@ -453,7 +453,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()[0]).toEqual(negatedFilter); }); - test('should allow overwriting a negated filter by a positive one', async function() { + test('should allow overwriting a negated filter by a positive one', async function () { // Add negate: true version of the same filter const negatedFilter = _.cloneDeep(readyFilters[0]); negatedFilter.meta.negate = true; @@ -473,7 +473,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()[0]).toEqual(filter); }); - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); @@ -493,8 +493,8 @@ describe('filter_manager', () => { }); }); - describe('filter reconciliation', function() { - test('should de-dupe app filters being added', async function() { + describe('filter reconciliation', function () { + test('should de-dupe app filters being added', async function () { const newFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(readyFilters, false); expect(filterManager.getFilters()).toHaveLength(3); @@ -503,7 +503,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(3); }); - test('should de-dupe global filters being added', async function() { + test('should de-dupe global filters being added', async function () { const newFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(readyFilters, true); expect(filterManager.getFilters()).toHaveLength(3); @@ -530,7 +530,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(1); }); - test('should mutate global filters on appStateStub filter changes', async function() { + test('should mutate global filters on appStateStub filter changes', async function () { const idx = 1; filterManager.addFilters(readyFilters, true); @@ -542,14 +542,14 @@ describe('filter_manager', () => { filterManager.addFilters(appFilter); const res = filterManager.getFilters(); expect(res).toHaveLength(3); - _.each(res, function(filter, i) { + _.each(res, function (filter, i) { expect(filter.$state && filter.$state.store).toBe('globalState'); // make sure global filter actually mutated expect(filter.meta.negate).toBe(i === idx); }); }); - test('should merge conflicting app filters', async function() { + test('should merge conflicting app filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter = _.cloneDeep(readyFilters[1]); appFilter.meta.negate = true; @@ -562,15 +562,15 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; }).length ).toBe(3); }); - test('should enable disabled filters - global state', async function() { + test('should enable disabled filters - global state', async function () { // test adding to globalStateStub - const disabledFilters = _.map(readyFilters, function(filter) { + const disabledFilters = _.map(readyFilters, function (filter) { const f = _.cloneDeep(filter); f.meta.disabled = true; return f; @@ -581,15 +581,15 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.meta.disabled === false; }).length ).toBe(3); }); - test('should enable disabled filters - app state', async function() { + test('should enable disabled filters - app state', async function () { // test adding to appStateStub - const disabledFilters = _.map(readyFilters, function(filter) { + const disabledFilters = _.map(readyFilters, function (filter) { const f = _.cloneDeep(filter); f.meta.disabled = true; return f; @@ -600,7 +600,7 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.meta.disabled === false; }).length ).toBe(3); @@ -652,21 +652,21 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(2); }); - test('should remove the filter from appStateStub', async function() { + test('should remove the filter from appStateStub', async function () { filterManager.addFilters(readyFilters, false); expect(filterManager.getAppFilters()).toHaveLength(3); filterManager.removeFilter(readyFilters[0]); expect(filterManager.getAppFilters()).toHaveLength(2); }); - test('should remove the filter from globalStateStub', async function() { + test('should remove the filter from globalStateStub', async function () { filterManager.addFilters(readyFilters, true); expect(filterManager.getGlobalFilters()).toHaveLength(3); filterManager.removeFilter(readyFilters[0]); expect(filterManager.getGlobalFilters()).toHaveLength(2); }); - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); @@ -687,7 +687,7 @@ describe('filter_manager', () => { expect(updateStub).toBeCalledTimes(1); }); - test('should remove matching filters', async function() { + test('should remove matching filters', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -697,7 +697,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(1); }); - test('should remove matching filters by comparison', async function() { + test('should remove matching filters by comparison', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -711,7 +711,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(1); }); - test('should do nothing with a non-matching filter', async function() { + test('should do nothing with a non-matching filter', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -723,7 +723,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(2); }); - test('should remove all the filters from both states', async function() { + test('should remove all the filters from both states', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); expect(filterManager.getAppFilters()).toHaveLength(1); @@ -736,7 +736,7 @@ describe('filter_manager', () => { }); describe('invert', () => { - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { filterManager.addFilters(readyFilters); expect(filterManager.getFilters()).toHaveLength(3); diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.ts b/src/plugins/data/public/query/filter_manager/filter_manager.ts index e206286bce147..d58a0eb45c04f 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.ts @@ -53,8 +53,8 @@ export class FilterManager { // existing globalFilters should be mutated by appFilters // ignore original appFilters which are already inside globalFilters const cleanedAppFilters: Filter[] = []; - _.each(appFilters, function(filter, i) { - const match = _.find(globalFilters, function(globalFilter) { + _.each(appFilters, function (filter, i) { + const match = _.find(globalFilters, function (globalFilter) { return compareFilters(globalFilter, filter); }); @@ -203,7 +203,7 @@ export class FilterManager { } public removeFilter(filter: Filter) { - const filterIndex = _.findIndex(this.filters, item => { + const filterIndex = _.findIndex(this.filters, (item) => { return _.isEqual(item.meta, filter.meta) && _.isEqual(item.query, filter.query); }); diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts b/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts index 4220df7b1a49b..432a763bfd48c 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts @@ -39,7 +39,7 @@ function getExistingFilter( value: any ): Filter | undefined { // TODO: On array fields, negating does not negate the combination, rather all terms - return _.find(appFilters, function(filter) { + return _.find(appFilters, function (filter) { if (!filter) return; if (fieldName === '_exists_' && isExistsFilter(filter)) { @@ -95,7 +95,7 @@ export function generateFilters( const negate = operation === '-'; let filter; - _.each(values, function(value) { + _.each(values, function (value) { const existing = getExistingFilter(appFilters, fieldName, value); if (existing) { diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts index 8322e79dd67d1..780db36426dc1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts @@ -97,7 +97,7 @@ describe('filter manager utilities', () => { expect(result).toEqual({ key: 'test', value: 'example' }); }); - test('should throw an error if no functions match', async done => { + test('should throw an error if no functions match', async (done) => { const filter = buildEmptyFilter(true); mapping.throws(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts index f75970d4dec18..35d2f2b7b294e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts @@ -77,7 +77,7 @@ describe('filter manager utilities', () => { expect(after.meta).toHaveProperty('negate', false); }); - test('should finish with a catch', async done => { + test('should finish with a catch', async (done) => { const before: any = { meta: { index: 'logstash-*' } }; try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts index c90c056f4eb35..b5715e33a4677 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts @@ -22,7 +22,7 @@ import { Filter, FILTERS } from '../../../../../common'; export const mapDefault = (filter: Filter) => { const metaProperty = /(^\$|meta)/; - const key = find(keys(filter), item => !item.match(metaProperty)); + const key = find(keys(filter), (item) => !item.match(metaProperty)); if (key) { const type = FILTERS.CUSTOM; diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts index 83c39e449d3ea..0e7b12b6f5f58 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts @@ -44,7 +44,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'exists'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts index 97f275b05a520..035dadfd7432a 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts @@ -79,7 +79,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts index f32c459baee5d..c66e65f00efbd 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts @@ -41,7 +41,7 @@ const getFormattedValueFn = (params: any) => { }; const getParams = (filter: GeoBoundingBoxFilter) => { - const key = Object.keys(filter.geo_bounding_box).filter(k => k !== 'ignore_unmapped')[0]; + const key = Object.keys(filter.geo_bounding_box).filter((k) => k !== 'ignore_unmapped')[0]; const params = filter.geo_bounding_box[key]; return { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts index 4af881aa58542..8da98b3a329d6 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts @@ -70,7 +70,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const wrongFilter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts index df5379289dd28..55f744558942a 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts @@ -36,7 +36,7 @@ const getFormattedValueFn = (points: string[]) => { }; function getParams(filter: GeoPolygonFilter) { - const key = Object.keys(filter.geo_polygon).filter(k => k !== 'ignore_unmapped')[0]; + const key = Object.keys(filter.geo_polygon).filter((k) => k !== 'ignore_unmapped')[0]; const params = filter.geo_polygon[key]; return { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts index b22583ff8bb24..3d50b87bb32f8 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts @@ -38,7 +38,7 @@ describe('filter_manager/lib', () => { }); describe('when given a filter that is not match_all', () => { - test('filter is rejected', async done => { + test('filter is rejected', async (done) => { delete filter.match_all; try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts index 67e5987818fb5..d851e96ad6ac6 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts @@ -33,7 +33,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'missing'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts index 5dd10ce30111f..8f4a8d1bb35a1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts @@ -38,7 +38,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts index 0589215955562..9b75d5a769d3e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts @@ -30,7 +30,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'foo:bar'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts index c8868b412707b..a6f587ddc7d32 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts @@ -37,7 +37,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts index aee1bf257be01..5e58b2c14c262 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts @@ -65,7 +65,7 @@ describe('mapSpatialFilter()', () => { expect(result).toHaveProperty('type', FILTERS.SPATIAL_FILTER); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { key: 'location', diff --git a/src/plugins/data/public/query/lib/from_user.test.ts b/src/plugins/data/public/query/lib/from_user.test.ts index b74a1a07dc356..208558bb138c6 100644 --- a/src/plugins/data/public/query/lib/from_user.test.ts +++ b/src/plugins/data/public/query/lib/from_user.test.ts @@ -19,23 +19,23 @@ import { fromUser } from '../'; -describe('user input helpers', function() { - describe('user input parser', function() { - it('should return the input if passed an object', function() { +describe('user input helpers', function () { + describe('user input parser', function () { + it('should return the input if passed an object', function () { expect(fromUser({ foo: 'bar' })).toEqual({ foo: 'bar' }); }); - it('unless the object is empty, then convert it to an empty string', function() { + it('unless the object is empty, then convert it to an empty string', function () { expect(fromUser({})).toEqual(''); }); - it('should pass through input strings that not start with {', function() { + it('should pass through input strings that not start with {', function () { expect(fromUser('foo')).toEqual('foo'); expect(fromUser('400')).toEqual('400'); expect(fromUser('true')).toEqual('true'); }); - it('should parse valid JSON and return the object instead of a string', function() { + it('should parse valid JSON and return the object instead of a string', function () { expect(fromUser('{}')).toEqual({}); // invalid json remains a string diff --git a/src/plugins/data/public/query/lib/match_pairs.ts b/src/plugins/data/public/query/lib/match_pairs.ts index d5cfb4f99c9d5..ce8b5f17644e7 100644 --- a/src/plugins/data/public/query/lib/match_pairs.ts +++ b/src/plugins/data/public/query/lib/match_pairs.ts @@ -31,8 +31,8 @@ */ const pairs = ['()', '[]', '{}', `''`, '""']; -const openers = pairs.map(pair => pair[0]); -const closers = pairs.map(pair => pair[1]); +const openers = pairs.map((pair) => pair[0]); +const closers = pairs.map((pair) => pair[1]); interface MatchPairsOptions { value: string; diff --git a/src/plugins/data/public/query/persisted_log/persisted_log.ts b/src/plugins/data/public/query/persisted_log/persisted_log.ts index 553b0bf5ef7e0..f61315b85b195 100644 --- a/src/plugins/data/public/query/persisted_log/persisted_log.ts +++ b/src/plugins/data/public/query/persisted_log/persisted_log.ts @@ -64,7 +64,7 @@ export class PersistedLog { // remove any matching items from the stack if option is set if (this.filterDuplicates) { - _.remove(this.items, item => { + _.remove(this.items, (item) => { return this.isDuplicate(item, val); }); } diff --git a/src/plugins/data/public/query/saved_query/saved_query_service.test.ts b/src/plugins/data/public/query/saved_query/saved_query_service.test.ts index a86a5b4ed401e..584eb01f44457 100644 --- a/src/plugins/data/public/query/saved_query/saved_query_service.test.ts +++ b/src/plugins/data/public/query/saved_query/saved_query_service.test.ts @@ -89,7 +89,7 @@ describe('saved query service', () => { mockSavedObjectsClient.delete.mockReset(); }); - describe('saveQuery', function() { + describe('saveQuery', function () { it('should create a saved object for the given attributes', async () => { mockSavedObjectsClient.create.mockReturnValue({ id: 'foo', @@ -165,7 +165,7 @@ describe('saved query service', () => { expect(error).not.toBe(null); }); }); - describe('findSavedQueries', function() { + describe('findSavedQueries', function () { it('should find and return saved queries without search text or pagination parameters', async () => { mockSavedObjectsClient.find.mockReturnValue({ savedObjects: [{ id: 'foo', attributes: savedQueryAttributes }], @@ -276,7 +276,7 @@ describe('saved query service', () => { }); }); - describe('getSavedQuery', function() { + describe('getSavedQuery', function () { it('should retrieve a saved query by id', async () => { mockSavedObjectsClient.get.mockReturnValue({ id: 'foo', attributes: savedQueryAttributes }); @@ -291,14 +291,14 @@ describe('saved query service', () => { }); }); - describe('deleteSavedQuery', function() { + describe('deleteSavedQuery', function () { it('should delete the saved query for the given ID', async () => { await deleteSavedQuery('foo'); expect(mockSavedObjectsClient.delete).toHaveBeenCalledWith('query', 'foo'); }); }); - describe('getAllSavedQueries', function() { + describe('getAllSavedQueries', function () { it('should return all the saved queries', async () => { mockSavedObjectsClient.find.mockReturnValue({ savedObjects: [{ id: 'foo', attributes: savedQueryAttributes }], @@ -324,7 +324,7 @@ describe('saved query service', () => { }); }); - describe('getSavedQueryCount', function() { + describe('getSavedQueryCount', function () { it('should return the total number of saved queries', async () => { mockSavedObjectsClient.find.mockReturnValue({ total: 1, diff --git a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts index 3256c1cbd65a1..e74497a5053b4 100644 --- a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts +++ b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts @@ -125,7 +125,7 @@ export const connectToQueryState = ( .pipe( filter(({ changes, state }) => { if (updateInProgress) return false; - return syncKeys.some(syncKey => changes[syncKey]); + return syncKeys.some((syncKey) => changes[syncKey]); }), map(({ changes }) => { const newState: QueryState = {}; @@ -150,10 +150,10 @@ export const connectToQueryState = ( return newState; }) ) - .subscribe(newState => { + .subscribe((newState) => { stateContainer.set({ ...stateContainer.get(), ...newState }); }), - stateContainer.state$.subscribe(state => { + stateContainer.state$.subscribe((state) => { updateInProgress = true; // cloneDeep is required because services are mutating passed objects @@ -204,6 +204,6 @@ export const connectToQueryState = ( ]; return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); }; }; diff --git a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts index dd075f9be7d94..87032925294c6 100644 --- a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts +++ b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts @@ -32,7 +32,7 @@ export function createQueryStateObservable({ timefilter: TimefilterSetup; filterManager: FilterManager; }): Observable<{ changes: QueryStateChange; state: QueryState }> { - return new Observable(subscriber => { + return new Observable((subscriber) => { const state = createStateContainer({ time: timefilter.getTime(), refreshInterval: timefilter.getRefreshInterval(), @@ -53,8 +53,8 @@ export function createQueryStateObservable({ currentChange.filters = true; const { filters } = state.get(); - const globalOld = filters?.filter(f => isFilterPinned(f)); - const appOld = filters?.filter(f => !isFilterPinned(f)); + const globalOld = filters?.filter((f) => isFilterPinned(f)); + const appOld = filters?.filter((f) => !isFilterPinned(f)); const globalNew = filterManager.getGlobalFilters(); const appNew = filterManager.getAppFilters(); @@ -73,7 +73,7 @@ export function createQueryStateObservable({ }), state.state$ .pipe( - map(newState => ({ state: newState, changes: currentChange })), + map((newState) => ({ state: newState, changes: currentChange })), tap(() => { currentChange = {}; }) @@ -81,7 +81,7 @@ export function createQueryStateObservable({ .subscribe(subscriber), ]; return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); }; }); } diff --git a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts index 77e5b0ab02dc1..4d3da7b9313a3 100644 --- a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts +++ b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts @@ -84,7 +84,7 @@ export const syncQueryStateWithUrl = ( stateStorage: kbnUrlStateStorage, stateContainer: { ...globalQueryStateContainer, - set: state => { + set: (state) => { if (state) { // syncState utils requires to handle incoming "null" value globalQueryStateContainer.set(state); diff --git a/src/plugins/data/public/query/timefilter/get_time.ts b/src/plugins/data/public/query/timefilter/get_time.ts index 9cdd25d3213ce..3706972ce4a2e 100644 --- a/src/plugins/data/public/query/timefilter/get_time.ts +++ b/src/plugins/data/public/query/timefilter/get_time.ts @@ -54,7 +54,9 @@ function createTimeRangeFilter( if (!indexPattern) { return; } - const field = indexPattern.fields.find(f => f.name === (fieldName || indexPattern.timeFieldName)); + const field = indexPattern.fields.find( + (f) => f.name === (fieldName || indexPattern.timeFieldName) + ); if (!field) { return; } diff --git a/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts b/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts index 850c87635be9c..3a9402209be20 100644 --- a/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts +++ b/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts @@ -22,7 +22,7 @@ import _ from 'lodash'; import { RefreshInterval } from '../../../../common'; import { InputTimeRange } from '../types'; -const valueOf = function(o: any) { +const valueOf = function (o: any) { if (o) return o.valueOf(); }; diff --git a/src/plugins/data/public/search/aggs/agg_config.test.ts b/src/plugins/data/public/search/aggs/agg_config.test.ts index b5df90313230c..6a0dad07b69bb 100644 --- a/src/plugins/data/public/search/aggs/agg_config.test.ts +++ b/src/plugins/data/public/search/aggs/agg_config.test.ts @@ -375,7 +375,7 @@ describe('AggConfig', () => { fieldFormats.getDefaultInstance = (() => ({ getConverterFor: (t?: string) => t || identity, })) as any; - indexPattern.fields.getByName = name => + indexPattern.fields.getByName = (name) => ({ format: { getConverterFor: (t?: string) => t || identity, @@ -500,7 +500,7 @@ describe('AggConfig', () => { // Overwrite the `ranges` param in the `range` agg with a mock toExpressionAst function const range: MetricAggType = typesRegistry.get('range'); range.expressionName = 'aggRange'; - const rangesParam = range.params.find(p => p.name === 'ranges'); + const rangesParam = range.params.find((p) => p.name === 'ranges'); rangesParam!.toExpressionAst = (val: any) => ({ type: 'function', function: 'aggRanges', @@ -623,7 +623,7 @@ describe('AggConfig', () => { fieldFormats.getDefaultInstance = (() => ({ getConverterFor: (t?: string) => t || identity, })) as any; - indexPattern.fields.getByName = name => + indexPattern.fields.getByName = (name) => ({ format: { getConverterFor: (t?: string) => t || identity, @@ -649,10 +649,7 @@ describe('AggConfig', () => { }, }; expect(aggConfig.fieldFormatter().toString()).toBe( - aggConfig - .getField() - .format.getConverterFor() - .toString() + aggConfig.getField().format.getConverterFor().toString() ); }); diff --git a/src/plugins/data/public/search/aggs/agg_config.ts b/src/plugins/data/public/search/aggs/agg_config.ts index 86a2c3e0e82e4..ee4116eefc0e2 100644 --- a/src/plugins/data/public/search/aggs/agg_config.ts +++ b/src/plugins/data/public/search/aggs/agg_config.ts @@ -75,12 +75,12 @@ export class AggConfig { static ensureIds(list: any[]) { const have: IAggConfig[] = []; const haveNot: AggConfigOptions[] = []; - list.forEach(function(obj) { + list.forEach(function (obj) { (obj.id ? have : haveNot).push(obj); }); let nextId = AggConfig.nextId(have); - haveNot.forEach(function(obj) { + haveNot.forEach(function (obj) { obj.id = String(nextId++); }); @@ -95,7 +95,7 @@ export class AggConfig { static nextId(list: IAggConfig[]) { return ( 1 + - list.reduce(function(max, obj) { + list.reduce(function (max, obj) { return Math.max(max, +obj.id || 0); }, 0) ); @@ -154,7 +154,7 @@ export class AggConfig { from = from || this.params || {}; const to = (this.params = {} as any); - this.getAggParams().forEach(aggParam => { + this.getAggParams().forEach((aggParam) => { let val = from[aggParam.name]; if (val == null) { @@ -323,7 +323,7 @@ export class AggConfig { // Go through each of the params and convert to an array of expression args. const params = Object.entries(rest.params).reduce((acc, [key, value]) => { - const deserializedParam = this.getAggParams().find(p => p.name === key); + const deserializedParam = this.getAggParams().find((p) => p.name === key); if (deserializedParam && deserializedParam.toExpressionAst) { // If the param provides `toExpressionAst`, we call it with the value @@ -454,7 +454,7 @@ export class AggConfig { if (this.__typeDecorations) { _.forOwn( this.__typeDecorations, - function(prop, name: string | undefined) { + function (prop, name: string | undefined) { // @ts-ignore delete this[name]; }, diff --git a/src/plugins/data/public/search/aggs/agg_configs.test.ts b/src/plugins/data/public/search/aggs/agg_configs.test.ts index 653bf6a266df6..6e6fb3350d901 100644 --- a/src/plugins/data/public/search/aggs/agg_configs.test.ts +++ b/src/plugins/data/public/search/aggs/agg_configs.test.ts @@ -172,7 +172,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getRequestAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.histogram); @@ -195,7 +195,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.date_histogram); @@ -212,7 +212,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.date_histogram); @@ -226,7 +226,7 @@ describe('AggConfigs', () => { describe('#toDsl', () => { beforeEach(() => { indexPattern = stubIndexPattern as IndexPattern; - indexPattern.fields.getByName = name => (name as unknown) as IndexPatternField; + indexPattern.fields.getByName = (name) => (name as unknown) as IndexPatternField; }); it('uses the sorted aggs', () => { @@ -250,7 +250,7 @@ describe('AggConfigs', () => { fieldFormats, }); - const aggInfos = ac.aggs.map(aggConfig => { + const aggInfos = ac.aggs.map((aggConfig) => { const football = {}; aggConfig.toDsl = jest.fn().mockImplementation(() => football); @@ -328,7 +328,7 @@ describe('AggConfigs', () => { expect(typeof dsl[histo.id]).toBe('object'); expect(dsl[histo.id]).toHaveProperty('aggs'); - metrics.forEach(metric => { + metrics.forEach((metric) => { expect(dsl[histo.id].aggs).toHaveProperty(metric.id); expect(dsl[histo.id].aggs[metric.id]).not.toHaveProperty('aggs'); }); diff --git a/src/plugins/data/public/search/aggs/agg_configs.ts b/src/plugins/data/public/search/aggs/agg_configs.ts index d2151a2c5ed4d..6cc03be292d7b 100644 --- a/src/plugins/data/public/search/aggs/agg_configs.ts +++ b/src/plugins/data/public/search/aggs/agg_configs.ts @@ -95,7 +95,7 @@ export class AggConfigs { this.timeRange = timeRange; const updateAggTimeRange = (agg: AggConfig) => { - _.each(agg.params, param => { + _.each(agg.params, (param) => { if (param instanceof AggConfig) { updateAggTimeRange(param); } @@ -176,10 +176,10 @@ export class AggConfigs { if (hierarchical) { // collect all metrics, and filter out the ones that we won't be copying nestedMetrics = this.aggs - .filter(function(agg) { + .filter(function (agg) { return agg.type.type === 'metrics' && agg.type.name !== 'count'; }) - .map(agg => { + .map((agg) => { return { config: agg, dsl: agg.toDsl(this), @@ -239,15 +239,15 @@ export class AggConfigs { } byId(id: string) { - return this.aggs.find(agg => agg.id === id); + return this.aggs.find((agg) => agg.id === id); } byName(name: string) { - return this.aggs.filter(agg => agg.type?.name === name); + return this.aggs.filter((agg) => agg.type?.name === name); } byType(type: string) { - return this.aggs.filter(agg => agg.type?.type === type); + return this.aggs.filter((agg) => agg.type?.type === type); } byTypeName(type: string) { @@ -255,13 +255,13 @@ export class AggConfigs { } bySchemaName(schema: string) { - return this.aggs.filter(agg => agg.schema === schema); + return this.aggs.filter((agg) => agg.schema === schema); } getRequestAggs(): AggConfig[] { // collect all the aggregations const aggregations = this.aggs - .filter(agg => agg.enabled && agg.type) + .filter((agg) => agg.enabled && agg.type) .reduce((requestValuesAggs, agg: AggConfig) => { const aggs = agg.getRequestAggs(); return aggs ? requestValuesAggs.concat(aggs) : requestValuesAggs; @@ -288,7 +288,7 @@ export class AggConfigs { * @return {array[AggConfig]} */ getResponseAggs(): AggConfig[] { - return this.getRequestAggs().reduce(function(responseValuesAggs, agg: AggConfig) { + return this.getRequestAggs().reduce(function (responseValuesAggs, agg: AggConfig) { const aggs = agg.getResponseAggs(); return aggs ? responseValuesAggs.concat(aggs) : responseValuesAggs; }, [] as AggConfig[]); @@ -303,7 +303,7 @@ export class AggConfigs { */ getResponseAggById(id: string): AggConfig | undefined { id = String(id); - const reqAgg = _.find(this.getRequestAggs(), function(agg: AggConfig) { + const reqAgg = _.find(this.getRequestAggs(), function (agg: AggConfig) { return id.substr(0, String(agg.id).length) === agg.id; }); if (!reqAgg) return; diff --git a/src/plugins/data/public/search/aggs/agg_params.test.ts b/src/plugins/data/public/search/aggs/agg_params.test.ts index e116bdca157ff..997027fe88e82 100644 --- a/src/plugins/data/public/search/aggs/agg_params.test.ts +++ b/src/plugins/data/public/search/aggs/agg_params.test.ts @@ -68,7 +68,7 @@ describe('AggParams class', () => { expect(aggParams[0] instanceof OptionedParamType).toBeTruthy(); }); - it('Always converts the params to a BaseParamType', function() { + it('Always converts the params to a BaseParamType', function () { const params = [ { name: 'height', @@ -88,7 +88,7 @@ describe('AggParams class', () => { expect(aggParams).toHaveLength(params.length); - aggParams.forEach(aggParam => expect(aggParam instanceof BaseParamType).toBeTruthy()); + aggParams.forEach((aggParam) => expect(aggParam instanceof BaseParamType).toBeTruthy()); }); }); }); diff --git a/src/plugins/data/public/search/aggs/agg_params.ts b/src/plugins/data/public/search/aggs/agg_params.ts index e7b2f72bae656..4f7bec30fa27d 100644 --- a/src/plugins/data/public/search/aggs/agg_params.ts +++ b/src/plugins/data/public/search/aggs/agg_params.ts @@ -83,7 +83,7 @@ export const writeParams = < }; locals = locals || {}; - params.forEach(param => { + params.forEach((param) => { if (param.write) { param.write(aggConfig, output, aggs, locals); } else { diff --git a/src/plugins/data/public/search/aggs/agg_type.test.ts b/src/plugins/data/public/search/aggs/agg_type.test.ts index 369ae0ce0b3a5..18783bbd9a760 100644 --- a/src/plugins/data/public/search/aggs/agg_type.test.ts +++ b/src/plugins/data/public/search/aggs/agg_type.test.ts @@ -159,7 +159,7 @@ describe('AggType Class', () => { }); }); - describe('getFormat', function() { + describe('getFormat', function () { let aggConfig: IAggConfig; let field: any; diff --git a/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts b/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts index abda6b5fc5980..fba3d35f002af 100644 --- a/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts +++ b/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts @@ -65,7 +65,7 @@ const getAggResultBuckets = ( for (let aggId = 0; aggId < responseAggs.length; aggId++) { const aggById = responseAggs[aggId]; const aggKey = keys(responseAgg)[aggId]; - const aggConfig = find(aggConfigs.aggs, agg => agg.id === aggKey); + const aggConfig = find(aggConfigs.aggs, (agg) => agg.id === aggKey); if (aggConfig) { const aggResultBucket = find(aggById.buckets, (bucket, bucketObjKey) => { const bucketKey = aggConfig @@ -102,9 +102,9 @@ const getAggConfigResultMissingBuckets = (responseAggs: any, aggId: string) => { if (matchingBucket) resultBuckets.push(matchingBucket); return resultBuckets; } - each(responseAggs, agg => { + each(responseAggs, (agg) => { if (agg.buckets) { - each(agg.buckets, bucket => { + each(agg.buckets, (bucket) => { resultBuckets = [...resultBuckets, ...getAggConfigResultMissingBuckets(bucket, aggId)]; }); } @@ -137,8 +137,8 @@ export const buildOtherBucketAgg = ( aggWithOtherBucket: IBucketAggConfig, response: any ) => { - const bucketAggs = aggConfigs.aggs.filter(agg => agg.type.type === AggGroupNames.Buckets); - const index = bucketAggs.findIndex(agg => agg.id === aggWithOtherBucket.id); + const bucketAggs = aggConfigs.aggs.filter((agg) => agg.type.type === AggGroupNames.Buckets); + const index = bucketAggs.findIndex((agg) => agg.id === aggWithOtherBucket.id); const aggs = aggConfigs.toDsl(); const indexPattern = aggWithOtherBucket.params.field.indexPattern; @@ -215,7 +215,7 @@ export const buildOtherBucketAgg = ( } // create not filters for all the buckets - each(agg.buckets, bucket => { + each(agg.buckets, (bucket) => { if (bucket.key === '__missing__') return; const filter = currentAgg.createFilter(bucket.key); filter.meta.negate = true; @@ -289,7 +289,7 @@ export const updateMissingBucket = ( ) => { const updatedResponse = cloneDeep(response); const aggResultBuckets = getAggConfigResultMissingBuckets(updatedResponse.aggregations, agg.id); - aggResultBuckets.forEach(bucket => { + aggResultBuckets.forEach((bucket) => { bucket.key = '__missing__'; }); return updatedResponse; diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts index bb73c8a39df19..2f03b8ec67112 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts @@ -121,7 +121,7 @@ describe('AggConfig Filters', () => { }); test('extends the filter edge to 1ms before the next bucket for all interval options', () => { - intervalOptions.forEach(option => { + intervalOptions.forEach((option) => { let duration; if (option.val !== 'custom' && moment(1, option.val).isValid()) { // @ts-ignore @@ -137,12 +137,7 @@ describe('AggConfig Filters', () => { const params = filter.range[field.name]; expect(params.gte).toBe(bucketStart.toISOString()); - expect(params.lt).toBe( - bucketStart - .clone() - .add(interval) - .toISOString() - ); + expect(params.lt).toBe(bucketStart.clone().add(interval).toISOString()); }); }); }); diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts index 219bb5440c8da..d5c97d0c95c5c 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -225,7 +225,7 @@ export const getDateHistogramBucketAgg = ({ const scaleMetrics = scaleMetricValues && interval.scaled && interval.scale && interval.scale < 1; if (scaleMetrics && aggs) { - const metrics = aggs.aggs.filter(a => isMetricAggType(a.type)); + const metrics = aggs.aggs.filter((a) => isMetricAggType(a.type)); const all = every(metrics, (a: IBucketAggConfig) => { const { type } = a; @@ -275,7 +275,7 @@ export const getDateHistogramBucketAgg = ({ name: 'drop_partials', default: false, write: noop, - shouldShow: agg => { + shouldShow: (agg) => { const field = agg.params.field; return field && field.name && field.name === agg.getIndexPattern().timeFieldName; }, diff --git a/src/plugins/data/public/search/aggs/buckets/date_range.ts b/src/plugins/data/public/search/aggs/buckets/date_range.ts index 504958854cad4..447347dbfbe10 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range.ts @@ -65,7 +65,7 @@ export const getDateRangeBucketAgg = ({ TEXT_CONTEXT_TYPE, fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.DATE) ); - const DateRangeFormat = FieldFormat.from(function(range: DateRangeKey) { + const DateRangeFormat = FieldFormat.from(function (range: DateRangeKey) { return convertDateRangeToString(range, formatter); }); return new DateRangeFormat(); diff --git a/src/plugins/data/public/search/aggs/buckets/filters.ts b/src/plugins/data/public/search/aggs/buckets/filters.ts index 8654645d46a9b..3f3f13bb955c1 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters.ts @@ -75,7 +75,7 @@ export const getFiltersBucketAgg = ({ const inFilters: FilterValue[] = aggConfig.params.filters; if (!size(inFilters)) return; - inFilters.forEach(filter => { + inFilters.forEach((filter) => { const persistedLog = getQueryLog( uiSettings, new Storage(window.localStorage), @@ -87,7 +87,7 @@ export const getFiltersBucketAgg = ({ const outFilters = transform( inFilters, - function(filters, filter) { + function (filters, filter) { const input = cloneDeep(filter.input); if (!input) { diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range.ts b/src/plugins/data/public/search/aggs/buckets/ip_range.ts index 029fd864154be..10fdb2d93b56e 100644 --- a/src/plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/ip_range.ts @@ -73,7 +73,7 @@ export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketA TEXT_CONTEXT_TYPE, fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.IP) ); - const IpRangeFormat = FieldFormat.from(function(range: IpRangeKey) { + const IpRangeFormat = FieldFormat.from(function (range: IpRangeKey) { return convertIPRangeToString(range, formatter); }); return new IpRangeFormat(); diff --git a/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts b/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts index 116f8cfad60f6..47da7e59af5e0 100644 --- a/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts +++ b/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts @@ -25,7 +25,7 @@ export const isType = (...types: string[]) => { return (agg: IAggConfig): boolean => { const field = agg.params.field; - return types.some(type => field && field.type === type); + return types.some((type) => field && field.type === type); }; }; diff --git a/src/plugins/data/public/search/aggs/buckets/terms.ts b/src/plugins/data/public/search/aggs/buckets/terms.ts index 1bfc508dc3871..45a76f08ddd13 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms.ts @@ -255,7 +255,7 @@ export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDe displayName: i18n.translate('data.search.aggs.otherBucket.labelForOtherBucketLabel', { defaultMessage: 'Label for other bucket', }), - shouldShow: agg => agg.getParam('otherBucket'), + shouldShow: (agg) => agg.getParam('otherBucket'), write: noop, }, { @@ -274,7 +274,7 @@ export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDe displayName: i18n.translate('data.search.aggs.otherBucket.labelForMissingValuesLabel', { defaultMessage: 'Label for missing values', }), - shouldShow: agg => agg.getParam('missingBucket'), + shouldShow: (agg) => agg.getParam('missingBucket'), write: noop, }, { diff --git a/src/plugins/data/public/search/aggs/index.test.ts b/src/plugins/data/public/search/aggs/index.test.ts index 382c5a10c2da5..4864a8b9d013b 100644 --- a/src/plugins/data/public/search/aggs/index.test.ts +++ b/src/plugins/data/public/search/aggs/index.test.ts @@ -44,7 +44,7 @@ describe('AggTypesComponent', () => { describe('bucket aggs', () => { test('all extend BucketAggType', () => { - buckets.forEach(bucketAgg => { + buckets.forEach((bucketAgg) => { expect(isBucketAggType(bucketAgg)).toBeTruthy(); }); }); @@ -52,7 +52,7 @@ describe('AggTypesComponent', () => { describe('metric aggs', () => { test('all extend MetricAggType', () => { - metrics.forEach(metricAgg => { + metrics.forEach((metricAgg) => { expect(isMetricAggType(metricAgg)).toBeTruthy(); }); }); diff --git a/src/plugins/data/public/search/aggs/metrics/avg.ts b/src/plugins/data/public/search/aggs/metrics/avg.ts index dba18d562ec19..1aa39ccd2aad9 100644 --- a/src/plugins/data/public/search/aggs/metrics/avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/avg.ts @@ -41,7 +41,7 @@ export const getAvgMetricAgg = ({ getInternalStartServices }: AvgMetricAggDepend { name: METRIC_TYPES.AVG, title: averageTitle, - makeLabel: aggConfig => { + makeLabel: (aggConfig) => { return i18n.translate('data.search.aggs.metrics.averageLabel', { defaultMessage: 'Average {field}', values: { field: aggConfig.getFieldDisplayName() }, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts index ded17eebf465b..927e9a7ae4458 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts @@ -50,7 +50,7 @@ export const getBucketAvgMetricAgg = ({ { name: METRIC_TYPES.AVG_BUCKET, title: averageBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallAverageLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallAverageLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts index dde328008b88a..2b171fcbd24fd 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts @@ -49,7 +49,7 @@ export const getBucketMaxMetricAgg = ({ { name: METRIC_TYPES.MAX_BUCKET, title: maxBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallMaxLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallMaxLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts index 9949524ce6110..e6a523eeea374 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts @@ -49,7 +49,7 @@ export const getBucketMinMetricAgg = ({ { name: METRIC_TYPES.MIN_BUCKET, title: minBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallMinLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallMinLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts index e69ae5798c6e1..71c88596ea569 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts @@ -49,7 +49,7 @@ export const getBucketSumMetricAgg = ({ { name: METRIC_TYPES.SUM_BUCKET, title: sumBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallSumLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallSumLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/cardinality.ts b/src/plugins/data/public/search/aggs/metrics/cardinality.ts index af594195fe027..9ff3e84c38cd8 100644 --- a/src/plugins/data/public/search/aggs/metrics/cardinality.ts +++ b/src/plugins/data/public/search/aggs/metrics/cardinality.ts @@ -59,7 +59,7 @@ export const getCardinalityMetricAgg = ({ name: 'field', type: 'field', filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - type => type !== KBN_FIELD_TYPES.HISTOGRAM + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM ), }, ], diff --git a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts index 67e907239799a..44bfca1b6fb87 100644 --- a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts @@ -51,7 +51,7 @@ export const getCumulativeSumMetricAgg = ({ name: METRIC_TYPES.CUMULATIVE_SUM, title: cumulativeSumTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, cumulativeSumLabel), + makeLabel: (agg) => makeNestedLabel(agg, cumulativeSumLabel), params: [...parentPipelineAggHelper.params()], getFormat: parentPipelineAggHelper.getFormat, }, diff --git a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts index bb16cba1bee62..83656db4ac547 100644 --- a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts +++ b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts @@ -84,7 +84,7 @@ export class MetricAggType { + ((agg) => { const { fieldFormats } = dependencies.getInternalStartServices(); const field = agg.getField(); return field ? field.format : fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); diff --git a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts index 38a824629d304..1173ae5358ee7 100644 --- a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts @@ -54,7 +54,7 @@ export const getMovingAvgMetricAgg = ({ dslName: 'moving_fn', title: movingAvgTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, movingAvgLabel), + makeLabel: (agg) => makeNestedLabel(agg, movingAvgLabel), params: [ ...parentPipelineAggHelper.params(), { diff --git a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts index f386034ea8a7b..2201366cdf78b 100644 --- a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts @@ -28,7 +28,7 @@ import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { GetInternalStartServicesFn, InternalStartServices } from '../../../types'; import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -describe('parent pipeline aggs', function() { +describe('parent pipeline aggs', function () { const getInternalStartServices: GetInternalStartServicesFn = () => (({ fieldFormats: fieldFormatsServiceMock.createStartContract(), @@ -61,7 +61,7 @@ describe('parent pipeline aggs', function() { }, ]; - metrics.forEach(metric => { + metrics.forEach((metric) => { describe(`${metric.title} metric`, () => { let aggDsl: Record; let metricAgg: MetricAggType; @@ -243,7 +243,7 @@ describe('parent pipeline aggs', function() { // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; - aggConfig.type.params.forEach(param => { + aggConfig.type.params.forEach((param) => { param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); diff --git a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts index 7491f15aa3002..df52c10a82495 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts @@ -30,7 +30,7 @@ import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; import { InternalStartServices } from '../../../types'; -describe('AggTypesMetricsPercentileRanksProvider class', function() { +describe('AggTypesMetricsPercentileRanksProvider class', function () { let aggConfigs: IAggConfigs; let fieldFormats: FieldFormatsStart; let aggTypesDependencies: PercentileRanksMetricAggDependencies; @@ -78,7 +78,7 @@ describe('AggTypesMetricsPercentileRanksProvider class', function() { ); }); - it('uses the custom label if it is set', function() { + it('uses the custom label if it is set', function () { const responseAggs: any = getPercentileRanksMetricAgg(aggTypesDependencies).getResponseAggs( aggConfigs.aggs[0] as IPercentileRanksAggConfig ); diff --git a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts index fe112a50ad3c1..00bc631cefab8 100644 --- a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts +++ b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts @@ -51,7 +51,7 @@ export const getSerialDiffMetricAgg = ({ name: METRIC_TYPES.SERIAL_DIFF, title: serialDiffTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, serialDiffLabel), + makeLabel: (agg) => makeNestedLabel(agg, serialDiffLabel), params: [...parentPipelineAggHelper.params()], getFormat: parentPipelineAggHelper.getFormat, }, diff --git a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts index 5e1834d3b4935..56bd33b2b6345 100644 --- a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts @@ -61,7 +61,7 @@ describe('sibling pipeline aggs', () => { }, ]; - metrics.forEach(metric => { + metrics.forEach((metric) => { describe(`${metric.title} metric`, () => { let aggDsl: Record; let metricAgg: MetricAggType; @@ -127,7 +127,7 @@ describe('sibling pipeline aggs', () => { expect(metricAgg.makeLabel(aggConfig)).toEqual(`${metric.title} of Count`); }); - it('should set parent aggs', function() { + it('should set parent aggs', function () { init(); expect(aggDsl[metric.name].buckets_path).toBe('2-bucket>_count'); @@ -186,7 +186,7 @@ describe('sibling pipeline aggs', () => { customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; customBucket.type.params[0].modifyAggConfigOnSearchRequestStart = customBucketSpy; - aggConfig.type.params.forEach(param => { + aggConfig.type.params.forEach((param) => { param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts index 617e458cf6243..49e0a3e4b349a 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts @@ -78,7 +78,7 @@ describe('Top hit metric', () => { getByName: () => field, filter: () => [field], }, - flattenHit: jest.fn(x => x!._source), + flattenHit: jest.fn((x) => x!._source), } as any; const aggConfigs = new AggConfigs( @@ -336,7 +336,7 @@ describe('Top hit metric', () => { data: [undefined, null], result: null, }, - ].forEach(agg => { + ].forEach((agg) => { it(`should return the result of the ${agg.type} aggregation over the last doc - ${agg.description}`, () => { const bucket = { '1': { diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.ts index df7a76f151c07..c6890f98b20e4 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.ts @@ -80,7 +80,7 @@ export const getTopHitMetricAgg = ({ getInternalStartServices }: TopHitMetricAgg type: 'field', onlyAggregatable: false, filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - type => type !== KBN_FIELD_TYPES.HISTOGRAM + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM ), write(agg, output) { const field = agg.getParam('field'); @@ -230,7 +230,7 @@ export const getTopHitMetricAgg = ({ getInternalStartServices }: TopHitMetricAgg const path = agg.getParam('field').name; let values = _.flatten( - hits.map(hit => + hits.map((hit) => path === '_source' ? hit._source : agg.getIndexPattern().flattenHit(hit, true)[path] ) ); diff --git a/src/plugins/data/public/search/aggs/param_types/base.ts b/src/plugins/data/public/search/aggs/param_types/base.ts index a6f7e5adea043..79e1cf2a540d1 100644 --- a/src/plugins/data/public/search/aggs/param_types/base.ts +++ b/src/plugins/data/public/search/aggs/param_types/base.ts @@ -82,7 +82,7 @@ export class BaseParamType { this.toExpressionAst = config.toExpressionAst; this.options = config.options; this.modifyAggConfigOnSearchRequestStart = - config.modifyAggConfigOnSearchRequestStart || function() {}; + config.modifyAggConfigOnSearchRequestStart || function () {}; this.valueType = config.valueType || config.type; } } diff --git a/src/plugins/data/public/search/aggs/param_types/json.test.ts b/src/plugins/data/public/search/aggs/param_types/json.test.ts index 12fd29b3a1452..82e12d3bd5be6 100644 --- a/src/plugins/data/public/search/aggs/param_types/json.test.ts +++ b/src/plugins/data/public/search/aggs/param_types/json.test.ts @@ -21,7 +21,7 @@ import { BaseParamType } from './base'; import { JsonParamType } from './json'; import { IAggConfig } from '../agg_config'; -describe('JSON', function() { +describe('JSON', function () { const paramName = 'json_test'; let aggConfig: IAggConfig; let output: Record; @@ -33,7 +33,7 @@ describe('JSON', function() { name: paramName, }); - beforeEach(function() { + beforeEach(function () { aggConfig = { params: {} } as IAggConfig; output = { params: {} }; }); diff --git a/src/plugins/data/public/search/aggs/param_types/json.ts b/src/plugins/data/public/search/aggs/param_types/json.ts index bf85b3b890c35..461f3c300c1d3 100644 --- a/src/plugins/data/public/search/aggs/param_types/json.ts +++ b/src/plugins/data/public/search/aggs/param_types/json.ts @@ -49,7 +49,7 @@ export class JsonParamType extends BaseParamType { return _(a) .keys() .union(_.keys(b)) - .transform(function(dest, key) { + .transform(function (dest, key) { const val = compare(a[key], b[key]); if (val !== undefined) dest[key] = val; }, {}) @@ -58,7 +58,7 @@ export class JsonParamType extends BaseParamType { function mergeArrays(a: any, b: any): any { // attempt to merge each value - return _.times(Math.max(a.length, b.length), function(i) { + return _.times(Math.max(a.length, b.length), function (i) { return compare(a[i], b[i]); }); } diff --git a/src/plugins/data/public/search/aggs/param_types/string.test.ts b/src/plugins/data/public/search/aggs/param_types/string.test.ts index 29ec9741611a3..c4afe1d5d1330 100644 --- a/src/plugins/data/public/search/aggs/param_types/string.test.ts +++ b/src/plugins/data/public/search/aggs/param_types/string.test.ts @@ -21,7 +21,7 @@ import { BaseParamType } from './base'; import { StringParamType } from './string'; import { IAggConfig } from '../agg_config'; -describe('String', function() { +describe('String', function () { let paramName = 'json_test'; let aggConfig: IAggConfig; let output: Record; diff --git a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts index cb0e37c0296d7..aa27bab8f4bd8 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts @@ -34,7 +34,7 @@ import { * expression functions. */ export const functionWrapper = (spec: T) => { - const defaultArgs = mapValues(spec.args, argSpec => argSpec.default); + const defaultArgs = mapValues(spec.args, (argSpec) => argSpec.default); return ( args: T extends ExpressionFunctionDefinition< infer Name, diff --git a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts index 3ff2fbf35ad7e..5549ffd2583b1 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts @@ -45,7 +45,7 @@ export function mockAggTypesRegistry | MetricAggTyp const registrySetup = registry.setup(); if (types) { - types.forEach(type => { + types.forEach((type) => { if (type instanceof BucketAggType) { registrySetup.registerBucket(type); } else if (type instanceof MetricAggType) { @@ -68,8 +68,8 @@ export function mockAggTypesRegistry | MetricAggTyp } as unknown) as InternalStartServices), }); - aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); - aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); + aggTypes.buckets.forEach((type) => registrySetup.registerBucket(type)); + aggTypes.metrics.forEach((type) => registrySetup.registerMetric(type)); } return registry.start(); diff --git a/src/plugins/data/public/search/aggs/utils/prop_filter.ts b/src/plugins/data/public/search/aggs/utils/prop_filter.ts index 01e98a68d3949..cad5c437fc896 100644 --- a/src/plugins/data/public/search/aggs/utils/prop_filter.ts +++ b/src/plugins/data/public/search/aggs/utils/prop_filter.ts @@ -44,7 +44,7 @@ export function propFilter

(prop: P) { filters: string[] | string | FilterFunc = [] ): T[] { if (isFunction(filters)) { - return list.filter(item => (filters as FilterFunc)(item[prop])); + return list.filter((item) => (filters as FilterFunc)(item[prop])); } if (!Array.isArray(filters)) { @@ -75,7 +75,7 @@ export function propFilter

(prop: P) { return acc; }, {} as { [type: string]: string[] }); - return list.filter(item => { + return list.filter((item) => { const value = item[prop]; const excluded = options.exclude && options.exclude.includes(value); diff --git a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts index 89a46db27e894..906b8862d00aa 100644 --- a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts +++ b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts @@ -40,8 +40,8 @@ export async function buildTabularInspectorData( table: TabbedTable, queryFilter: { addFilters: (filter: any) => void } ) { - const aggConfigs = table.columns.map(column => column.aggConfig); - const rows = table.rows.map(row => { + const aggConfigs = table.columns.map((column) => column.aggConfig); + const rows = table.rows.map((row) => { return table.columns.reduce>((prev, cur, colIndex) => { const value = row[cur.id]; const fieldFormatter = cur.aggConfig.fieldFormatter('text'); @@ -60,7 +60,7 @@ export async function buildTabularInspectorData( isCellContentFilterable && ((value: { raw: unknown }) => { const rowIndex = rows.findIndex( - row => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw + (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw); @@ -72,7 +72,7 @@ export async function buildTabularInspectorData( isCellContentFilterable && ((value: { raw: unknown }) => { const rowIndex = rows.findIndex( - row => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw + (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw); @@ -80,7 +80,7 @@ export async function buildTabularInspectorData( const notOther = value.raw !== '__other__'; const notMissing = value.raw !== '__missing__'; if (Array.isArray(filter)) { - filter.forEach(f => set(f, 'meta.negate', notOther && notMissing)); + filter.forEach((f) => set(f, 'meta.negate', notOther && notMissing)); } else { set(filter, 'meta.negate', notOther && notMissing); } diff --git a/src/plugins/data/public/search/expressions/create_filter.ts b/src/plugins/data/public/search/expressions/create_filter.ts index 2e2bd435151b6..94d84380e03df 100644 --- a/src/plugins/data/public/search/expressions/create_filter.ts +++ b/src/plugins/data/public/search/expressions/create_filter.ts @@ -27,16 +27,16 @@ const getOtherBucketFilterTerms = (table: TabbedTable, columnIndex: number, rowI } // get only rows where cell value matches current row for all the fields before columnIndex - const rows = table.rows.filter(row => { + const rows = table.rows.filter((row) => { return table.columns.every((column, i) => { return row[column.id] === table.rows[rowIndex][column.id] || i >= columnIndex; }); }); - const terms = rows.map(row => row[table.columns[columnIndex].id]); + const terms = rows.map((row) => row[table.columns[columnIndex].id]); return [ ...new Set( - terms.filter(term => { + terms.filter((term) => { const notOther = term !== '__other__'; const notMissing = term !== '__missing__'; return notOther && notMissing; diff --git a/src/plugins/data/public/search/expressions/esaggs.ts b/src/plugins/data/public/search/expressions/esaggs.ts index d6901da99319a..153eb7de6f2de 100644 --- a/src/plugins/data/public/search/expressions/esaggs.ts +++ b/src/plugins/data/public/search/expressions/esaggs.ts @@ -115,7 +115,7 @@ const handleCourierRequest = async ({ }, }); - requestSearchSource.setField('aggs', function() { + requestSearchSource.setField('aggs', function () { return aggs.toDsl(metricsAtAllLevels); }); @@ -134,7 +134,7 @@ const handleCourierRequest = async ({ if (timeRange && allTimeFields.length > 0) { timeFilterSearchSource.setField('filter', () => { return allTimeFields - .map(fieldName => getTime(indexPattern, timeRange, { fieldName })) + .map((fieldName) => getTime(indexPattern, timeRange, { fieldName })) .filter(isRangeFilter); }); } diff --git a/src/plugins/data/public/search/fetch/get_search_params.test.ts b/src/plugins/data/public/search/fetch/get_search_params.test.ts index edf18405e8ff7..4809d76a46f59 100644 --- a/src/plugins/data/public/search/fetch/get_search_params.test.ts +++ b/src/plugins/data/public/search/fetch/get_search_params.test.ts @@ -22,7 +22,7 @@ import { IUiSettingsClient } from 'kibana/public'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } diff --git a/src/plugins/data/public/search/legacy/call_client.test.ts b/src/plugins/data/public/search/legacy/call_client.test.ts index 9a2a9dc222e7e..a3c4e720b4cab 100644 --- a/src/plugins/data/public/search/legacy/call_client.test.ts +++ b/src/plugins/data/public/search/legacy/call_client.test.ts @@ -34,7 +34,7 @@ jest.mock('./default_search_strategy', () => { search: jest.fn(({ searchRequests }: SearchStrategySearchParams) => { return { searching: Promise.resolve( - searchRequests.map(req => { + searchRequests.map((req) => { return { id: req._searchStrategyId, }; diff --git a/src/plugins/data/public/search/legacy/call_client.ts b/src/plugins/data/public/search/legacy/call_client.ts index c484c46aa4879..4b12f517daf78 100644 --- a/src/plugins/data/public/search/legacy/call_client.ts +++ b/src/plugins/data/public/search/legacy/call_client.ts @@ -40,10 +40,10 @@ export function callClient( }); searchRequests.forEach((request, i) => { - const response = searching.then(results => handleResponse(request, results[i])); + const response = searching.then((results) => handleResponse(request, results[i])); const { abortSignal = null } = requestOptionsMap.get(request) || {}; if (abortSignal) abortSignal.addEventListener('abort', abort); requestResponseMap.set(request, response); }); - return searchRequests.map(request => requestResponseMap.get(request)); + return searchRequests.map((request) => requestResponseMap.get(request)); } diff --git a/src/plugins/data/public/search/legacy/default_search_strategy.test.ts b/src/plugins/data/public/search/legacy/default_search_strategy.test.ts index 9e3d65a69bf02..c619c9b17d9a8 100644 --- a/src/plugins/data/public/search/legacy/default_search_strategy.test.ts +++ b/src/plugins/data/public/search/legacy/default_search_strategy.test.ts @@ -26,7 +26,7 @@ const { search } = defaultSearchStrategy; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } @@ -38,8 +38,8 @@ const searchMockResponse: any = Promise.resolve([]); searchMockResponse.abort = jest.fn(); const searchMock = jest.fn().mockReturnValue(searchMockResponse); -describe('defaultSearchStrategy', function() { - describe('search', function() { +describe('defaultSearchStrategy', function () { + describe('search', function () { let searchArgs: MockedKeys>; let es: any; diff --git a/src/plugins/data/public/search/legacy/default_search_strategy.ts b/src/plugins/data/public/search/legacy/default_search_strategy.ts index 3216803dcbfa2..284768bc5a1cc 100644 --- a/src/plugins/data/public/search/legacy/default_search_strategy.ts +++ b/src/plugins/data/public/search/legacy/default_search_strategy.ts @@ -25,7 +25,7 @@ import { SearchStrategyProvider, SearchStrategySearchParams } from './types'; export const defaultSearchStrategy: SearchStrategyProvider = { id: 'default', - search: params => { + search: (params) => { return msearch(params); }, }; diff --git a/src/plugins/data/public/search/legacy/fetch_soon.test.ts b/src/plugins/data/public/search/legacy/fetch_soon.test.ts index 6c0467e3297e8..e99e13ba33d1a 100644 --- a/src/plugins/data/public/search/legacy/fetch_soon.test.ts +++ b/src/plugins/data/public/search/legacy/fetch_soon.test.ts @@ -25,7 +25,7 @@ import { SearchRequest, SearchResponse } from '../index'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } @@ -41,9 +41,9 @@ jest.mock('./call_client', () => ({ callClient: jest.fn((requests: SearchRequest[]) => { // Allow a request object to specify which mockResponse it wants to receive (_mockResponseId) // in addition to how long to simulate waiting before returning a response (_waitMs) - const responses = requests.map(request => { + const responses = requests.map((request) => { const waitMs = requests.reduce((total, { _waitMs }) => total + _waitMs || 0, 0); - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => { resolve(mockResponses[request._mockResponseId]); }, waitMs); @@ -109,7 +109,7 @@ describe('fetchSoon', () => { }); const requests = [{ _mockResponseId: 'foo' }, { _mockResponseId: 'bar' }]; - const promises = requests.map(request => { + const promises = requests.map((request) => { return fetchSoon(request, {}, { config } as FetchHandlers); }); jest.advanceTimersByTime(50); @@ -125,11 +125,11 @@ describe('fetchSoon', () => { const firstBatch = [{ foo: 1 }, { foo: 2 }]; const secondBatch = [{ bar: 1 }, { bar: 2 }]; - firstBatch.forEach(request => { + firstBatch.forEach((request) => { fetchSoon(request, {}, { config } as FetchHandlers); }); jest.advanceTimersByTime(50); - secondBatch.forEach(request => { + secondBatch.forEach((request) => { fetchSoon(request, {}, { config } as FetchHandlers); }); diff --git a/src/plugins/data/public/search/legacy/fetch_soon.ts b/src/plugins/data/public/search/legacy/fetch_soon.ts index 83617d394fe95..304c1c4d63f5b 100644 --- a/src/plugins/data/public/search/legacy/fetch_soon.ts +++ b/src/plugins/data/public/search/legacy/fetch_soon.ts @@ -42,7 +42,7 @@ export async function fetchSoon( * @return Promise A promise that resolves with the result of executing the function */ function delay(fn: Function, ms: number) { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => resolve(fn()), ms); }); } diff --git a/src/plugins/data/public/search/legacy/get_msearch_params.test.ts b/src/plugins/data/public/search/legacy/get_msearch_params.test.ts index 9f16d5b408178..ce98f6ab2a7bb 100644 --- a/src/plugins/data/public/search/legacy/get_msearch_params.test.ts +++ b/src/plugins/data/public/search/legacy/get_msearch_params.test.ts @@ -22,7 +22,7 @@ import { IUiSettingsClient } from '../../../../../core/public'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 2815b41eaba5c..53cc650ee7a77 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -67,7 +67,7 @@ export class SearchInterceptor { // When search requests go out, a notification is scheduled allowing users to continue the // request past the timeout. When all search requests complete, we remove the notification. this.getPendingCount$() - .pipe(filter(count => count === 0)) + .pipe(filter((count) => count === 0)) .subscribe(this.hideToast); } diff --git a/src/plugins/data/public/search/search_service.ts b/src/plugins/data/public/search/search_service.ts index b69b3261d4a5e..1615aac9e7b7d 100644 --- a/src/plugins/data/public/search/search_service.ts +++ b/src/plugins/data/public/search/search_service.ts @@ -102,12 +102,12 @@ export class SearchService implements Plugin { uiSettings: core.uiSettings, getInternalStartServices, }); - aggTypes.buckets.forEach(b => aggTypesSetup.registerBucket(b)); - aggTypes.metrics.forEach(m => aggTypesSetup.registerMetric(m)); + aggTypes.buckets.forEach((b) => aggTypesSetup.registerBucket(b)); + aggTypes.metrics.forEach((m) => aggTypesSetup.registerMetric(m)); // register expression functions for each agg type const aggFunctions = getAggTypesFunctions(); - aggFunctions.forEach(fn => expressions.registerFunction(fn)); + aggFunctions.forEach((fn) => expressions.registerFunction(fn)); return { aggs: { diff --git a/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts b/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts index 917d26f0decd1..bbac30d7dfdc5 100644 --- a/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts +++ b/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts @@ -26,7 +26,7 @@ export function filterDocvalueFields( docvalueFields: Array, fields: string[] ) { - return docvalueFields.filter(docValue => { + return docvalueFields.filter((docValue) => { const docvalueFieldName = typeof docValue === 'string' ? docValue : docValue.field; return fields.includes(docvalueFieldName); }); diff --git a/src/plugins/data/public/search/search_source/inject_references.ts b/src/plugins/data/public/search/search_source/inject_references.ts index a567c33d2280b..07f37c3c11275 100644 --- a/src/plugins/data/public/search/search_source/inject_references.ts +++ b/src/plugins/data/public/search/search_source/inject_references.ts @@ -27,7 +27,7 @@ export const injectReferences = ( const searchSourceReturnFields: SearchSourceFields = { ...searchSourceFields }; // Inject index id if a reference is saved if (searchSourceFields.indexRefName) { - const reference = references.find(ref => ref.name === searchSourceFields.indexRefName); + const reference = references.find((ref) => ref.name === searchSourceFields.indexRefName); if (!reference) { throw new Error(`Could not find reference for ${searchSourceFields.indexRefName}`); } diff --git a/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts b/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts index 13a6167544b5e..d47aab80ee0bc 100644 --- a/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts +++ b/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts @@ -21,7 +21,7 @@ import { normalizeSortRequest } from './normalize_sort_request'; import { SortDirection } from './types'; import { IIndexPattern } from '../..'; -describe('SearchSource#normalizeSortRequest', function() { +describe('SearchSource#normalizeSortRequest', function () { const scriptedField = { name: 'script string', type: 'number', @@ -40,7 +40,7 @@ describe('SearchSource#normalizeSortRequest', function() { fields: [scriptedField, murmurScriptedField], } as IIndexPattern; - it('should return an array', function() { + it('should return an array', function () { const sortable = { someField: SortDirection.desc }; const result = normalizeSortRequest(sortable, indexPattern); expect(result).toEqual([ @@ -55,7 +55,7 @@ describe('SearchSource#normalizeSortRequest', function() { expect(sortable).toEqual({ someField: SortDirection.desc }); }); - it('should make plain string sort into the more verbose format', function() { + it('should make plain string sort into the more verbose format', function () { const result = normalizeSortRequest([{ someField: SortDirection.desc }], indexPattern); expect(result).toEqual([ { @@ -66,7 +66,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should append default sort options', function() { + it('should append default sort options', function () { const defaultSortOptions = { unmapped_type: 'boolean', }; @@ -85,7 +85,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should enable script based sorting', function() { + it('should enable script based sorting', function () { const result = normalizeSortRequest( { [scriptedField.name]: SortDirection.desc, @@ -106,7 +106,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should use script based sorting only on sortable types', function() { + it('should use script based sorting only on sortable types', function () { const result = normalizeSortRequest( [ { @@ -125,7 +125,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should remove unmapped_type parameter from _score sorting', function() { + it('should remove unmapped_type parameter from _score sorting', function () { const result = normalizeSortRequest({ _score: SortDirection.desc }, indexPattern, { unmapped_type: 'boolean', }); diff --git a/src/plugins/data/public/search/search_source/normalize_sort_request.ts b/src/plugins/data/public/search/search_source/normalize_sort_request.ts index 9e36d2e416f03..9a0cf371ce81d 100644 --- a/src/plugins/data/public/search/search_source/normalize_sort_request.ts +++ b/src/plugins/data/public/search/search_source/normalize_sort_request.ts @@ -26,7 +26,7 @@ export function normalizeSortRequest( defaultSortOptions: SortOptions = {} ) { const sortArray: EsQuerySortValue[] = Array.isArray(sortObject) ? sortObject : [sortObject]; - return sortArray.map(function(sortable) { + return sortArray.map(function (sortable) { return normalize(sortable, indexPattern, defaultSortOptions); }); } diff --git a/src/plugins/data/public/search/search_source/search_source.test.ts b/src/plugins/data/public/search/search_source/search_source.test.ts index 7783e65889a12..6d53b8dfc4b4e 100644 --- a/src/plugins/data/public/search/search_source/search_source.test.ts +++ b/src/plugins/data/public/search/search_source/search_source.test.ts @@ -58,7 +58,7 @@ describe('SearchSource', () => { const data = dataPluginMock.createStartContract(); mockSearchMethod = jest.fn(() => { - return new Observable(subscriber => { + return new Observable((subscriber) => { setTimeout(() => { subscriber.next({ rawResponse: '', diff --git a/src/plugins/data/public/search/search_source/search_source.ts b/src/plugins/data/public/search/search_source/search_source.ts index 9fdef5e1f3eb0..38f4ce73713c8 100644 --- a/src/plugins/data/public/search/search_source/search_source.ts +++ b/src/plugins/data/public/search/search_source/search_source.ts @@ -309,7 +309,7 @@ export class SearchSource { } } - return Promise.all(handlers.map(fn => fn(this, options))); + return Promise.all(handlers.map((fn) => fn(this, options))); } /** diff --git a/src/plugins/data/public/search/sync_search_strategy.test.ts b/src/plugins/data/public/search/sync_search_strategy.test.ts index 31a1adfa01c75..6197980314b86 100644 --- a/src/plugins/data/public/search/sync_search_strategy.test.ts +++ b/src/plugins/data/public/search/sync_search_strategy.test.ts @@ -61,7 +61,7 @@ describe('Sync search strategy', () => { const request = { serverStrategy: SYNC_SEARCH_STRATEGY }; const loadingCount$ = mockCoreStart.http.addLoadingCountSource.mock.calls[0][0]; - loadingCount$.subscribe(value => receivedLoadingCountValues.push(value)); + loadingCount$.subscribe((value) => receivedLoadingCountValues.push(value)); await syncSearch.search(request, {}).toPromise(); @@ -82,7 +82,7 @@ describe('Sync search strategy', () => { const request = { serverStrategy: SYNC_SEARCH_STRATEGY }; const loadingCount$ = mockCoreStart.http.addLoadingCountSource.mock.calls[0][0]; - loadingCount$.subscribe(value => receivedLoadingCountValues.push(value)); + loadingCount$.subscribe((value) => receivedLoadingCountValues.push(value)); try { await syncSearch.search(request, {}).toPromise(); diff --git a/src/plugins/data/public/search/tabify/buckets.test.ts b/src/plugins/data/public/search/tabify/buckets.test.ts index 81d9f3d5ca3fd..dfd9462d87b68 100644 --- a/src/plugins/data/public/search/tabify/buckets.test.ts +++ b/src/plugins/data/public/search/tabify/buckets.test.ts @@ -86,7 +86,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(2); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); @@ -116,7 +116,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(2); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); @@ -141,7 +141,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(1); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); diff --git a/src/plugins/data/public/search/tabify/buckets.ts b/src/plugins/data/public/search/tabify/buckets.ts index cd52a09caeaad..e6e5ba4e68ea3 100644 --- a/src/plugins/data/public/search/tabify/buckets.ts +++ b/src/plugins/data/public/search/tabify/buckets.ts @@ -68,7 +68,7 @@ export class TabifyBuckets { const buckets = this.buckets; if (this.objectMode) { - this._keys.forEach(key => { + this._keys.forEach((key) => { fn(buckets[key], key); }); } else { diff --git a/src/plugins/data/public/search/tabify/get_columns.test.ts b/src/plugins/data/public/search/tabify/get_columns.test.ts index 1072e9318b40e..b4498aca4079c 100644 --- a/src/plugins/data/public/search/tabify/get_columns.test.ts +++ b/src/plugins/data/public/search/tabify/get_columns.test.ts @@ -159,7 +159,7 @@ describe('get columns', () => { false ); - expect(columns.map(c => c.name)).toEqual([ + expect(columns.map((c) => c.name)).toEqual([ '@timestamp per 20 seconds', 'Sum of @timestamp', '@timestamp per 10 seconds', diff --git a/src/plugins/data/public/search/tabify/get_columns.ts b/src/plugins/data/public/search/tabify/get_columns.ts index ee8c636fb2e86..8c538288d2fea 100644 --- a/src/plugins/data/public/search/tabify/get_columns.ts +++ b/src/plugins/data/public/search/tabify/get_columns.ts @@ -45,7 +45,7 @@ export function tabifyGetColumns(aggs: IAggConfig[], minimalColumns: boolean): T const columns: TabbedAggColumn[] = []; // separate the metrics - const grouped = groupBy(aggs, agg => { + const grouped = groupBy(aggs, (agg) => { return agg.type.type; }); @@ -56,9 +56,9 @@ export function tabifyGetColumns(aggs: IAggConfig[], minimalColumns: boolean): T let columnIndex = 0; // return the buckets, and after each place all of the metrics - grouped.buckets.forEach(agg => { + grouped.buckets.forEach((agg) => { columns.push(getColumn(agg, columnIndex++)); - grouped.metrics.forEach(metric => { + grouped.metrics.forEach((metric) => { columns.push(getColumn(metric, columnIndex++)); }); }); diff --git a/src/plugins/data/public/search/tabify/response_writer.ts b/src/plugins/data/public/search/tabify/response_writer.ts index 02e18d75ae6e5..da9b59cc92791 100644 --- a/src/plugins/data/public/search/tabify/response_writer.ts +++ b/src/plugins/data/public/search/tabify/response_writer.ts @@ -61,15 +61,15 @@ export class TabbedAggResponseWriter { row() { const rowBuffer: TabbedAggRow = {}; - this.bucketBuffer.forEach(bucket => { + this.bucketBuffer.forEach((bucket) => { rowBuffer[bucket.id] = bucket.value; }); - this.metricBuffer.forEach(metric => { + this.metricBuffer.forEach((metric) => { rowBuffer[metric.id] = metric.value; }); - const isPartialRow = !this.columns.every(column => rowBuffer.hasOwnProperty(column.id)); + const isPartialRow = !this.columns.every((column) => rowBuffer.hasOwnProperty(column.id)); const removePartial = isPartialRow && !this.partialRows; if (!isEmpty(rowBuffer) && !removePartial) { this.rows.push(rowBuffer); diff --git a/src/plugins/data/public/search/tabify/tabify.test.ts b/src/plugins/data/public/search/tabify/tabify.test.ts index 63685cc87f5cf..f6691360cec31 100644 --- a/src/plugins/data/public/search/tabify/tabify.test.ts +++ b/src/plugins/data/public/search/tabify/tabify.test.ts @@ -142,7 +142,7 @@ describe('tabifyAggResponse Integration', () => { expectColumns(tabbed, [ext, src, os, avg]); - tabbed.rows.forEach(row => { + tabbed.rows.forEach((row) => { expectRow(row, [expectExtension, expectCountry, expectOS, expectAvgBytes]); }); }); @@ -152,7 +152,7 @@ describe('tabifyAggResponse Integration', () => { expectColumns(tabbed, [ext, avg, src, avg, os, avg]); - tabbed.rows.forEach(row => { + tabbed.rows.forEach((row) => { expectRow(row, [ expectExtension, expectAvgBytes, diff --git a/src/plugins/data/public/ui/filter_bar/filter_bar.tsx b/src/plugins/data/public/ui/filter_bar/filter_bar.tsx index 6852152d059be..d89cf01eedd43 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_bar.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_bar.tsx @@ -65,7 +65,7 @@ function FilterBarUI(props: Props) { onUpdate(i, newFilter)} + onUpdate={(newFilter) => onUpdate(i, newFilter)} onRemove={() => onRemove(i)} indexPatterns={props.indexPatterns} uiSettings={uiSettings!} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx index a5db8b66caa01..66adbfe9a6fc3 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx @@ -38,12 +38,12 @@ export function GenericComboBox(props: GenericComboBoxProps) { const { options, selectedOptions, getLabel, onChange, ...otherProps } = props; const labels = options.map(getLabel); - const euiOptions: EuiComboBoxOptionOption[] = labels.map(label => ({ label })); + const euiOptions: EuiComboBoxOptionOption[] = labels.map((label) => ({ label })); const selectedEuiOptions = selectedOptions - .filter(option => { + .filter((option) => { return options.indexOf(option) !== -1; }) - .map(option => { + .map((option) => { return euiOptions[options.indexOf(option)]; }); diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx index ffe2a153a87f3..fd228a2213795 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx @@ -198,7 +198,7 @@ class FilterEditorUI extends Component { if ( this.props.indexPatterns.length <= 1 && this.props.indexPatterns.find( - indexPattern => indexPattern === this.state.selectedIndexPattern + (indexPattern) => indexPattern === this.state.selectedIndexPattern ) ) { return ''; @@ -220,7 +220,7 @@ class FilterEditorUI extends Component { })} options={this.props.indexPatterns} selectedOptions={selectedIndexPattern ? [selectedIndexPattern] : []} - getLabel={indexPattern => indexPattern.title} + getLabel={(indexPattern) => indexPattern.title} onChange={this.onIndexPatternChange} singleSelection={{ asPlainText: true }} isClearable={false} @@ -267,7 +267,7 @@ class FilterEditorUI extends Component { })} options={fields} selectedOptions={selectedField ? [selectedField] : []} - getLabel={field => field.name} + getLabel={(field) => field.name} onChange={this.onFieldChange} singleSelection={{ asPlainText: true }} isClearable={false} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts index 771743a3e5df2..12cdf13caeb55 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts @@ -115,7 +115,7 @@ describe('Filter editor utils', () => { it('limits the fields to the filterable fields', () => { const fieldOptions = getFilterableFields(stubIndexPattern); - const nonFilterableFields = fieldOptions.filter(field => !field.filterable); + const nonFilterableFields = fieldOptions.filter((field) => !field.filterable); expect(nonFilterableFields.length).toBe(0); }); }); @@ -124,14 +124,14 @@ describe('Filter editor utils', () => { it('returns range for number fields', () => { const [field] = stubFields.filter(({ type }) => type === 'number'); const operatorOptions = getOperatorOptions(field); - const rangeOperator = operatorOptions.find(operator => operator.type === 'range'); + const rangeOperator = operatorOptions.find((operator) => operator.type === 'range'); expect(rangeOperator).not.toBeUndefined(); }); it('does not return range for string fields', () => { const [field] = stubFields.filter(({ type }) => type === 'string'); const operatorOptions = getOperatorOptions(field); - const rangeOperator = operatorOptions.find(operator => operator.type === 'range'); + const rangeOperator = operatorOptions.find((operator) => operator.type === 'range'); expect(rangeOperator).toBeUndefined(); }); }); diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts index beb7714ffcca3..01a664837e704 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts @@ -29,11 +29,11 @@ import { } from '../../../../../common'; export function getFieldFromFilter(filter: FieldFilter, indexPattern: IIndexPattern) { - return indexPattern.fields.find(field => field.name === filter.meta.key); + return indexPattern.fields.find((field) => field.name === filter.meta.key); } export function getOperatorFromFilter(filter: Filter) { - return FILTER_OPERATORS.find(operator => { + return FILTER_OPERATORS.find((operator) => { return filter.meta.type === operator.type && filter.meta.negate === operator.negate; }); } @@ -43,7 +43,7 @@ export function getFilterableFields(indexPattern: IIndexPattern) { } export function getOperatorOptions(field: IFieldType) { - return FILTER_OPERATORS.filter(operator => { + return FILTER_OPERATORS.filter((operator) => { return !operator.fieldTypes || operator.fieldTypes.includes(field.type); }); } @@ -80,7 +80,7 @@ export function isFilterValid( if (!Array.isArray(params) || !params.length) { return false; } - return params.every(phrase => validateParams(phrase, field.type)); + return params.every((phrase) => validateParams(phrase, field.type)); case 'range': if (typeof params !== 'object') { return false; diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx index b16994cb0057b..ca94970afbafd 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx @@ -71,7 +71,7 @@ class PhraseValueInputUI extends PhraseSuggestorUI { defaultMessage: 'Select a value', })} options={options} - getLabel={option => option} + getLabel={(option) => option} selectedOptions={value ? [valueAsStr] : []} onChange={([newValue = '']) => onChange(newValue)} onSearchChange={this.onSearchChange} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx index 72f92268f3330..7ca46f60bba5b 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx @@ -49,7 +49,7 @@ class PhrasesValuesInputUI extends PhraseSuggestorUI { defaultMessage: 'Select values', })} options={options} - getLabel={option => option} + getLabel={(option) => option} selectedOptions={values || []} onSearchChange={this.onSearchChange} onCreateOption={(option: string) => onChange([...(values || []), option])} diff --git a/src/plugins/data/public/ui/filter_bar/filter_options.tsx b/src/plugins/data/public/ui/filter_bar/filter_options.tsx index eaa7c291ca00d..3fb7f198d5466 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_options.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_options.tsx @@ -43,7 +43,7 @@ class FilterOptionsUI extends Component { }; public togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts b/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts index 1e01d2452ce04..127dc0f1f41d3 100644 --- a/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts +++ b/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts @@ -29,7 +29,7 @@ export async function fetchIndexPatterns( return []; } - const searchString = indexPatternStrings.map(string => `"${string}"`).join(' | '); + const searchString = indexPatternStrings.map((string) => `"${string}"`).join(' | '); const indexPatternsFromSavedObjects = await savedObjectsClient.find({ type: 'index-pattern', fields: ['title', 'fields'], @@ -37,7 +37,7 @@ export async function fetchIndexPatterns( searchFields: ['title'], }); - const exactMatches = indexPatternsFromSavedObjects.savedObjects.filter(savedObject => { + const exactMatches = indexPatternsFromSavedObjects.savedObjects.filter((savedObject) => { return indexPatternStrings.includes(savedObject.attributes.title); }); diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx index 738c9cfb39398..755716aee8f48 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx @@ -160,10 +160,7 @@ describe('QueryStringInput', () => { ) ); - component - .find(QueryLanguageSwitcher) - .props() - .onSelectLanguage('lucene'); + component.find(QueryLanguageSwitcher).props().onSelectLanguage('lucene'); expect(mockStorage.set).toHaveBeenCalledWith('kibana.userQueryLanguage', 'lucene'); expect(mockCallback).toHaveBeenCalledWith({ query: '', language: 'lucene' }); }); diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx index a51362d0ba92e..32295745ce217 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx @@ -105,10 +105,10 @@ export class QueryStringInputUI extends Component { private fetchIndexPatterns = async () => { const stringPatterns = this.props.indexPatterns.filter( - indexPattern => typeof indexPattern === 'string' + (indexPattern) => typeof indexPattern === 'string' ) as string[]; const objectPatterns = this.props.indexPatterns.filter( - indexPattern => typeof indexPattern !== 'string' + (indexPattern) => typeof indexPattern !== 'string' ) as IIndexPattern[]; const objectPatternsFromStrings = (await fetchIndexPatterns( @@ -175,11 +175,11 @@ export class QueryStringInputUI extends Component { return []; } const recentSearches = this.persistedLog.get(); - const matchingRecentSearches = recentSearches.filter(recentQuery => { + const matchingRecentSearches = recentSearches.filter((recentQuery) => { const recentQueryString = typeof recentQuery === 'object' ? toUser(recentQuery) : recentQuery; return recentQueryString.includes(query); }); - return matchingRecentSearches.map(recentSearch => { + return matchingRecentSearches.map((recentSearch) => { const text = toUser(recentSearch); const start = 0; const end = query.length; @@ -536,7 +536,7 @@ export class QueryStringInputUI extends Component { onClick={this.onClickInput} fullWidth autoFocus={!this.props.disableAutoFocus} - inputRef={node => { + inputRef={(node) => { if (node) { this.inputRef = node; } diff --git a/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx b/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx index 5550ea16c22df..c61625dc06c18 100644 --- a/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx +++ b/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx @@ -104,7 +104,7 @@ export function SaveQueryForm({ const errors = []; if ( !!savedQueries.find( - existingSavedQuery => !savedQuery && existingSavedQuery.attributes.title === title + (existingSavedQuery) => !savedQuery && existingSavedQuery.attributes.title === title ) ) { errors.push(titleConflictErrorText); @@ -129,7 +129,7 @@ export function SaveQueryForm({ } }, [validate, onSave, title, description, shouldIncludeFilters, shouldIncludeTimefilter]); - const onInputChange = useCallback(event => { + const onInputChange = useCallback((event) => { setEnabledSaveButton(Boolean(event.target.value)); setFormErrors([]); setTitle(event.target.value); @@ -178,7 +178,7 @@ export function SaveQueryForm({ { + onChange={(event) => { setDescription(event.target.value); }} data-test-subj="saveQueryFormDescription" diff --git a/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx b/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx index 8ad1b5d392f3b..6108de0280183 100644 --- a/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx +++ b/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx @@ -116,7 +116,7 @@ export function SavedQueryManagementComponent({ const onDeleteSavedQuery = async (savedQuery: SavedQuery) => { cancelPendingListingRequest.current(); setSavedQueries( - savedQueries.filter(currentSavedQuery => currentSavedQuery.id !== savedQuery.id) + savedQueries.filter((currentSavedQuery) => currentSavedQuery.id !== savedQuery.id) ); if (loadedSavedQuery && loadedSavedQuery.id === savedQuery.id) { @@ -146,7 +146,7 @@ export function SavedQueryManagementComponent({ ); const savedQueryRows = () => { - const savedQueriesWithoutCurrent = savedQueries.filter(savedQuery => { + const savedQueriesWithoutCurrent = savedQueries.filter((savedQuery) => { if (!loadedSavedQuery) return true; return savedQuery.id !== loadedSavedQuery.id; }); @@ -154,16 +154,16 @@ export function SavedQueryManagementComponent({ loadedSavedQuery && savedQueriesWithoutCurrent.length !== savedQueries.length ? [loadedSavedQuery, ...savedQueriesWithoutCurrent] : [...savedQueriesWithoutCurrent]; - return savedQueriesReordered.map(savedQuery => ( + return savedQueriesReordered.map((savedQuery) => ( { + onSelect={(savedQueryToSelect) => { onLoad(savedQueryToSelect); setIsOpen(false); }} - onDelete={savedQueryToDelete => onDeleteSavedQuery(savedQueryToDelete)} + onDelete={(savedQueryToDelete) => onDeleteSavedQuery(savedQueryToDelete)} showWriteOperations={!!showSaveQuery} /> )); diff --git a/src/plugins/data/public/ui/search_bar/search_bar.tsx b/src/plugins/data/public/ui/search_bar/search_bar.tsx index 2371ccdde068c..a5ac227559115 100644 --- a/src/plugins/data/public/ui/search_bar/search_bar.tsx +++ b/src/plugins/data/public/ui/search_bar/search_bar.tsx @@ -414,13 +414,13 @@ class SearchBarUI extends Component { filterBar = (

{ + ref={(node) => { this.filterBarWrapperRef = node; }} className={filterGroupClasses} >
{ + ref={(node) => { this.filterBarRef = node; }} > @@ -453,7 +453,7 @@ class SearchBarUI extends Component { {this.state.showSaveNewQueryModal ? ( this.onSave(savedQueryMeta, true)} + onSave={(savedQueryMeta) => this.onSave(savedQueryMeta, true)} onClose={() => this.setState({ showSaveNewQueryModal: false })} showFilterOption={this.props.showFilterBar} showTimeFilterOption={this.shouldRenderTimeFilterInSavedQueryForm()} diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx index 947f33efa242c..23cf087de23f3 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx @@ -26,8 +26,8 @@ export function getFailurePropsForSummary( ): Array<{ key: string; value: string }> { const failureDetailProps: Array = ['shard', 'index', 'node']; return failureDetailProps - .filter(key => typeof failure[key] === 'number' || typeof failure[key] === 'string') - .map(key => ({ key, value: String(failure[key]) })); + .filter((key) => typeof failure[key] === 'number' || typeof failure[key] === 'string') + .map((key) => ({ key, value: String(failure[key]) })); } export function getFailureSummaryText(failure: ShardFailure, failureDetails?: string): string { @@ -49,7 +49,7 @@ export function getFailureSummaryDetailsText(failure: ShardFailure): string { } export function ShardFailureDescriptionHeader(props: ShardFailure) { - const failureDetails = getFailurePropsForSummary(props).map(kv => ( + const failureDetails = getFailurePropsForSummary(props).map((kv) => ( {kv.key} {kv.value} diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx index 3dcab7732f769..535f63161966d 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx @@ -104,7 +104,7 @@ export function ShardFailureModal({ request, response, title, onClose }: Props) - {copy => ( + {(copy) => ( { /> ); - component - .find(SuggestionComponent) - .at(1) - .simulate('click'); + component.find(SuggestionComponent).at(1).simulate('click'); expect(mockCallback).toHaveBeenCalledTimes(1); expect(mockCallback).toHaveBeenCalledWith(mockSuggestions[1]); }); @@ -140,10 +137,7 @@ describe('SuggestionsComponent', () => { /> ); - component - .find(SuggestionComponent) - .at(1) - .simulate('mouseenter'); + component.find(SuggestionComponent).at(1).simulate('mouseenter'); expect(mockCallback).toHaveBeenCalledTimes(1); expect(mockCallback).toHaveBeenCalledWith(1); }); diff --git a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx index cdc6cd5b9e772..77dd7dcec01ee 100644 --- a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx @@ -43,7 +43,7 @@ export class SuggestionsComponent extends Component { const suggestions = this.props.suggestions.map((suggestion, index) => { return ( (this.childNodes[index] = node)} + innerRef={(node) => (this.childNodes[index] = node)} selected={index === this.props.index} suggestion={suggestion} onClick={this.props.onClick} @@ -62,7 +62,7 @@ export class SuggestionsComponent extends Component { id="kbnTypeahead__items" className="kbnTypeahead__items" role="listbox" - ref={node => (this.parentNode = node)} + ref={(node) => (this.parentNode = node)} onScroll={this.handleScroll} > {suggestions} diff --git a/src/plugins/data/server/autocomplete/value_suggestions_route.ts b/src/plugins/data/server/autocomplete/value_suggestions_route.ts index b7569a22e9fc9..1b13ff4905c40 100644 --- a/src/plugins/data/server/autocomplete/value_suggestions_route.ts +++ b/src/plugins/data/server/autocomplete/value_suggestions_route.ts @@ -93,7 +93,7 @@ async function getBody( // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html#_standard_operators const getEscapedQuery = (q: string = '') => - q.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, match => `\\${match}`); + q.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, (match) => `\\${match}`); // Helps ensure that the regex is not evaluated eagerly against the terms dictionary const executionHint = 'map'; diff --git a/src/plugins/data/server/field_formats/converters/date_server.ts b/src/plugins/data/server/field_formats/converters/date_server.ts index f4e6296259196..85eb65dfc6a8d 100644 --- a/src/plugins/data/server/field_formats/converters/date_server.ts +++ b/src/plugins/data/server/field_formats/converters/date_server.ts @@ -77,7 +77,7 @@ export class DateFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so we can hot-swap when config changes const pattern = this.param('pattern'); const timezone = this.param('timezone'); diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 3404fe8cee9fd..70584efbee0a0 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -42,7 +42,7 @@ export class FieldFormatsService { const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); - Object.keys(registeredUiSettings).forEach(key => { + Object.keys(registeredUiSettings).forEach((key) => { if (has(uiConfigs, key) && registeredUiSettings[key].type === 'json') { uiConfigs[key] = JSON.parse(uiConfigs[key]); } diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js index ba4c0865a8d80..a0af7582ac6f3 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js @@ -44,7 +44,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { // assert that the stub was called with the exact `args`, using === matching const calledWithExactly = (stub, args, matcher = sinon.match.same) => { - sinon.assert.calledWithExactly(stub, ...args.map(arg => matcher(arg))); + sinon.assert.calledWithExactly(stub, ...args.map((arg) => matcher(arg))); }; const stubDeps = (options = {}) => { @@ -83,10 +83,10 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { const sortedLetters = sortBy(letters); stubDeps({ - fieldsFromFieldCaps: shuffle(letters.map(name => ({ name }))), + fieldsFromFieldCaps: shuffle(letters.map((name) => ({ name }))), }); - const fieldNames = (await getFieldCapabilities()).map(field => field.name); + const fieldNames = (await getFieldCapabilities()).map((field) => field.name); expect(fieldNames).toEqual(sortedLetters); }); }); @@ -99,7 +99,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { const resp = await getFieldCapabilities(undefined, undefined, ['meta1', 'meta2']); expect(resp).toHaveLength(4); - expect(resp.map(field => field.name)).toEqual(['bar', 'foo', 'meta1', 'meta2']); + expect(resp.map((field) => field.name)).toEqual(['bar', 'foo', 'meta1', 'meta2']); }); }); @@ -115,7 +115,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { }); describe('ensures that every field has property:', () => { - properties.forEach(property => { + properties.forEach((property) => { it(property, async () => { const field = createField(); delete field[property]; @@ -131,7 +131,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { // ensure field object was not mutated expect(field).not.toHaveProperty(property); - Object.keys(field).forEach(key => { + Object.keys(field).forEach((key) => { // ensure response field has original values from field expect(resp[0][key]).toBe(footballs[0]); }); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts index 2a30c89342cf3..d8c9466432204 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts @@ -47,10 +47,10 @@ export async function getFieldCapabilities( const fieldsFromFieldCapsByName = indexBy(readFieldCapsResponse(esFieldCaps), 'name'); const allFieldsUnsorted = Object.keys(fieldsFromFieldCapsByName) - .filter(name => !name.startsWith('_')) + .filter((name) => !name.startsWith('_')) .concat(metaFields) .reduce(concatIfUniq, [] as string[]) - .map(name => + .map((name) => defaults({}, fieldsFromFieldCapsByName[name], { name, type: 'string', diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js index de905ce4f336d..1a4e2b1fe9ee2 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js @@ -49,7 +49,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { responseClone.fields['@timestamp'].date.extraCapability = true; const fields = readFieldCapsResponse(responseClone); - fields.forEach(field => { + fields.forEach((field) => { const fieldWithoutOptionalKeys = omit(field, 'conflictDescriptions', 'subType'); expect(Object.keys(fieldWithoutOptionalKeys)).toEqual([ @@ -67,13 +67,13 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('calls shouldReadFieldFromDocValues() for each non-conflict field', () => { sandbox.spy(shouldReadFieldFromDocValuesNS, 'shouldReadFieldFromDocValues'); const fields = readFieldCapsResponse(esResponse); - const conflictCount = fields.filter(f => f.type === 'conflict').length; + const conflictCount = fields.filter((f) => f.type === 'conflict').length; // +2 is for the object and nested fields which get filtered out of the final return value from readFieldCapsResponse sinon.assert.callCount(shouldReadFieldFromDocValues, fields.length - conflictCount + 2); }); it('converts es types to kibana types', () => { - readFieldCapsResponse(esResponse).forEach(field => { + readFieldCapsResponse(esResponse).forEach((field) => { if (!getKbnFieldType(field.type)) { throw new Error(`expected field to have kibana type, got ${field.type}`); } @@ -82,7 +82,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('should include the original ES types found for each field across indices', () => { const fields = readFieldCapsResponse(esResponse); - fields.forEach(field => { + fields.forEach((field) => { const fixtureTypes = Object.keys(esResponse.fields[field.name]); expect(field.esTypes).toEqual(fixtureTypes); }); @@ -90,7 +90,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('returns fields with multiple types as conflicts', () => { const fields = readFieldCapsResponse(esResponse); - const conflicts = fields.filter(f => f.type === 'conflict'); + const conflicts = fields.filter((f) => f.type === 'conflict'); expect(conflicts).toEqual([ { name: 'success', @@ -109,43 +109,43 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('does not return conflicted fields if the types are resolvable to the same kibana type', () => { const fields = readFieldCapsResponse(esResponse); - const resolvableToString = fields.find(f => f.name === 'resolvable_to_string'); - const resolvableToNumber = fields.find(f => f.name === 'resolvable_to_number'); + const resolvableToString = fields.find((f) => f.name === 'resolvable_to_string'); + const resolvableToNumber = fields.find((f) => f.name === 'resolvable_to_number'); expect(resolvableToString.type).toBe('string'); expect(resolvableToNumber.type).toBe('number'); }); it('returns aggregatable if at least one field is aggregatable', () => { const fields = readFieldCapsResponse(esResponse); - const mixAggregatable = fields.find(f => f.name === 'mix_aggregatable'); - const mixAggregatableOther = fields.find(f => f.name === 'mix_aggregatable_other'); + const mixAggregatable = fields.find((f) => f.name === 'mix_aggregatable'); + const mixAggregatableOther = fields.find((f) => f.name === 'mix_aggregatable_other'); expect(mixAggregatable.aggregatable).toBe(true); expect(mixAggregatableOther.aggregatable).toBe(true); }); it('returns searchable if at least one field is searchable', () => { const fields = readFieldCapsResponse(esResponse); - const mixSearchable = fields.find(f => f.name === 'mix_searchable'); - const mixSearchableOther = fields.find(f => f.name === 'mix_searchable_other'); + const mixSearchable = fields.find((f) => f.name === 'mix_searchable'); + const mixSearchableOther = fields.find((f) => f.name === 'mix_searchable_other'); expect(mixSearchable.searchable).toBe(true); expect(mixSearchableOther.searchable).toBe(true); }); it('returns multi fields with a subType key describing the relationship', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'multi_parent.child'); + const child = fields.find((f) => f.name === 'multi_parent.child'); expect(child).toHaveProperty('subType', { multi: { parent: 'multi_parent' } }); }); it('returns nested sub-fields with a subType key describing the relationship', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent.child'); + const child = fields.find((f) => f.name === 'nested_object_parent.child'); expect(child).toHaveProperty('subType', { nested: { path: 'nested_object_parent' } }); }); it('handles fields that are both nested and multi', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent.child.keyword'); + const child = fields.find((f) => f.name === 'nested_object_parent.child.keyword'); expect(child).toHaveProperty('subType', { nested: { path: 'nested_object_parent' }, multi: { parent: 'nested_object_parent.child' }, @@ -154,7 +154,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('does not include the field actually mapped as nested itself', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent'); + const child = fields.find((f) => f.name === 'nested_object_parent'); expect(child).toBeUndefined(); }); @@ -163,7 +163,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { // to see if their parents are *not* object fields. In the future we may want to // add subType info for object fields but for now we don't need it. const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'object_parent.child'); + const child = fields.find((f) => f.name === 'object_parent.child'); expect(child).not.toHaveProperty('subType'); }); }); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts index 06eb30db0b24b..cb1ec6a2ebcf3 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts @@ -93,74 +93,76 @@ export interface FieldCapsResponse { */ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): FieldDescriptor[] { const capsByNameThenType = fieldCapsResponse.fields; - const kibanaFormattedCaps: FieldDescriptor[] = Object.keys(capsByNameThenType).map(fieldName => { - const capsByType = capsByNameThenType[fieldName]; - const types = Object.keys(capsByType); + const kibanaFormattedCaps: FieldDescriptor[] = Object.keys(capsByNameThenType).map( + (fieldName) => { + const capsByType = capsByNameThenType[fieldName]; + const types = Object.keys(capsByType); - // If a single type is marked as searchable or aggregatable, all the types are searchable or aggregatable - const isSearchable = types.some(type => { - return ( - !!capsByType[type].searchable || - (!!capsByType[type].non_searchable_indices && - capsByType[type].non_searchable_indices!.length > 0) - ); - }); + // If a single type is marked as searchable or aggregatable, all the types are searchable or aggregatable + const isSearchable = types.some((type) => { + return ( + !!capsByType[type].searchable || + (!!capsByType[type].non_searchable_indices && + capsByType[type].non_searchable_indices!.length > 0) + ); + }); - const isAggregatable = types.some(type => { - return ( - !!capsByType[type].aggregatable || - (!!capsByType[type].non_aggregatable_indices && - capsByType[type].non_aggregatable_indices!.length > 0) - ); - }); + const isAggregatable = types.some((type) => { + return ( + !!capsByType[type].aggregatable || + (!!capsByType[type].non_aggregatable_indices && + capsByType[type].non_aggregatable_indices!.length > 0) + ); + }); + + // If there are multiple types but they all resolve to the same kibana type + // ignore the conflict and carry on (my wayward son) + const uniqueKibanaTypes = uniq(types.map(castEsToKbnFieldTypeName)); + if (uniqueKibanaTypes.length > 1) { + return { + name: fieldName, + type: 'conflict', + esTypes: types, + searchable: isSearchable, + aggregatable: isAggregatable, + readFromDocValues: false, + conflictDescriptions: types.reduce( + (acc, esType) => ({ + ...acc, + [esType]: capsByType[esType].indices, + }), + {} + ), + }; + } - // If there are multiple types but they all resolve to the same kibana type - // ignore the conflict and carry on (my wayward son) - const uniqueKibanaTypes = uniq(types.map(castEsToKbnFieldTypeName)); - if (uniqueKibanaTypes.length > 1) { + const esType = types[0]; return { name: fieldName, - type: 'conflict', + type: castEsToKbnFieldTypeName(esType), esTypes: types, searchable: isSearchable, aggregatable: isAggregatable, - readFromDocValues: false, - conflictDescriptions: types.reduce( - (acc, esType) => ({ - ...acc, - [esType]: capsByType[esType].indices, - }), - {} - ), + readFromDocValues: shouldReadFieldFromDocValues(isAggregatable, esType), }; } - - const esType = types[0]; - return { - name: fieldName, - type: castEsToKbnFieldTypeName(esType), - esTypes: types, - searchable: isSearchable, - aggregatable: isAggregatable, - readFromDocValues: shouldReadFieldFromDocValues(isAggregatable, esType), - }; - }); + ); // Get all types of sub fields. These could be multi fields or children of nested/object types - const subFields = kibanaFormattedCaps.filter(field => { + const subFields = kibanaFormattedCaps.filter((field) => { return field.name.includes('.'); }); // Determine the type of each sub field. - subFields.forEach(field => { + subFields.forEach((field) => { const parentFieldNames = field.name .split('.') .slice(0, -1) .map((_, index, parentFieldNameParts) => { return parentFieldNameParts.slice(0, index + 1).join('.'); }); - const parentFieldCaps = parentFieldNames.map(parentFieldName => { - return kibanaFormattedCaps.find(caps => caps.name === parentFieldName); + const parentFieldCaps = parentFieldNames.map((parentFieldName) => { + return kibanaFormattedCaps.find((caps) => caps.name === parentFieldName); }); const parentFieldCapsAscending = parentFieldCaps.reverse(); @@ -174,7 +176,7 @@ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): Fie // We need to know if any parent field is nested const nestedParentCaps = parentFieldCapsAscending.find( - parentCaps => parentCaps && parentCaps.type === 'nested' + (parentCaps) => parentCaps && parentCaps.type === 'nested' ); if (nestedParentCaps) { subType = { ...subType, nested: { path: nestedParentCaps.name } }; @@ -186,7 +188,7 @@ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): Fie } }); - return kibanaFormattedCaps.filter(field => { + return kibanaFormattedCaps.filter((field) => { return !['object', 'nested'].includes(field.type); }); } diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts b/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts index 7504d7bc9c460..764307bef0ba6 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts @@ -47,7 +47,7 @@ export async function resolveTimePattern(callCluster: APICaller, timePattern: st ) .sortBy((indexName: string) => indexName) .uniq(true) - .map(indexName => { + .map((indexName) => { const parsed = moment(indexName, timePattern, true); if (!parsed.isValid()) { return { @@ -69,8 +69,10 @@ export async function resolveTimePattern(callCluster: APICaller, timePattern: st .value(); return { - all: allIndexDetails.map(details => details.indexName), + all: allIndexDetails.map((details) => details.indexName), - matches: allIndexDetails.filter(details => details.isMatch).map(details => details.indexName), + matches: allIndexDetails + .filter((details) => details.isMatch) + .map((details) => details.indexName), }; } diff --git a/src/plugins/data/server/index_patterns/utils.ts b/src/plugins/data/server/index_patterns/utils.ts index b7adafaeb3e94..e841097fe49c2 100644 --- a/src/plugins/data/server/index_patterns/utils.ts +++ b/src/plugins/data/server/index_patterns/utils.ts @@ -25,7 +25,7 @@ export const getFieldByName = ( indexPattern: IIndexPattern ): IFieldType | undefined => { const fields: IFieldType[] = indexPattern && JSON.parse(indexPattern.attributes.fields); - const field = fields && fields.find(f => f.name === fieldName); + const field = fields && fields.find((f) => f.name === fieldName); return field; }; diff --git a/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts b/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts index 3dfaa9c6d0a98..d8ccdcc6a61c5 100644 --- a/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts +++ b/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts @@ -42,8 +42,8 @@ export class KqlTelemetryService implements Plugin { this.initializerContext.config.legacy.globalConfig$ .pipe(first()) .toPromise() - .then(config => makeKQLUsageCollector(usageCollection, config.kibana.index)) - .catch(e => { + .then((config) => makeKQLUsageCollector(usageCollection, config.kibana.index)) + .catch((e) => { this.initializerContext.logger .get('kql-telemetry') .warn(`Registering KQL telemetry collector failed: ${e}`); diff --git a/src/plugins/data/server/saved_objects/index_pattern_migrations.ts b/src/plugins/data/server/saved_objects/index_pattern_migrations.ts index c64f7361a8cf4..37819a13b6518 100644 --- a/src/plugins/data/server/saved_objects/index_pattern_migrations.ts +++ b/src/plugins/data/server/saved_objects/index_pattern_migrations.ts @@ -20,7 +20,7 @@ import { flow, omit } from 'lodash'; import { SavedObjectMigrationFn } from 'kibana/server'; -const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn = doc => ({ +const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn = (doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -29,12 +29,12 @@ const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn }, }); -const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn = doc => { +const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn = (doc) => { if (!doc.attributes.fields) return doc; const fieldsString = doc.attributes.fields; const fields = JSON.parse(fieldsString) as any[]; - const migratedFields = fields.map(field => { + const migratedFields = fields.map((field) => { if (field.subType === 'multi') { return { ...omit(field, 'parent'), diff --git a/src/plugins/data/server/saved_objects/search_migrations.test.ts b/src/plugins/data/server/saved_objects/search_migrations.test.ts index f9b4af7d6d2bf..69db08a689255 100644 --- a/src/plugins/data/server/saved_objects/search_migrations.test.ts +++ b/src/plugins/data/server/saved_objects/search_migrations.test.ts @@ -277,7 +277,7 @@ Object { }); }); - describe('7.4.0', function() { + describe('7.4.0', function () { const migrationFn = searchSavedObjectTypeMigrations['7.4.0']; test('transforms one dimensional sort arrays into two dimensional arrays', () => { diff --git a/src/plugins/data/server/saved_objects/search_migrations.ts b/src/plugins/data/server/saved_objects/search_migrations.ts index c8ded51193c92..2e37cd1255cee 100644 --- a/src/plugins/data/server/saved_objects/search_migrations.ts +++ b/src/plugins/data/server/saved_objects/search_migrations.ts @@ -21,7 +21,7 @@ import { flow, get } from 'lodash'; import { SavedObjectMigrationFn } from 'kibana/server'; import { DEFAULT_QUERY_LANGUAGE } from '../../common'; -const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { +const migrateMatchAllQuery: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (searchSourceJSON) { @@ -55,7 +55,7 @@ const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { return doc; }; -const migrateIndexPattern: SavedObjectMigrationFn = doc => { +const migrateIndexPattern: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (typeof searchSourceJSON !== 'string') { return doc; @@ -103,7 +103,7 @@ const setNewReferences: SavedObjectMigrationFn = (doc, context) => { return migrateIndexPattern(doc, context); }; -const migrateSearchSortToNestedArray: SavedObjectMigrationFn = doc => { +const migrateSearchSortToNestedArray: SavedObjectMigrationFn = (doc) => { const sort = get(doc, 'attributes.sort'); if (!sort) return doc; diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 5ee19cd3df19f..2a0164f113097 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -57,7 +57,7 @@ export class SearchService implements Plugin { core.savedObjects.registerType(searchSavedObjectType); - core.http.registerRouteHandlerContext<'search'>('search', context => { + core.http.registerRouteHandlerContext<'search'>('search', (context) => { return createApi({ caller: context.core.elasticsearch.dataClient.callAsCurrentUser, searchStrategies: this.searchStrategies, diff --git a/src/plugins/dev_tools/public/application.tsx b/src/plugins/dev_tools/public/application.tsx index 4e9128c327fe1..1a9d6bf4848f4 100644 --- a/src/plugins/dev_tools/public/application.tsx +++ b/src/plugins/dev_tools/public/application.tsx @@ -60,7 +60,7 @@ function DevToolsWrapper({ return (
- {devTools.map(currentDevTool => ( + {devTools.map((currentDevTool) => ( { + ref={async (element) => { if ( element && (mountedTool.current === null || @@ -172,13 +172,13 @@ export function renderApp( {devTools // Only create routes for devtools that are not disabled - .filter(devTool => !devTool.isDisabled()) - .map(devTool => ( + .filter((devTool) => !devTool.isDisabled()) + .map((devTool) => ( ( + render={(props) => ( { +const k7Breadcrumbs = ($route) => { const { indexPattern } = $route.current.locals; const { id } = $route.current.params; @@ -44,7 +44,7 @@ const k7Breadcrumbs = $route => { ]; }; -getAngularModule().config($routeProvider => { +getAngularModule().config(($routeProvider) => { $routeProvider // deprecated route, kept for compatibility // should be removed in the future @@ -97,7 +97,7 @@ function ContextAppRouteController($routeParams, $scope, $route) { 'contextAppRoute.state.predecessorCount', 'contextAppRoute.state.successorCount', ], - newValues => { + (newValues) => { const [columns, predecessorCount, successorCount] = newValues; if (Array.isArray(columns) && predecessorCount >= 0 && successorCount >= 0) { setAppState({ columns, predecessorCount, successorCount }); diff --git a/src/plugins/discover/public/application/angular/context/api/_stubs.js b/src/plugins/discover/public/application/angular/context/api/_stubs.js index acd609df203e3..35ddf396c2dba 100644 --- a/src/plugins/discover/public/application/angular/context/api/_stubs.js +++ b/src/plugins/discover/public/application/angular/context/api/_stubs.js @@ -22,7 +22,7 @@ import moment from 'moment'; export function createIndexPatternsStub() { return { - get: sinon.spy(indexPatternId => + get: sinon.spy((indexPatternId) => Promise.resolve({ id: indexPatternId, isTimeNanosBased: () => false, @@ -48,7 +48,7 @@ export function createSearchSourceStub(hits, timeField) { searchSourceStub.setParent = sinon.spy(() => searchSourceStub); searchSourceStub.setField = sinon.spy(() => searchSourceStub); - searchSourceStub.getField = sinon.spy(key => { + searchSourceStub.getField = sinon.spy((key) => { const previousSetCall = searchSourceStub.setField.withArgs(key).lastCall; return previousSetCall ? previousSetCall.args[1] : null; }); @@ -83,7 +83,7 @@ export function createContextSearchSourceStub(hits, timeField = '@timestamp') { : (first, second) => second[timeField] - first[timeField]; const filteredHits = searchSourceStub._stubHits .filter( - hit => + (hit) => moment(hit[timeField]).isSameOrAfter(timeRange.gte) && moment(hit[timeField]).isSameOrBefore(timeRange.lte) ) diff --git a/src/plugins/discover/public/application/angular/context/api/anchor.test.js b/src/plugins/discover/public/application/angular/context/api/anchor.test.js index 757e74589555a..993aefc4f59e3 100644 --- a/src/plugins/discover/public/application/angular/context/api/anchor.test.js +++ b/src/plugins/discover/public/application/angular/context/api/anchor.test.js @@ -21,8 +21,8 @@ import { createIndexPatternsStub, createSearchSourceStub } from './_stubs'; import { fetchAnchorProvider } from './anchor'; -describe('context app', function() { - describe('function fetchAnchor', function() { +describe('context app', function () { + describe('function fetchAnchor', function () { let fetchAnchor; let searchSourceStub; @@ -31,7 +31,7 @@ describe('context app', function() { fetchAnchor = fetchAnchorProvider(createIndexPatternsStub(), searchSourceStub); }); - it('should use the `fetch` method of the SearchSource', function() { + it('should use the `fetch` method of the SearchSource', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -40,7 +40,7 @@ describe('context app', function() { }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -51,7 +51,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource index pattern', function() { + it('should set the SearchSource index pattern', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -61,7 +61,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource version flag to true', function() { + it('should set the SearchSource version flag to true', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -72,7 +72,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource size to 1', function() { + it('should set the SearchSource size to 1', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -83,7 +83,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource query to an ids query', function() { + it('should set the SearchSource query to an ids query', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -105,7 +105,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource sort order', function() { + it('should set the SearchSource sort order', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -116,7 +116,7 @@ describe('context app', function() { }); }); - it('should reject with an error when no hits were found', function() { + it('should reject with an error when no hits were found', function () { searchSourceStub._stubHits = []; return fetchAnchor('INDEX_PATTERN_ID', 'id', [ @@ -126,19 +126,19 @@ describe('context app', function() { () => { expect().fail('expected the promise to be rejected'); }, - error => { + (error) => { expect(error).toBeInstanceOf(Error); } ); }); - it('should return the first hit after adding an anchor marker', function() { + it('should return the first hit after adding an anchor marker', function () { searchSourceStub._stubHits = [{ property1: 'value1' }, { property2: 'value2' }]; return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, - ]).then(anchorDocument => { + ]).then((anchorDocument) => { expect(anchorDocument).toHaveProperty('property1', 'value1'); expect(anchorDocument).toHaveProperty('$$_isAnchor', true); }); diff --git a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js index ebd4af536aabd..fcde2ade0b2c6 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js @@ -29,8 +29,8 @@ const ANCHOR_TIMESTAMP_3 = new Date(MS_PER_DAY * 3).toJSON(); const ANCHOR_TIMESTAMP_1000 = new Date(MS_PER_DAY * 1000).toJSON(); const ANCHOR_TIMESTAMP_3000 = new Date(MS_PER_DAY * 3000).toJSON(); -describe('context app', function() { - describe('function fetchPredecessors', function() { +describe('context app', function () { + describe('function fetchPredecessors', function () { let fetchPredecessors; let mockSearchSource; @@ -77,7 +77,7 @@ describe('context app', function() { }; }); - it('should perform exactly one query when enough hits are returned', function() { + it('should perform exactly one query when enough hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3000 + 2), mockSearchSource._createStubHit(MS_PER_DAY * 3000 + 1), @@ -96,13 +96,13 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(mockSearchSource.fetch.calledOnce).toBe(true); expect(hits).toEqual(mockSearchSource._stubHits.slice(0, 3)); }); }); - it('should perform multiple queries with the last being unrestricted when too few hits are returned', function() { + it('should perform multiple queries with the last being unrestricted when too few hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3010), mockSearchSource._createStubHit(MS_PER_DAY * 3002), @@ -121,7 +121,7 @@ describe('context app', function() { 0, 6, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -141,7 +141,7 @@ describe('context app', function() { }); }); - it('should perform multiple queries until the expected hit count is returned', function() { + it('should perform multiple queries until the expected hit count is returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 1700), mockSearchSource._createStubHit(MS_PER_DAY * 1200), @@ -159,7 +159,7 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -175,7 +175,7 @@ describe('context app', function() { }); }); - it('should return an empty array when no hits were found', function() { + it('should return an empty array when no hits were found', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -186,12 +186,12 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(hits).toEqual([]); }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -209,7 +209,7 @@ describe('context app', function() { }); }); - it('should set the tiebreaker sort order to the opposite as the time field', function() { + it('should set the tiebreaker sort order to the opposite as the time field', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', diff --git a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js index 452d0cc9fd1a0..0f84aa82a989a 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js @@ -30,8 +30,8 @@ const ANCHOR_TIMESTAMP = new Date(MS_PER_DAY).toJSON(); const ANCHOR_TIMESTAMP_3 = new Date(MS_PER_DAY * 3).toJSON(); const ANCHOR_TIMESTAMP_3000 = new Date(MS_PER_DAY * 3000).toJSON(); -describe('context app', function() { - describe('function fetchSuccessors', function() { +describe('context app', function () { + describe('function fetchSuccessors', function () { let fetchSuccessors; let mockSearchSource; @@ -78,7 +78,7 @@ describe('context app', function() { }; }); - it('should perform exactly one query when enough hits are returned', function() { + it('should perform exactly one query when enough hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 5000), mockSearchSource._createStubHit(MS_PER_DAY * 4000), @@ -97,13 +97,13 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(mockSearchSource.fetch.calledOnce).toBe(true); expect(hits).toEqual(mockSearchSource._stubHits.slice(-3)); }); }); - it('should perform multiple queries with the last being unrestricted when too few hits are returned', function() { + it('should perform multiple queries with the last being unrestricted when too few hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3010), mockSearchSource._createStubHit(MS_PER_DAY * 3002), @@ -122,7 +122,7 @@ describe('context app', function() { 0, 6, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -142,7 +142,7 @@ describe('context app', function() { }); }); - it('should perform multiple queries until the expected hit count is returned', function() { + it('should perform multiple queries until the expected hit count is returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3000), mockSearchSource._createStubHit(MS_PER_DAY * 3000 - 1), @@ -162,7 +162,7 @@ describe('context app', function() { 0, 4, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -179,7 +179,7 @@ describe('context app', function() { }); }); - it('should return an empty array when no hits were found', function() { + it('should return an empty array when no hits were found', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -190,12 +190,12 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(hits).toEqual([]); }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -213,7 +213,7 @@ describe('context app', function() { }); }); - it('should set the tiebreaker sort order to the same as the time field', function() { + it('should set the tiebreaker sort order to the same as the time field', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', diff --git a/src/plugins/discover/public/application/angular/context/api/context.ts b/src/plugins/discover/public/application/angular/context/api/context.ts index a47005b640538..e244176914a9b 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.ts +++ b/src/plugins/discover/public/application/angular/context/api/context.ts @@ -37,7 +37,7 @@ export type EsHitRecordList = EsHitRecord[]; const DAY_MILLIS = 24 * 60 * 60 * 1000; // look from 1 day up to 10000 days into the past and future -const LOOKUP_OFFSETS = [0, 1, 7, 30, 365, 10000].map(days => days * DAY_MILLIS); +const LOOKUP_OFFSETS = [0, 1, 7, 30, 365, 10000].map((days) => days * DAY_MILLIS); function fetchContextProvider(indexPatterns: IndexPatternsContract) { return { diff --git a/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts index 223b174718296..7cb3ac1f3f745 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts @@ -18,14 +18,14 @@ */ import { extractNanos } from './date_conversion'; -describe('function extractNanos', function() { - test('extract nanos of 2014-01-01', function() { +describe('function extractNanos', function () { + test('extract nanos of 2014-01-01', function () { expect(extractNanos('2014-01-01')).toBe('000000000'); }); - test('extract nanos of 2014-01-01T12:12:12.234Z', function() { + test('extract nanos of 2014-01-01T12:12:12.234Z', function () { expect(extractNanos('2014-01-01T12:12:12.234Z')).toBe('234000000'); }); - test('extract nanos of 2014-01-01T12:12:12.234123321Z', function() { + test('extract nanos of 2014-01-01T12:12:12.234123321Z', function () { expect(extractNanos('2014-01-01T12:12:12.234123321Z')).toBe('234123321'); }); }); diff --git a/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts index 1497f54aa5079..81533917dfff8 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts @@ -50,5 +50,5 @@ export function generateIntervals( ? 1 : -1; // ending with `null` opens the last interval - return asPairs([...offsets.map(offset => startTime + offset * offsetSign), null]); + return asPairs([...offsets.map((offset) => startTime + offset * offsetSign), null]); } diff --git a/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts index 350a0a8ede8d5..20b868367471c 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts @@ -18,8 +18,8 @@ */ import { reverseSortDir, SortDirection } from './sorting'; -describe('function reverseSortDir', function() { - test('reverse a given sort direction', function() { +describe('function reverseSortDir', function () { + test('reverse a given sort direction', function () { expect(reverseSortDir(SortDirection.asc)).toBe(SortDirection.desc); expect(reverseSortDir(SortDirection.desc)).toBe(SortDirection.asc); }); diff --git a/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts index ef1be8d48d338..2a5d6312921b8 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts @@ -36,7 +36,7 @@ const META_FIELD_NAMES: string[] = ['_seq_no', '_doc', '_uid']; */ export function getFirstSortableField(indexPattern: IndexPattern, fieldNames: string[]) { const sortableFields = fieldNames.filter( - fieldName => + (fieldName) => META_FIELD_NAMES.includes(fieldName) || // @ts-ignore (indexPattern.fields.getByName(fieldName) || { sortable: false }).sortable diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx index 325cfb2c9f0bb..8976f8ea3c107 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx @@ -25,7 +25,7 @@ import { findTestSubject } from '@elastic/eui/lib/test'; import { MAX_CONTEXT_SIZE, MIN_CONTEXT_SIZE } from '../../query_parameters/constants'; describe('Test Discover Context ActionBar for successor | predecessor records', () => { - ['successors', 'predecessors'].forEach(type => { + ['successors', 'predecessors'].forEach((type) => { const onChangeCount = jest.fn(); const props = { defaultStepSize: 5, diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx index 97a29ab21c581..ac88d2aa36696 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx @@ -131,7 +131,7 @@ export function ActionBar({ disabled={isDisabled} min={MIN_CONTEXT_SIZE} max={MAX_CONTEXT_SIZE} - onChange={ev => { + onChange={(ev) => { setNewDocCount(ev.target.valueAsNumber); }} onBlur={() => { diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts index b705b4e4faeb5..2a77b762c2966 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts @@ -19,6 +19,6 @@ import { getAngularModule } from '../../../../../kibana_services'; import { ActionBar } from './action_bar'; -getAngularModule().directive('contextActionBar', function(reactDirective: any) { +getAngularModule().directive('contextActionBar', function (reactDirective: any) { return reactDirective(ActionBar); }); diff --git a/src/plugins/discover/public/application/angular/context/query/actions.js b/src/plugins/discover/public/application/angular/context/query/actions.js index 6f8d5fe64f831..0e057e0a715c4 100644 --- a/src/plugins/discover/public/application/angular/context/query/actions.js +++ b/src/plugins/discover/public/application/angular/context/query/actions.js @@ -37,24 +37,24 @@ export function QueryActionsProvider(Promise) { indexPatterns ); - const setFailedStatus = state => (subject, details = {}) => + const setFailedStatus = (state) => (subject, details = {}) => (state.loadingStatus[subject] = { status: LOADING_STATUS.FAILED, reason: FAILURE_REASONS.UNKNOWN, ...details, }); - const setLoadedStatus = state => subject => + const setLoadedStatus = (state) => (subject) => (state.loadingStatus[subject] = { status: LOADING_STATUS.LOADED, }); - const setLoadingStatus = state => subject => + const setLoadingStatus = (state) => (subject) => (state.loadingStatus[subject] = { status: LOADING_STATUS.LOADING, }); - const fetchAnchorRow = state => () => { + const fetchAnchorRow = (state) => () => { const { queryParameters: { indexPatternId, anchorId, sort, tieBreakerField }, } = state; @@ -72,12 +72,12 @@ export function QueryActionsProvider(Promise) { return Promise.try(() => fetchAnchor(indexPatternId, anchorId, [_.zipObject([sort]), { [tieBreakerField]: sort[1] }]) ).then( - anchorDocument => { + (anchorDocument) => { setLoadedStatus(state)('anchor'); state.rows.anchor = anchorDocument; return anchorDocument; }, - error => { + (error) => { setFailedStatus(state)('anchor', { error }); getServices().toastNotifications.addDanger({ title: i18n.translate('discover.context.unableToLoadAnchorDocumentDescription', { @@ -125,12 +125,12 @@ export function QueryActionsProvider(Promise) { filters ) ).then( - documents => { + (documents) => { setLoadedStatus(state)(type); state.rows[type] = documents; return documents; }, - error => { + (error) => { setFailedStatus(state)(type, { error }); getServices().toastNotifications.addDanger({ title: i18n.translate('discover.context.unableToLoadDocumentDescription', { @@ -143,36 +143,36 @@ export function QueryActionsProvider(Promise) { ); }; - const fetchContextRows = state => () => + const fetchContextRows = (state) => () => Promise.all([ fetchSurroundingRows('predecessors', state), fetchSurroundingRows('successors', state), ]); - const fetchAllRows = state => () => + const fetchAllRows = (state) => () => Promise.try(fetchAnchorRow(state)).then(fetchContextRows(state)); - const fetchContextRowsWithNewQueryParameters = state => queryParameters => { + const fetchContextRowsWithNewQueryParameters = (state) => (queryParameters) => { setQueryParameters(state)(queryParameters); return fetchContextRows(state)(); }; - const fetchAllRowsWithNewQueryParameters = state => queryParameters => { + const fetchAllRowsWithNewQueryParameters = (state) => (queryParameters) => { setQueryParameters(state)(queryParameters); return fetchAllRows(state)(); }; - const fetchGivenPredecessorRows = state => count => { + const fetchGivenPredecessorRows = (state) => (count) => { setPredecessorCount(state)(count); return fetchSurroundingRows('predecessors', state); }; - const fetchGivenSuccessorRows = state => count => { + const fetchGivenSuccessorRows = (state) => (count) => { setSuccessorCount(state)(count); return fetchSurroundingRows('successors', state); }; - const setAllRows = state => (predecessorRows, anchorRow, successorRows) => + const setAllRows = (state) => (predecessorRows, anchorRow, successorRows) => (state.rows.all = [ ...(predecessorRows || []), ...(anchorRow ? [anchorRow] : []), diff --git a/src/plugins/discover/public/application/angular/context/query_parameters/actions.js b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js index 4f86dea08fe84..fcd4b8ac02cfb 100644 --- a/src/plugins/discover/public/application/angular/context/query_parameters/actions.js +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js @@ -23,28 +23,28 @@ import { esFilters } from '../../../../../../data/public'; import { MAX_CONTEXT_SIZE, MIN_CONTEXT_SIZE, QUERY_PARAMETER_KEYS } from './constants'; export function getQueryParameterActions(filterManager, indexPatterns) { - const setPredecessorCount = state => predecessorCount => + const setPredecessorCount = (state) => (predecessorCount) => (state.queryParameters.predecessorCount = clamp( MIN_CONTEXT_SIZE, MAX_CONTEXT_SIZE, predecessorCount )); - const setSuccessorCount = state => successorCount => + const setSuccessorCount = (state) => (successorCount) => (state.queryParameters.successorCount = clamp( MIN_CONTEXT_SIZE, MAX_CONTEXT_SIZE, successorCount )); - const setQueryParameters = state => queryParameters => + const setQueryParameters = (state) => (queryParameters) => Object.assign(state.queryParameters, _.pick(queryParameters, QUERY_PARAMETER_KEYS)); - const updateFilters = () => filters => { + const updateFilters = () => (filters) => { filterManager.setFilters(filters); }; - const addFilter = state => async (field, values, operation) => { + const addFilter = (state) => async (field, values, operation) => { const indexPatternId = state.queryParameters.indexPatternId; const newFilters = esFilters.generateFilters( filterManager, diff --git a/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts index 00747fcc81227..6309c61d3bb34 100644 --- a/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts @@ -48,7 +48,7 @@ beforeEach(() => { }; }); -describe('context query_parameter actions', function() { +describe('context query_parameter actions', function () { describe('action addFilter', () => { it('should pass the given arguments to the filterManager', () => { const { addFilter } = getQueryParameterActions(filterManager); @@ -90,7 +90,7 @@ describe('context query_parameter actions', function() { }); }); describe('action setSuccessorCount', () => { - it('should set the successorCount to the given value', function() { + it('should set the successorCount to the given value', function () { const { setSuccessorCount } = getQueryParameterActions(filterManager); setSuccessorCount(state)(20); @@ -109,10 +109,10 @@ describe('context query_parameter actions', function() { expect(state.queryParameters.successorCount).toBe(10000); }); }); - describe('action setQueryParameters', function() { + describe('action setQueryParameters', function () { const { setQueryParameters } = getQueryParameterActions(filterManager); - it('should update the queryParameters with valid properties from the given object', function() { + it('should update the queryParameters with valid properties from the given object', function () { const newState = { ...state, queryParameters: { @@ -144,7 +144,7 @@ describe('context query_parameter actions', function() { }); }); - it('should ignore invalid properties', function() { + it('should ignore invalid properties', function () { const newState = { ...state }; setQueryParameters(newState)({ diff --git a/src/plugins/discover/public/application/angular/context_app.js b/src/plugins/discover/public/application/angular/context_app.js index acb94bf97d21f..f698ed84a8948 100644 --- a/src/plugins/discover/public/application/angular/context_app.js +++ b/src/plugins/discover/public/application/angular/context_app.js @@ -69,7 +69,7 @@ function ContextAppController($scope, Private) { ...queryParameterActions, ...queryActions, }, - action => (...args) => action(this.state)(...args) + (action) => (...args) => action(this.state)(...args) ); this.constants = { @@ -83,7 +83,7 @@ function ContextAppController($scope, Private) { () => this.state.rows.anchor, () => this.state.rows.successors, ], - newValues => this.actions.setAllRows(...newValues) + (newValues) => this.actions.setAllRows(...newValues) ); /** @@ -94,7 +94,7 @@ function ContextAppController($scope, Private) { ..._.pick(this, QUERY_PARAMETER_KEYS), indexPatternId: this.indexPattern.id, }), - newQueryParameters => { + (newQueryParameters) => { const { queryParameters } = this.state; if ( newQueryParameters.indexPatternId !== queryParameters.indexPatternId || @@ -120,7 +120,7 @@ function ContextAppController($scope, Private) { predecessorCount: this.state.queryParameters.predecessorCount, successorCount: this.state.queryParameters.successorCount, }), - newParameters => { + (newParameters) => { _.assign(this, newParameters); } ); diff --git a/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts index 5b6de7f16d444..16fbb0af9f3fd 100644 --- a/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts +++ b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts @@ -27,7 +27,7 @@ interface LazyScope extends IScope { export function CollapsibleSidebarProvider() { // simply a list of all of all of angulars .col-md-* classes except 12 - const listOfWidthClasses = _.times(11, function(i) { + const listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); @@ -60,7 +60,7 @@ export function CollapsibleSidebarProvider() { // If there is are only two elements we can assume the other one will take 100% of the width. const hasSingleSibling = $siblings.length === 1 && siblingsClass; - $collapser.on('click', function() { + $collapser.on('click', function () { if (isCollapsed) { isCollapsed = false; $elem.removeClass('closed'); diff --git a/src/plugins/discover/public/application/angular/directives/debounce/debounce.js b/src/plugins/discover/public/application/angular/directives/debounce/debounce.js index 54507f673c2d6..586e8ed4fab59 100644 --- a/src/plugins/discover/public/application/angular/directives/debounce/debounce.js +++ b/src/plugins/discover/public/application/angular/directives/debounce/debounce.js @@ -22,7 +22,7 @@ import _ from 'lodash'; // borrowed heavily from https://github.com/shahata/angular-debounce export function DebounceProviderTimeout($timeout) { - return function(func, wait, options) { + return function (func, wait, options) { let timeout; let args; let self; @@ -37,7 +37,7 @@ export function DebounceProviderTimeout($timeout) { self = this; args = arguments; - const later = function() { + const later = function () { timeout = null; if (!options.leading || options.trailing) { result = func.apply(self, args); @@ -58,7 +58,7 @@ export function DebounceProviderTimeout($timeout) { return result; } - debounce.cancel = function() { + debounce.cancel = function () { $timeout.cancel(timeout); timeout = null; }; diff --git a/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts index bc08d8566d48a..ccdee153002e4 100644 --- a/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts +++ b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts @@ -31,7 +31,7 @@ import { navigationPluginMock } from '../../../../../../navigation/public/mocks' import { dataPluginMock } from '../../../../../../data/public/mocks'; import { initAngularBootstrap } from '../../../../../../kibana_legacy/public'; -describe('debounce service', function() { +describe('debounce service', function () { let debounce: (fn: () => void, timeout: number, options?: any) => any; let debounceFromProvider: (fn: () => void, timeout: number, options?: any) => any; let $timeout: ITimeoutService; @@ -61,7 +61,7 @@ describe('debounce service', function() { ); }); - it('should have a cancel method', function() { + it('should have a cancel method', function () { const bouncer = debounce(() => {}, 100); const bouncerFromProvider = debounceFromProvider(() => {}, 100); @@ -69,13 +69,13 @@ describe('debounce service', function() { expect(bouncerFromProvider).toHaveProperty('cancel'); }); - describe('delayed execution', function() { + describe('delayed execution', function () { const sandbox = sinon.createSandbox(); beforeEach(() => sandbox.useFakeTimers()); afterEach(() => sandbox.restore()); - it('should delay execution', function() { + it('should delay execution', function () { const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); @@ -92,7 +92,7 @@ describe('debounce service', function() { sinon.assert.calledOnce(spy); }); - it('should fire on leading edge', function() { + it('should fire on leading edge', function () { const bouncer = debounce(spy, 100, { leading: true }); const bouncerFromProvider = debounceFromProvider(spy, 100, { leading: true }); @@ -109,7 +109,7 @@ describe('debounce service', function() { sinon.assert.calledTwice(spy); }); - it('should only fire on leading edge', function() { + it('should only fire on leading edge', function () { const bouncer = debounce(spy, 100, { leading: true, trailing: false }); const bouncerFromProvider = debounceFromProvider(spy, 100, { leading: true, @@ -129,7 +129,7 @@ describe('debounce service', function() { sinon.assert.calledOnce(spy); }); - it('should reset delayed execution', function() { + it('should reset delayed execution', function () { const cancelSpy = sinon.spy($timeout, 'cancel'); const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); @@ -157,8 +157,8 @@ describe('debounce service', function() { }); }); - describe('cancel', function() { - it('should cancel the $timeout', function() { + describe('cancel', function () { + it('should cancel the $timeout', function () { const cancelSpy = sinon.spy($timeout, 'cancel'); const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); diff --git a/src/plugins/discover/public/application/angular/directives/fixed_scroll.js b/src/plugins/discover/public/application/angular/directives/fixed_scroll.js index bc159c14a16a7..182b4aeca9a23 100644 --- a/src/plugins/discover/public/application/angular/directives/fixed_scroll.js +++ b/src/plugins/discover/public/application/angular/directives/fixed_scroll.js @@ -33,7 +33,7 @@ export function FixedScrollProvider(Private) { return { restrict: 'A', - link: function($scope, $el) { + link: function ($scope, $el) { let $window = $(window); let $scroller = $('
').height(SCROLLER_HEIGHT); @@ -69,12 +69,12 @@ export function FixedScrollProvider(Private) { } $from.on('scroll', handler); - return function() { + return function () { $from.off('scroll', handler); }; } - unlisten = _.flow(bind($el, $scroller), bind($scroller, $el), function() { + unlisten = _.flow(bind($el, $scroller), bind($scroller, $el), function () { unlisten = _.noop; }); } @@ -141,7 +141,7 @@ export function FixedScrollProvider(Private) { $scope.$watch(debouncedCheckWidth); // cleanup when the scope is destroyed - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { cleanUp(); debouncedCheckWidth.cancel(); $scroller = $window = null; diff --git a/src/plugins/discover/public/application/angular/directives/histogram.tsx b/src/plugins/discover/public/application/angular/directives/histogram.tsx index d856be58958f1..8b646106fe52f 100644 --- a/src/plugins/discover/public/application/angular/directives/histogram.tsx +++ b/src/plugins/discover/public/application/angular/directives/histogram.tsx @@ -66,10 +66,7 @@ function findIntervalFromDuration( ) { const date = moment.tz(dateValue, timeZone); const startOfDate = moment.tz(date, timeZone).startOf(esUnit); - const endOfDate = moment - .tz(date, timeZone) - .startOf(esUnit) - .add(esValue, esUnit); + const endOfDate = moment.tz(date, timeZone).startOf(esUnit).add(esValue, esUnit); return endOfDate.valueOf() - startOfDate.valueOf(); } @@ -242,10 +239,7 @@ export class DiscoverHistogram extends Component reactDirective(DiscoverNoResults)); +app.directive('discoverNoResults', (reactDirective) => reactDirective(DiscoverNoResults)); -app.directive('discoverUninitialized', reactDirective => reactDirective(DiscoverUninitialized)); +app.directive('discoverUninitialized', (reactDirective) => reactDirective(DiscoverUninitialized)); -app.directive('discoverHistogram', reactDirective => reactDirective(DiscoverHistogram)); +app.directive('discoverHistogram', (reactDirective) => reactDirective(DiscoverHistogram)); diff --git a/src/plugins/discover/public/application/angular/discover.js b/src/plugins/discover/public/application/angular/discover.js index 84b4b2254e703..daea8b5938042 100644 --- a/src/plugins/discover/public/application/angular/discover.js +++ b/src/plugins/discover/public/application/angular/discover.js @@ -91,13 +91,13 @@ const fetchStatuses = { const app = getAngularModule(); -app.config($routeProvider => { +app.config(($routeProvider) => { const defaults = { requireDefaultIndex: true, requireUICapability: 'discover.show', k7Breadcrumbs: ($route, $injector) => $injector.invoke($route.current.params.id ? getSavedSearchBreadcrumbs : getRootBreadcrumbs), - badge: uiCapabilities => { + badge: (uiCapabilities) => { if (uiCapabilities.discover.save) { return undefined; } @@ -118,14 +118,14 @@ app.config($routeProvider => { template: indexTemplate, reloadOnSearch: false, resolve: { - savedObjects: function($route, Promise) { + savedObjects: function ($route, Promise) { const history = getHistory(); const savedSearchId = $route.current.params.id; return data.indexPatterns.ensureDefaultIndexPattern(history).then(() => { const { appStateContainer } = getState({ history }); const { index } = appStateContainer.getState(); return Promise.props({ - ip: indexPatterns.getCache().then(indexPatternList => { + ip: indexPatterns.getCache().then((indexPatternList) => { /** * In making the indexPattern modifiable it was placed in appState. Unfortunately, * the load order of AppState conflicts with the load order of many other things @@ -145,7 +145,7 @@ app.config($routeProvider => { }), savedSearch: getServices() .getSavedSearchById(savedSearchId) - .then(savedSearch => { + .then((savedSearch) => { if (savedSearchId) { chrome.recentlyAccessed.add( savedSearch.getFullPath(), @@ -179,7 +179,7 @@ app.config($routeProvider => { }); }); -app.directive('discoverApp', function() { +app.directive('discoverApp', function () { return { restrict: 'E', controllerAs: 'discoverApp', @@ -249,7 +249,7 @@ function discoverController( { filters: esFilters.FilterStateStore.APP_STATE } ); - const appStateUnsubscribe = appStateContainer.subscribe(async newState => { + const appStateUnsubscribe = appStateContainer.subscribe(async (newState) => { const { state: newStatePartial } = splitState(newState); const { state: oldStatePartial } = splitState(getPreviousAppState()); @@ -259,7 +259,7 @@ function discoverController( // detect changes that should trigger fetching of new data const changes = ['interval', 'sort', 'query'].filter( - prop => !_.isEqual(newStatePartial[prop], oldStatePartial[prop]) + (prop) => !_.isEqual(newStatePartial[prop], oldStatePartial[prop]) ); if (changes.length) { @@ -278,7 +278,7 @@ function discoverController( } }); - $scope.setIndexPattern = async id => { + $scope.setIndexPattern = async (id) => { await replaceUrlAppState({ index: id }); $route.reload(); }; @@ -294,7 +294,7 @@ function discoverController( $scope.updateDataSource(); }, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); @@ -302,7 +302,7 @@ function discoverController( requests: new RequestAdapter(), }; - $scope.timefilterUpdateHandler = ranges => { + $scope.timefilterUpdateHandler = (ranges) => { timefilter.setTime({ from: moment(ranges.from).toISOString(), to: moment(ranges.to).toISOString(), @@ -316,7 +316,7 @@ function discoverController( $scope.$watch( () => uiCapabilities.discover.saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability; } ); @@ -342,7 +342,7 @@ function discoverController( description: i18n.translate('discover.localMenu.newSearchDescription', { defaultMessage: 'New Search', }), - run: function() { + run: function () { $scope.$evalAsync(() => { history.push('/'); }); @@ -374,7 +374,7 @@ function discoverController( isTitleDuplicateConfirmed, onTitleDuplicate, }; - return saveDataSource(saveOptions).then(response => { + return saveDataSource(saveOptions).then((response) => { // If the save wasn't successful, put the original values back. if (!response.id || response.error) { savedSearch.title = currentTitle; @@ -414,7 +414,7 @@ function discoverController( testId: 'discoverOpenButton', run: () => { showOpenSearchPanel({ - makeUrl: searchId => `#/${encodeURIComponent(searchId)}`, + makeUrl: (searchId) => `#/${encodeURIComponent(searchId)}`, I18nContext: core.i18n.Context, }); }, @@ -429,7 +429,7 @@ function discoverController( defaultMessage: 'Share Search', }), testId: 'shareTopNavButton', - run: async anchorElement => { + run: async (anchorElement) => { const sharingData = await this.getSharingData(); share.toggleShareContextMenu({ anchorElement, @@ -524,8 +524,8 @@ function discoverController( return $scope.fieldCounts; } - return await new Promise(resolve => { - const unwatch = $scope.$watch('fetchStatus', newValue => { + return await new Promise((resolve) => { + const unwatch = $scope.$watch('fetchStatus', (newValue) => { if (newValue === fetchStatuses.COMPLETE) { unwatch(); resolve($scope.fieldCounts); @@ -582,8 +582,8 @@ function discoverController( fields: selectFields, metaFields: $scope.indexPattern.metaFields, conflictedTypesFields: $scope.indexPattern.fields - .filter(f => f.type === 'conflict') - .map(f => f.name), + .filter((f) => f.type === 'conflict') + .map((f) => f.name), indexPatternId: searchSource.getField('index').id, }; }; @@ -644,7 +644,7 @@ function discoverController( { next: $scope.fetch, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); subscriptions.add( @@ -656,11 +656,11 @@ function discoverController( $scope.updateTime(); }, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); - $scope.changeInterval = interval => { + $scope.changeInterval = (interval) => { if (interval) { setAppState({ interval }); } @@ -694,7 +694,7 @@ function discoverController( else return status.NO_RESULTS; } - return function() { + return function () { const current = { rows: $scope.rows, fetchStatus: $scope.fetchStatus, @@ -768,7 +768,7 @@ function discoverController( } } - $scope.opts.fetch = $scope.fetch = function() { + $scope.opts.fetch = $scope.fetch = function () { // ignore requests to fetch before the app inits if (!init.complete) return; $scope.fetchCounter++; @@ -781,7 +781,7 @@ function discoverController( $scope .updateDataSource() .then(setupVisualization) - .then(function() { + .then(function () { $scope.fetchStatus = fetchStatuses.LOADING; logInspectorRequest(); return $scope.searchSource.fetch({ @@ -789,7 +789,7 @@ function discoverController( }); }) .then(onResults) - .catch(error => { + .catch((error) => { // If the request was aborted then no need to surface this error in the UI if (error instanceof Error && error.name === 'AbortError') return; @@ -808,14 +808,14 @@ function discoverController( }); }; - $scope.updateQuery = function({ query }, isUpdate = true) { + $scope.updateQuery = function ({ query }, isUpdate = true) { if (!_.isEqual(query, appStateContainer.getState().query) || isUpdate === false) { setAppState({ query }); $fetchObservable.next(); } }; - $scope.updateSavedQueryId = newSavedQueryId => { + $scope.updateSavedQueryId = (newSavedQueryId) => { if (newSavedQueryId) { setAppState({ savedQuery: newSavedQueryId }); } else { @@ -878,9 +878,9 @@ function discoverController( // if we haven't counted yet, reset the counts const counts = ($scope.fieldCounts = $scope.fieldCounts || {}); - $scope.rows.forEach(hit => { + $scope.rows.forEach((hit) => { const fields = Object.keys($scope.indexPattern.flattenHit(hit)); - fields.forEach(fieldName => { + fields.forEach((fieldName) => { counts[fieldName] = (counts[fieldName] || 0) + 1; }); }); @@ -898,12 +898,12 @@ function discoverController( }); inspectorRequest = inspectorAdapters.requests.start(title, { description }); inspectorRequest.stats(getRequestInspectorStats($scope.searchSource)); - $scope.searchSource.getSearchRequestBody().then(body => { + $scope.searchSource.getSearchRequestBody().then((body) => { inspectorRequest.json(body); }); } - $scope.updateTime = function() { + $scope.updateTime = function () { //this is the timerange for the histogram, should be refactored $scope.timeRange = { from: dateMath.parse(timefilter.getTime().from), @@ -911,16 +911,16 @@ function discoverController( }; }; - $scope.toMoment = function(datetime) { + $scope.toMoment = function (datetime) { return moment(datetime).format(config.get('dateFormat')); }; - $scope.resetQuery = function() { + $scope.resetQuery = function () { history.push(`/${encodeURIComponent($route.current.params.id)}`); $route.reload(); }; - $scope.newQuery = function() { + $scope.newQuery = function () { history.push('/'); }; @@ -947,7 +947,7 @@ function discoverController( }; // TODO: On array fields, negating does not negate the combination, rather all terms - $scope.filterQuery = function(field, values, operation) { + $scope.filterQuery = function (field, values, operation) { $scope.indexPattern.popularizeField(field, 1); const newFilters = esFilters.generateFilters( filterManager, @@ -976,18 +976,18 @@ function discoverController( setAppState({ columns }); }; - $scope.scrollToTop = function() { + $scope.scrollToTop = function () { $window.scrollTo(0, 0); }; - $scope.scrollToBottom = function() { + $scope.scrollToBottom = function () { // delay scrolling to after the rows have been rendered $timeout(() => { $element.find('#discoverBottomMarker').focus(); }, 0); }; - $scope.showAllRows = function() { + $scope.showAllRows = function () { $scope.minimumVisibleRows = $scope.hits; }; @@ -1029,7 +1029,7 @@ function discoverController( return $scope.vis.data.aggs.onSearchRequestStart(searchSource, options); }); - $scope.searchSource.setField('aggs', function() { + $scope.searchSource.setField('aggs', function () { if (!$scope.vis) return; return $scope.vis.data.aggs.toDsl(); }); diff --git a/src/plugins/discover/public/application/angular/doc.ts b/src/plugins/discover/public/application/angular/doc.ts index 45075f3742f3e..347caa0f3431c 100644 --- a/src/plugins/discover/public/application/angular/doc.ts +++ b/src/plugins/discover/public/application/angular/doc.ts @@ -28,7 +28,7 @@ interface LazyScope extends ng.IScope { const { timefilter } = getServices(); const app = getAngularModule(); -app.directive('discoverDoc', function(reactDirective: any) { +app.directive('discoverDoc', function (reactDirective: any) { return reactDirective( Doc, [ @@ -51,7 +51,7 @@ app.config(($routeProvider: any) => { .when('/doc/:indexPattern/:index', { // have to be written as function expression, because it's not compiled in dev mode // eslint-disable-next-line object-shorthand - controller: function($scope: LazyScope, $route: any, es: any) { + controller: function ($scope: LazyScope, $route: any, es: any) { timefilter.disableAutoRefreshSelector(); timefilter.disableTimeRangeSelector(); $scope.esClient = es; diff --git a/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts b/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts index cec1a097da5bf..8257c79af7e8a 100644 --- a/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts +++ b/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts @@ -24,7 +24,7 @@ */ function buildColumns(columns: string[]) { if (columns.length > 1 && columns.indexOf('_source') !== -1) { - return columns.filter(col => col !== '_source'); + return columns.filter((col) => col !== '_source'); } else if (columns.length !== 0) { return columns; } @@ -42,7 +42,7 @@ export function removeColumn(columns: string[], columnName: string) { if (!columns.includes(columnName)) { return columns; } - return buildColumns(columns.filter(col => col !== columnName)); + return buildColumns(columns.filter((col) => col !== columnName)); } export function moveColumn(columns: string[], columnName: string, newIndex: number) { diff --git a/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx index 2ca53d5a34b03..dd5f2a10b8a77 100644 --- a/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx @@ -51,7 +51,7 @@ export function TableHeader({ return ( - {displayedColumns.map(col => { + {displayedColumns.map((col) => { return ( name === sortPair[0]) || []; - const currentSortWithoutColumn = sortOrder.filter(pair => pair[0] !== name); - const currentColumnSort = sortOrder.find(pair => pair[0] === name); + const [, sortDirection = ''] = sortOrder.find((sortPair) => name === sortPair[0]) || []; + const currentSortWithoutColumn = sortOrder.filter((pair) => pair[0] !== name); + const currentColumnSort = sortOrder.find((pair) => pair[0] === name); const currentColumnSortDirection = (currentColumnSort && currentColumnSort[1]) || ''; const btnSortIcon = sortDirectionToIcon[sortDirection]; @@ -172,7 +172,7 @@ export function TableHeaderColumn({ {displayName} {buttons - .filter(button => button.active) + .filter((button) => button.active) .map((button, idx) => ( { indexPattern = FixturesStubbedLogstashIndexPatternProvider() as IndexPattern; }); - describe('getSort function', function() { - test('should be a function', function() { + describe('getSort function', function () { + test('should be a function', function () { expect(typeof getSort === 'function').toBeTruthy(); }); - test('should return an array of objects', function() { + test('should return an array of objects', function () { expect(getSort([['bytes', 'desc']], indexPattern)).toEqual([{ bytes: 'desc' }]); delete indexPattern.timeFieldName; @@ -45,7 +45,7 @@ describe('docTable', function() { expect(getSort([{ bytes: 'desc' }], indexPattern)).toEqual([{ bytes: 'desc' }]); }); - test('should return an empty array when passed an unsortable field', function() { + test('should return an empty array when passed an unsortable field', function () { expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); expect(getSort([['lol_nope', 'asc']], indexPattern)).toEqual([]); @@ -53,27 +53,27 @@ describe('docTable', function() { expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); }); - test('should return an empty array ', function() { + test('should return an empty array ', function () { expect(getSort([], indexPattern)).toEqual([]); expect(getSort([['foo', 'bar']], indexPattern)).toEqual([]); expect(getSort([{ foo: 'bar' }], indexPattern)).toEqual([]); }); }); - describe('getSortArray function', function() { - test('should have an array method', function() { + describe('getSortArray function', function () { + test('should have an array method', function () { expect(getSortArray).toBeInstanceOf(Function); }); - test('should return an array of arrays for sortable fields', function() { + test('should return an array of arrays for sortable fields', function () { expect(getSortArray([['bytes', 'desc']], indexPattern)).toEqual([['bytes', 'desc']]); }); - test('should return an array of arrays from an array of elasticsearch sort objects', function() { + test('should return an array of arrays from an array of elasticsearch sort objects', function () { expect(getSortArray([{ bytes: 'desc' }], indexPattern)).toEqual([['bytes', 'desc']]); }); - test('should sort by an empty array when an unsortable field is given', function() { + test('should sort by an empty array when an unsortable field is given', function () { expect(getSortArray([{ 'non-sortable': 'asc' }], indexPattern)).toEqual([]); expect(getSortArray([{ lol_nope: 'asc' }], indexPattern)).toEqual([]); diff --git a/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts b/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts index aa23aa4390673..c28519692318e 100644 --- a/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts +++ b/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts @@ -57,7 +57,7 @@ export function getSort(sort: SortPair[], indexPattern: IndexPattern): SortPairO if (Array.isArray(sort)) { return sort .map((sortPair: SortPair) => createSortObject(sortPair, indexPattern)) - .filter(sortPairObj => typeof sortPairObj === 'object') as SortPairObj[]; + .filter((sortPairObj) => typeof sortPairObj === 'object') as SortPairObj[]; } return []; } @@ -67,5 +67,5 @@ export function getSort(sort: SortPair[], indexPattern: IndexPattern): SortPairO * [[fieldToSort: directionToSort]] */ export function getSortArray(sort: SortPair[], indexPattern: IndexPattern) { - return getSort(sort, indexPattern).map(sortPair => Object.entries(sortPair).pop()); + return getSort(sort, indexPattern).map((sortPair) => Object.entries(sortPair).pop()); } diff --git a/src/plugins/discover/public/application/angular/helpers/point_series.ts b/src/plugins/discover/public/application/angular/helpers/point_series.ts index db0ca85b0399a..4c280bf43ea12 100644 --- a/src/plugins/discover/public/application/angular/helpers/point_series.ts +++ b/src/plugins/discover/public/application/angular/helpers/point_series.ts @@ -84,7 +84,7 @@ export const buildPointSeriesData = (table: Table, dimensions: Dimensions) => { const yAccessor = table.columns[y.accessor].id; const chart = {} as Chart; - chart.xAxisOrderedValues = uniq(table.rows.map(r => r[xAccessor] as number)); + chart.xAxisOrderedValues = uniq(table.rows.map((r) => r[xAccessor] as number)); chart.xAxisFormat = x.format; chart.xAxisLabel = table.columns[x.accessor].name; @@ -101,8 +101,8 @@ export const buildPointSeriesData = (table: Table, dimensions: Dimensions) => { chart.yAxisLabel = table.columns[y.accessor].name; chart.values = table.rows - .filter(row => row && row[yAccessor] !== 'NaN') - .map(row => ({ + .filter((row) => row && row[yAccessor] !== 'NaN') + .map((row) => ({ x: row[xAccessor] as number, y: row[yAccessor] as number, })); diff --git a/src/plugins/discover/public/application/angular/response_handler.js b/src/plugins/discover/public/application/angular/response_handler.js index 04ccb67ec7e25..00a9ee934430d 100644 --- a/src/plugins/discover/public/application/angular/response_handler.js +++ b/src/plugins/discover/public/application/angular/response_handler.js @@ -87,7 +87,7 @@ function convertTableGroup(tableGroup, convertTable) { const out = {}; let outList; - tables.forEach(function(table) { + tables.forEach(function (table) { if (!outList) { const direction = tableGroup.direction === 'row' ? 'rows' : 'columns'; outList = out[direction] = []; @@ -105,7 +105,7 @@ function convertTableGroup(tableGroup, convertTable) { export const discoverResponseHandler = (response, dimensions) => { const tableGroup = tableResponseHandler(response, dimensions); - let converted = convertTableGroup(tableGroup, table => { + let converted = convertTableGroup(tableGroup, (table) => { return buildPointSeriesData(table, dimensions); }); if (!converted) { diff --git a/src/plugins/discover/public/application/components/doc/doc.test.tsx b/src/plugins/discover/public/application/components/doc/doc.test.tsx index 2cbc1547d1082..0bc621714c70f 100644 --- a/src/plugins/discover/public/application/components/doc/doc.test.tsx +++ b/src/plugins/discover/public/application/components/doc/doc.test.tsx @@ -53,7 +53,7 @@ beforeEach(() => { const waitForPromises = async () => act(async () => { - await new Promise(resolve => setTimeout(resolve)); + await new Promise((resolve) => setTimeout(resolve)); }); /** diff --git a/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx b/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx index ae5fbd05b0aaf..84ad19dbddcbf 100644 --- a/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx +++ b/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx @@ -23,7 +23,7 @@ import { HitsCounter, HitsCounterProps } from './hits_counter'; // @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; -describe('hits counter', function() { +describe('hits counter', function () { let props: HitsCounterProps; let component: ReactWrapper; @@ -47,13 +47,13 @@ describe('hits counter', function() { expect(findTestSubject(component, 'resetSavedSearch').length).toBe(0); }); - it('expect to render the number of hits', function() { + it('expect to render the number of hits', function () { component = mountWithIntl(); const hits = findTestSubject(component, 'discoverQueryHits'); expect(hits.text()).toBe('2'); }); - it('expect to render 1,899 hits if 1899 hits given', function() { + it('expect to render 1,899 hits if 1899 hits given', function () { component = mountWithIntl( ); @@ -61,7 +61,7 @@ describe('hits counter', function() { expect(hits.text()).toBe('1,899'); }); - it('should reset query', function() { + it('should reset query', function () { component = mountWithIntl(); findTestSubject(component, 'resetSavedSearch').simulate('click'); expect(props.onResetQuery).toHaveBeenCalled(); diff --git a/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx b/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx index 9d304bfa9c27d..4a539b618f817 100644 --- a/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx +++ b/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx @@ -51,7 +51,7 @@ export function ChangeIndexPattern({ }) { const [isPopoverOpen, setPopoverIsOpen] = useState(false); - const createTrigger = function() { + const createTrigger = function () { const { label, title, ...rest } = trigger; return ( { + onChange={(choices) => { const choice = (choices.find(({ checked }) => checked) as unknown) as { value: string; }; diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx index 7372fab075ea3..8c527475b7480 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx @@ -92,18 +92,18 @@ function getComponent(selected = false, showDetails = false, useShortDots = fals return { comp, props }; } -describe('discover sidebar field', function() { - it('should allow selecting fields', function() { +describe('discover sidebar field', function () { + it('should allow selecting fields', function () { const { comp, props } = getComponent(); findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onAddField).toHaveBeenCalledWith('bytes'); }); - it('should allow deselecting fields', function() { + it('should allow deselecting fields', function () { const { comp, props } = getComponent(true); findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onRemoveField).toHaveBeenCalledWith('bytes'); }); - it('should trigger onShowDetails', function() { + it('should trigger onShowDetails', function () { const { comp, props } = getComponent(); findTestSubject(comp, 'field-bytes-showDetails').simulate('click'); expect(props.onShowDetails).toHaveBeenCalledWith(true, props.field); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx index a533b798ad09f..99dad418c04bd 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx @@ -80,7 +80,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { defaultMessage: 'Type', }); const typeOptions = types - ? types.map(type => { + ? types.map((type) => { return { value: type, text: type }; }) : [{ value: 'any', text: 'any' }]; @@ -224,7 +224,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { legend={legend} options={toggleButtons(id)} idSelected={`${id}-${values[id]}`} - onChange={optionId => handleValueChange(id, optionId.replace(`${id}-`, ''))} + onChange={(optionId) => handleValueChange(id, optionId.replace(`${id}-`, ''))} buttonSize="compressed" isFullWidth data-test-subj={`${id}ButtonGroup`} @@ -257,7 +257,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { data-test-subj="fieldFilterSearchInput" compressed fullWidth - onChange={event => onChange('name', event.currentTarget.value)} + onChange={(event) => onChange('name', event.currentTarget.value)} placeholder={searchPlaceholder} value={value} /> diff --git a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx index 79417c07501a3..24e6f5993a0a5 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx @@ -53,18 +53,11 @@ const defaultProps = { }; function getIndexPatternPickerList(instance: ShallowWrapper) { - return instance - .find(ChangeIndexPattern) - .first() - .dive() - .find(EuiSelectable); + return instance.find(ChangeIndexPattern).first().dive().find(EuiSelectable); } function getIndexPatternPickerOptions(instance: ShallowWrapper) { - return getIndexPatternPickerList(instance) - .dive() - .find(EuiSelectableList) - .prop('options'); + return getIndexPatternPickerList(instance).dive().find(EuiSelectableList).prop('options'); } function selectIndexPatternPickerOption(instance: ShallowWrapper, selectedLabel: string) { diff --git a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx index 3b01d5e7a9e62..3acdcb1e92091 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx @@ -46,7 +46,7 @@ export function DiscoverIndexPattern({ selectedIndexPattern, setIndexPattern, }: DiscoverIndexPatternProps) { - const options: IndexPatternRef[] = (indexPatternList || []).map(entity => ({ + const options: IndexPatternRef[] = (indexPatternList || []).map((entity) => ({ id: entity.id, title: entity.attributes!.title, })); @@ -76,8 +76,8 @@ export function DiscoverIndexPattern({ }} indexPatternId={selected.id} indexPatternRefs={options} - onChangeIndexPattern={id => { - const indexPattern = options.find(pattern => pattern.id === id); + onChangeIndexPattern={(id) => { + const indexPattern = options.find((pattern) => pattern.id === id); if (indexPattern) { setIndexPattern(id); setSelected(indexPattern); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx index c7512824d7d44..60011914e8f74 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx @@ -59,7 +59,7 @@ jest.mock('../../../kibana_services', () => ({ })); jest.mock('./lib/get_index_pattern_field_list', () => ({ - getIndexPatternFieldList: jest.fn(indexPattern => indexPattern.fields), + getIndexPatternFieldList: jest.fn((indexPattern) => indexPattern.fields), })); function getCompProps() { @@ -102,7 +102,7 @@ function getCompProps() { }; } -describe('discover sidebar', function() { +describe('discover sidebar', function () { let props: DiscoverSidebarProps; let comp: ReactWrapper; @@ -111,7 +111,7 @@ describe('discover sidebar', function() { comp = mountWithIntl(); }); - it('should have Selected Fields and Available Fields with Popular Fields sections', function() { + it('should have Selected Fields and Available Fields with Popular Fields sections', function () { const popular = findTestSubject(comp, 'fieldList-popular'); const selected = findTestSubject(comp, 'fieldList-selected'); const unpopular = findTestSubject(comp, 'fieldList-unpopular'); @@ -119,15 +119,15 @@ describe('discover sidebar', function() { expect(unpopular.children().length).toBe(7); expect(selected.children().length).toBe(1); }); - it('should allow selecting fields', function() { + it('should allow selecting fields', function () { findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onAddField).toHaveBeenCalledWith('bytes'); }); - it('should allow deselecting fields', function() { + it('should allow deselecting fields', function () { findTestSubject(comp, 'fieldToggle-extension').simulate('click'); expect(props.onRemoveField).toHaveBeenCalledWith('extension'); }); - it('should allow adding filters', function() { + it('should allow adding filters', function () { findTestSubject(comp, 'field-extension-showDetails').simulate('click'); findTestSubject(comp, 'plus-extension-gif').simulate('click'); expect(props.onAddFilter).toHaveBeenCalled(); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx index 0d9aebe11ece6..99a5547ed0760 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx @@ -174,7 +174,7 @@ export function DiscoverSidebar({ o.attributes.title)} + indexPatternList={sortBy(indexPatternList, (o) => o.attributes.title)} />
diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js index c2d225360d0ef..e055d644e1f91 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js @@ -23,7 +23,7 @@ import { i18n } from '@kbn/i18n'; function getFieldValues(hits, field) { const name = field.name; const flattenHit = field.indexPattern.flattenHit; - return _.map(hits, function(hit) { + return _.map(hits, function (hit) { return flattenHit(hit)[name]; }); } @@ -55,18 +55,13 @@ function getFieldValueCounts(params) { try { const groups = _groupValues(allValues, params); - counts = _.map( - _.sortBy(groups, 'count') - .reverse() - .slice(0, params.count), - function(bucket) { - return { - value: bucket.value, - count: bucket.count, - percent: ((bucket.count / (params.hits.length - missing)) * 100).toFixed(1), - }; - } - ); + counts = _.map(_.sortBy(groups, 'count').reverse().slice(0, params.count), function (bucket) { + return { + value: bucket.value, + count: bucket.count, + percent: ((bucket.count / (params.hits.length - missing)) * 100).toFixed(1), + }; + }); if (params.hits.length - missing === 0) { return { @@ -103,7 +98,7 @@ function _groupValues(allValues, params) { const groups = {}; let k; - allValues.forEach(function(value) { + allValues.forEach(function (value) { if (_.isObject(value) && !Array.isArray(value)) { throw new Error( i18n.translate( @@ -121,7 +116,7 @@ function _groupValues(allValues, params) { k = value == null ? undefined : [value]; } - _.each(k, function(key) { + _.each(k, function (key) { if (groups.hasOwnProperty(key)) { groups[key].count++; } else { diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts index fdfc536485579..875cbf4075aa2 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts @@ -31,8 +31,8 @@ import { fieldCalculator } from './field_calculator'; let indexPattern: IndexPattern; -describe('fieldCalculator', function() { - beforeEach(function() { +describe('fieldCalculator', function () { + beforeEach(function () { indexPattern = new StubIndexPattern( 'logstash-*', (cfg: any) => cfg, @@ -41,7 +41,7 @@ describe('fieldCalculator', function() { coreMock.createStart() ); }); - it('should have a _countMissing that counts nulls & undefineds in an array', function() { + it('should have a _countMissing that counts nulls & undefineds in an array', function () { const values = [ ['foo', 'bar'], 'foo', @@ -59,11 +59,11 @@ describe('fieldCalculator', function() { expect(fieldCalculator._countMissing(values)).toBe(5); }); - describe('_groupValues', function() { + describe('_groupValues', function () { let groups: Record; let params: any; let values: any; - beforeEach(function() { + beforeEach(function () { values = [ ['foo', 'bar'], 'foo', @@ -82,17 +82,17 @@ describe('fieldCalculator', function() { groups = fieldCalculator._groupValues(values, params); }); - it('should have a _groupValues that counts values', function() { + it('should have a _groupValues that counts values', function () { expect(groups).toBeInstanceOf(Object); }); - it('should throw an error if any value is a plain object', function() { - expect(function() { + it('should throw an error if any value is a plain object', function () { + expect(function () { fieldCalculator._groupValues([{}, true, false], params); }).toThrowError(); }); - it('should handle values with dots in them', function() { + it('should handle values with dots in them', function () { values = ['0', '0.........', '0.......,.....']; params = {}; groups = fieldCalculator._groupValues(values, params); @@ -101,36 +101,36 @@ describe('fieldCalculator', function() { expect(groups[values[2]].count).toBe(1); }); - it('should have a a key for value in the array when not grouping array terms', function() { + it('should have a a key for value in the array when not grouping array terms', function () { expect(_.keys(groups).length).toBe(3); expect(groups.foo).toBeInstanceOf(Object); expect(groups.bar).toBeInstanceOf(Object); expect(groups.baz).toBeInstanceOf(Object); }); - it('should count array terms independently', function() { + it('should count array terms independently', function () { expect(groups['foo,bar']).toBe(undefined); expect(groups.foo.count).toBe(5); expect(groups.bar.count).toBe(3); expect(groups.baz.count).toBe(1); }); - describe('grouped array terms', function() { - beforeEach(function() { + describe('grouped array terms', function () { + beforeEach(function () { params.grouped = true; groups = fieldCalculator._groupValues(values, params); }); - it('should group array terms when passed params.grouped', function() { + it('should group array terms when passed params.grouped', function () { expect(_.keys(groups).length).toBe(4); expect(groups['foo,bar']).toBeInstanceOf(Object); }); - it('should contain the original array as the value', function() { + it('should contain the original array as the value', function () { expect(groups['foo,bar'].value).toEqual(['foo', 'bar']); }); - it('should count the pairs separately from the values they contain', function() { + it('should count the pairs separately from the values they contain', function () { expect(groups['foo,bar'].count).toBe(2); expect(groups.foo.count).toBe(3); expect(groups.bar.count).toBe(1); @@ -138,32 +138,32 @@ describe('fieldCalculator', function() { }); }); - describe('getFieldValues', function() { + describe('getFieldValues', function () { let hits: any; - beforeEach(function() { + beforeEach(function () { hits = _.each(_.cloneDeep(realHits), indexPattern.flattenHit); }); - it('Should return an array of values for _source fields', function() { + it('Should return an array of values for _source fields', function () { const extensions = fieldCalculator.getFieldValues( hits, indexPattern.fields.getByName('extension') ); expect(extensions).toBeInstanceOf(Array); expect( - _.filter(extensions, function(v) { + _.filter(extensions, function (v) { return v === 'html'; }).length ).toBe(8); expect(_.uniq(_.clone(extensions)).sort()).toEqual(['gif', 'html', 'php', 'png']); }); - it('Should return an array of values for core meta fields', function() { + it('Should return an array of values for core meta fields', function () { const types = fieldCalculator.getFieldValues(hits, indexPattern.fields.getByName('_type')); expect(types).toBeInstanceOf(Array); expect( - _.filter(types, function(v) { + _.filter(types, function (v) { return v === 'apache'; }).length ).toBe(18); @@ -171,9 +171,9 @@ describe('fieldCalculator', function() { }); }); - describe('getFieldValueCounts', function() { + describe('getFieldValueCounts', function () { let params: { hits: any; field: any; count: number }; - beforeEach(function() { + beforeEach(function () { params = { hits: _.cloneDeep(realHits), field: indexPattern.fields.getByName('extension'), @@ -181,7 +181,7 @@ describe('fieldCalculator', function() { }; }); - it('counts the top 3 values', function() { + it('counts the top 3 values', function () { const extensions = fieldCalculator.getFieldValueCounts(params); expect(extensions).toBeInstanceOf(Object); expect(extensions.buckets).toBeInstanceOf(Array); @@ -190,7 +190,7 @@ describe('fieldCalculator', function() { expect(extensions.error).toBe(undefined); }); - it('fails to analyze geo and attachment types', function() { + it('fails to analyze geo and attachment types', function () { params.field = indexPattern.fields.getByName('point'); expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); @@ -201,16 +201,16 @@ describe('fieldCalculator', function() { expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); }); - it('fails to analyze fields that are in the mapping, but not the hits', function() { + it('fails to analyze fields that are in the mapping, but not the hits', function () { params.field = indexPattern.fields.getByName('ip'); expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); }); - it('counts the total hits', function() { + it('counts the total hits', function () { expect(fieldCalculator.getFieldValueCounts(params).total).toBe(params.hits.length); }); - it('counts the hits the field exists in', function() { + it('counts the hits the field exists in', function () { params.field = indexPattern.fields.getByName('phpmemory'); expect(fieldCalculator.getFieldValueCounts(params).exists).toBe(5); }); diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts index 1351433e9dd0e..eb139f97c7b00 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts @@ -20,8 +20,8 @@ import { getDefaultFieldFilter, setFieldFilterProp, isFieldFiltered } from './field_filter'; import { IndexPatternField } from '../../../../../../data/public'; -describe('field_filter', function() { - it('getDefaultFieldFilter should return default filter state', function() { +describe('field_filter', function () { + it('getDefaultFieldFilter should return default filter state', function () { expect(getDefaultFieldFilter()).toMatchInlineSnapshot(` Object { "aggregatable": null, @@ -32,7 +32,7 @@ describe('field_filter', function() { } `); }); - it('setFieldFilterProp should return allow filter changes', function() { + it('setFieldFilterProp should return allow filter changes', function () { const state = getDefaultFieldFilter(); const targetState = { aggregatable: true, @@ -83,12 +83,12 @@ describe('field_filter', function() { { filter: { aggregatable: true }, result: ['extension'] }, { filter: { aggregatable: true, searchable: false }, result: [] }, { filter: { type: 'string' }, result: ['extension'] }, - ].forEach(test => { + ].forEach((test) => { const filtered = fieldList - .filter(field => + .filter((field) => isFieldFiltered(field, { ...defaultState, ...test.filter }, { bytes: 1, extension: 1 }) ) - .map(field => field.name); + .map((field) => field.name); expect(filtered).toEqual(test.result); }); diff --git a/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts b/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts index 63e1b761f4dd0..0fcbe925e0798 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts @@ -31,7 +31,7 @@ export function getIndexPatternFieldList( const fieldNamesInDocs = Object.keys(fieldCounts); const fieldNamesInIndexPattern = map(indexPattern.fields, 'name'); - difference(fieldNamesInDocs, fieldNamesInIndexPattern).forEach(unknownFieldName => { + difference(fieldNamesInDocs, fieldNamesInIndexPattern).forEach((unknownFieldName) => { fieldSpecs.push({ name: String(unknownFieldName), type: 'unknown', diff --git a/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts b/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts index 138e805405c89..c57ee197d856f 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts @@ -34,7 +34,7 @@ export function getWarnings(field: IndexPatternField) { } if (warnings.length > 1) { - warnings = warnings.map(function(warning, i) { + warnings = warnings.map(function (warning, i) { return (i > 0 ? '\n' : '') + (i + 1) + ' - ' + warning; }); } diff --git a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts index e83287a139dd0..d4670a1e76011 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts @@ -20,8 +20,8 @@ import { groupFields } from './group_fields'; import { getDefaultFieldFilter } from './field_filter'; -describe('group_fields', function() { - it('should group fields in selected, popular, unpopular group', function() { +describe('group_fields', function () { + it('should group fields in selected, popular, unpopular group', function () { const fields = [ { name: 'category', diff --git a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx index e4e5f00172371..fab4637d87ca7 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx +++ b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx @@ -45,9 +45,9 @@ export function groupFields( } const popular = fields - .filter(field => !columns.includes(field.name) && field.count) + .filter((field) => !columns.includes(field.name) && field.count) .sort((a: IndexPatternField, b: IndexPatternField) => (b.count || 0) - (a.count || 0)) - .map(field => field.name) + .map((field) => field.name) .slice(0, popularLimit); const compareFn = (a: IndexPatternField, b: IndexPatternField) => { diff --git a/src/plugins/discover/public/application/components/table/table.test.tsx b/src/plugins/discover/public/application/components/table/table.test.tsx index 04cf5d80da585..0793072fd0cf4 100644 --- a/src/plugins/discover/public/application/components/table/table.test.tsx +++ b/src/plugins/discover/public/application/components/table/table.test.tsx @@ -58,11 +58,11 @@ const indexPattern = { ], metaFields: ['_index', '_score'], flattenHit: undefined, - formatHit: jest.fn(hit => hit._source), + formatHit: jest.fn((hit) => hit._source), } as IndexPattern; indexPattern.fields.getByName = (name: string) => { - return indexPattern.fields.find(field => field.name === name); + return indexPattern.fields.find((field) => field.name === name); }; indexPattern.flattenHit = indexPatterns.flattenHitWrapper(indexPattern, indexPattern.metaFields); @@ -146,7 +146,7 @@ describe('DocViewTable at Discover', () => { toggleColumnButton: true, underScoreWarning: false, }, - ].forEach(check => { + ].forEach((check) => { const rowComponent = findTestSubject(component, `tableDocViewRow-${check._property}`); it(`renders row for ${check._property}`, () => { @@ -158,7 +158,7 @@ describe('DocViewTable at Discover', () => { 'collapseBtn', 'toggleColumnButton', 'underscoreWarning', - ] as const).forEach(element => { + ] as const).forEach((element) => { const elementExist = check[element]; if (typeof elementExist === 'boolean') { @@ -172,7 +172,7 @@ describe('DocViewTable at Discover', () => { } }); - (['noMappingWarning'] as const).forEach(element => { + (['noMappingWarning'] as const).forEach((element) => { const elementExist = check[element]; if (typeof elementExist === 'boolean') { diff --git a/src/plugins/discover/public/application/components/table/table.tsx b/src/plugins/discover/public/application/components/table/table.tsx index 6789f753899f5..9b95f2fc6bd27 100644 --- a/src/plugins/discover/public/application/components/table/table.tsx +++ b/src/plugins/discover/public/application/components/table/table.tsx @@ -47,7 +47,7 @@ export function DocViewTable({ {Object.keys(flattened) .sort() - .map(field => { + .map((field) => { const valueRaw = flattened[field]; const value = trimAngularSpan(String(formatted[field])); @@ -104,15 +104,15 @@ export function DocViewTable({ // to the index pattern, but that has its own complications which you can read more about in the following // issue: https://github.com/elastic/kibana/issues/54957 const isNestedField = - !indexPattern.fields.find(patternField => patternField.name === field) && - !!indexPattern.fields.find(patternField => { + !indexPattern.fields.find((patternField) => patternField.name === field) && + !!indexPattern.fields.find((patternField) => { // We only want to match a full path segment const nestedRootRegex = new RegExp(escapeRegExp(field) + '(\\.|$)'); return nestedRootRegex.test(patternField.subType?.nested?.path ?? ''); }); const fieldType = isNestedField ? 'nested' - : indexPattern.fields.find(patternField => patternField.name === field)?.type; + : indexPattern.fields.find((patternField) => patternField.name === field)?.type; return ( typeof v === 'object' && v !== null); + return Array.isArray(value) && value.some((v) => typeof v === 'object' && v !== null); } /** diff --git a/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx b/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx index 642774d6be202..964f94ca9d9b2 100644 --- a/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx +++ b/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx @@ -24,7 +24,7 @@ import { EuiIconTip } from '@elastic/eui'; // @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; -describe('timechart header', function() { +describe('timechart header', function () { let props: TimechartHeaderProps; let component: ReactWrapper; @@ -65,7 +65,7 @@ describe('timechart header', function() { expect(component.find(EuiIconTip).length).toBe(1); }); - it('expect to render the date range', function() { + it('expect to render the date range', function () { component = mountWithIntl(); const datetimeRangeText = findTestSubject(component, 'discoverIntervalDateRange'); expect(datetimeRangeText.text()).toBe( @@ -78,14 +78,14 @@ describe('timechart header', function() { const dropdown = findTestSubject(component, 'discoverIntervalSelect'); expect(dropdown.length).toBe(1); // @ts-ignore - const values = dropdown.find('option').map(option => option.prop('value')); + const values = dropdown.find('option').map((option) => option.prop('value')); expect(values).toEqual(['auto', 'ms', 's']); // @ts-ignore - const labels = dropdown.find('option').map(option => option.text()); + const labels = dropdown.find('option').map((option) => option.text()); expect(labels).toEqual(['Auto', 'Millisecond', 'Second']); }); - it('should change the interval', function() { + it('should change the interval', function () { component = mountWithIntl(); findTestSubject(component, 'discoverIntervalSelect').simulate('change', { target: { value: 'ms' }, diff --git a/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx b/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx index 077adcb6b006e..8789847058aff 100644 --- a/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx +++ b/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx @@ -147,9 +147,7 @@ export function TimechartHeader({ size="s" type="alert" /> - ) : ( - undefined - ) + ) : undefined } /> diff --git a/src/plugins/discover/public/application/components/top_nav/open_search_panel.js b/src/plugins/discover/public/application/components/top_nav/open_search_panel.js index 06267407dcb21..4266035a5bb4f 100644 --- a/src/plugins/discover/public/application/components/top_nav/open_search_panel.js +++ b/src/plugins/discover/public/application/components/top_nav/open_search_panel.js @@ -71,7 +71,7 @@ export function OpenSearchPanel(props) { }), }, ]} - onChoose={id => { + onChoose={(id) => { window.location.assign(props.makeUrl(id)); props.onClose(); }} diff --git a/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx b/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx index b9932da0523f8..958b7b6f8705b 100644 --- a/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx +++ b/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx @@ -79,7 +79,7 @@ export function convertDirectiveToRenderFn( directive.controller, getInjector ); - cleanupFnPromise.catch(e => { + cleanupFnPromise.catch((e) => { rejected = true; render(, domNode); }); @@ -88,7 +88,7 @@ export function convertDirectiveToRenderFn( if (!rejected) { // for cleanup // http://roubenmeschian.com/rubo/?p=51 - cleanupFnPromise.then(cleanup => cleanup()); + cleanupFnPromise.then((cleanup) => cleanup()); } }; }; diff --git a/src/plugins/discover/public/application/doc_views/doc_views_registry.ts b/src/plugins/discover/public/application/doc_views/doc_views_registry.ts index cdc22155f4710..589ecd4efe0f5 100644 --- a/src/plugins/discover/public/application/doc_views/doc_views_registry.ts +++ b/src/plugins/discover/public/application/doc_views/doc_views_registry.ts @@ -53,7 +53,7 @@ export class DocViewsRegistry { */ getDocViewsSorted(hit: ElasticSearchHit) { return this.docViews - .filter(docView => docView.shouldShow(hit)) + .filter((docView) => docView.shouldShow(hit)) .sort((a, b) => (Number(a.order) > Number(b.order) ? 1 : -1)); } } diff --git a/src/plugins/discover/public/application/embeddable/search_embeddable.ts b/src/plugins/discover/public/application/embeddable/search_embeddable.ts index ed70c90eb64e6..77d1572b0a40c 100644 --- a/src/plugins/discover/public/application/embeddable/search_embeddable.ts +++ b/src/plugins/discover/public/application/embeddable/search_embeddable.ts @@ -212,7 +212,7 @@ export class SearchEmbeddable extends Embeddable this.pushContainerStateParamsToScope(searchScope); - searchScope.setSortOrder = sort => { + searchScope.setSortOrder = (sort) => { this.updateInput({ sort }); }; @@ -249,7 +249,7 @@ export class SearchEmbeddable extends Embeddable operator, indexPattern.id! ); - filters = filters.map(filter => ({ + filters = filters.map((filter) => ({ ...filter, $state: { store: esFilters.FilterStateStore.APP_STATE }, })); diff --git a/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts b/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts index b78c43b9a74ac..601f892e3c56a 100644 --- a/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts +++ b/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts @@ -26,7 +26,7 @@ export function findIndexPatternById( if (!Array.isArray(indexPatterns) || !id) { return; } - return indexPatterns.find(o => o.id === id); + return indexPatterns.find((o) => o.id === id); } /** diff --git a/src/plugins/discover/public/get_inner_angular.ts b/src/plugins/discover/public/get_inner_angular.ts index d97bbef7aca25..a3e2efa785c81 100644 --- a/src/plugins/discover/public/get_inner_angular.ts +++ b/src/plugins/discover/public/get_inner_angular.ts @@ -126,7 +126,7 @@ export function initializeInnerAngularModule( 'discoverPromise', ]) .config(watchMultiDecorator) - .directive('icon', reactDirective => reactDirective(EuiIcon)) + .directive('icon', (reactDirective) => reactDirective(EuiIcon)) .directive('renderComplete', createRenderCompleteDirective) .service('debounce', ['$timeout', DebounceProviderTimeout]); } @@ -148,7 +148,7 @@ export function initializeInnerAngularModule( ]) .config(watchMultiDecorator) .run(registerListenEventListener) - .directive('icon', reactDirective => reactDirective(EuiIcon)) + .directive('icon', (reactDirective) => reactDirective(EuiIcon)) .directive('kbnAccessibleClick', KbnAccessibleClickProvider) .directive('collapsibleSidebar', CollapsibleSidebarProvider) .directive('fixedScroll', FixedScrollProvider) @@ -189,8 +189,8 @@ function createLocalStorageModule() { .service('sessionStorage', createLocalStorageService('sessionStorage')); } -const createLocalStorageService = function(type: string) { - return function($window: any) { +const createLocalStorageService = function (type: string) { + return function ($window: any) { return new Storage($window[type]); }; }; @@ -200,7 +200,7 @@ function createElasticSearchModule(data: DataPublicPluginStart) { .module('discoverEs', []) // Elasticsearch client used for requesting data. Connects to the /elasticsearch proxy // have to be written as function expression, because it's not compiled in dev mode - .service('es', function() { + .service('es', function () { return data.search.__LEGACY.esClient; }); } diff --git a/src/plugins/embeddable/public/components/panel_options_menu/index.tsx b/src/plugins/embeddable/public/components/panel_options_menu/index.tsx index e0796990e0c4e..7790646a88a68 100644 --- a/src/plugins/embeddable/public/components/panel_options_menu/index.tsx +++ b/src/plugins/embeddable/public/components/panel_options_menu/index.tsx @@ -45,7 +45,7 @@ export const PanelOptionsMenu: React.FC = ({ }, [close]); const handleContextMenuClick = () => { - setOpen(isOpen => !isOpen); + setOpen((isOpen) => !isOpen); }; const handlePopoverClose = () => { diff --git a/src/plugins/embeddable/public/lib/containers/container.ts b/src/plugins/embeddable/public/lib/containers/container.ts index ffbe75f66b581..8cf3d1a15883b 100644 --- a/src/plugins/embeddable/public/lib/containers/container.ts +++ b/src/plugins/embeddable/public/lib/containers/container.ts @@ -80,7 +80,7 @@ export abstract class Container< } public reload() { - Object.values(this.children).forEach(child => child.reload()); + Object.values(this.children).forEach((child) => child.reload()); } public async addNewEmbeddable< @@ -131,7 +131,7 @@ export abstract class Container< // to default back to inherited input. However, if the particular value is not part of the container, then // the caller may be trying to explicitly tell the child to clear out a given value, so in that case, we want // to pass it along. - keys.forEach(key => { + keys.forEach((key) => { if (explicitInput[key] === undefined && containerInput[key] !== undefined) { return; } @@ -149,7 +149,7 @@ export abstract class Container< public destroy() { super.destroy(); - Object.values(this.children).forEach(child => child.destroy()); + Object.values(this.children).forEach((child) => child.destroy()); this.subscription.unsubscribe(); } @@ -251,7 +251,7 @@ export abstract class Container< // Container input overrides defaults. const explicitInput: Partial = partial; - getKeys(defaults).forEach(key => { + getKeys(defaults).forEach((key) => { // @ts-ignore We know this key might not exist on inheritedInput. const inheritedValue = inheritedInput[key]; if (inheritedValue === undefined && explicitInput[key] === undefined) { @@ -330,7 +330,7 @@ export abstract class Container< private maybeUpdateChildren() { const allIds = Object.keys({ ...this.input.panels, ...this.output.embeddableLoaded }); - allIds.forEach(id => { + allIds.forEach((id) => { if (this.input.panels[id] !== undefined && this.output.embeddableLoaded[id] === undefined) { this.onPanelAdded(this.input.panels[id]); } else if ( diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx index a8ac5abe42a1d..340d851f3eedf 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx @@ -51,7 +51,7 @@ class OutputTestEmbeddable extends Embeddable { reload() {} } -test('Embeddable calls input subscribers when changed', async done => { +test('Embeddable calls input subscribers when changed', async (done) => { const hello = new ContactCardEmbeddable( { id: '123', firstName: 'Brienne', lastName: 'Tarth' }, { execAction: (() => null) as any } @@ -60,7 +60,7 @@ test('Embeddable calls input subscribers when changed', async done => { const subscription = hello .getInput$() .pipe(skip(1)) - .subscribe(input => { + .subscribe((input) => { expect(input.nameTitle).toEqual('Sir'); done(); subscription.unsubscribe(); diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx index 81052620fd08d..1ba9e12ec4d20 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx @@ -62,7 +62,7 @@ export class EmbeddableFactoryRenderer extends React.Component { return; } - factory.create(this.props.input).then(embeddable => { + factory.create(this.props.input).then((embeddable) => { this.embeddable = embeddable; this.setState({ loading: false }); }); diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx index 384297d8dee7d..ff9f466a8d553 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx @@ -64,7 +64,7 @@ setup.registerEmbeddableFactory(embeddableFactory.type, embeddableFactory); const start = doStart(); const getEmbeddableFactory = start.getEmbeddableFactory; -test('HelloWorldContainer initializes embeddables', async done => { +test('HelloWorldContainer initializes embeddables', async (done) => { const container = new HelloWorldContainer( { id: '123', diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx index 36ddfb49b0312..4fcf8b9f608f8 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx @@ -111,7 +111,7 @@ export class EmbeddablePanel extends React.Component { const { disabledActions } = this.props.embeddable.getInput(); if (disabledActions) { - badges = badges.filter(badge => disabledActions.indexOf(badge.id) === -1); + badges = badges.filter((badge) => disabledActions.indexOf(badge.id) === -1); } this.setState({ @@ -127,7 +127,7 @@ export class EmbeddablePanel extends React.Component { const { disabledActions } = this.props.embeddable.getInput(); if (disabledActions) { - notifications = notifications.filter(badge => disabledActions.indexOf(badge.id) === -1); + notifications = notifications.filter((badge) => disabledActions.indexOf(badge.id) === -1); } this.setState({ @@ -248,12 +248,12 @@ export class EmbeddablePanel extends React.Component { const createGetUserData = (overlays: OverlayStart) => async function getUserData(context: { embeddable: IEmbeddable }) { - return new Promise<{ title: string | undefined }>(resolve => { + return new Promise<{ title: string | undefined }>((resolve) => { const session = overlays.openModal( toMountPoint( { + updateTitle={(title) => { session.close(); resolve({ title }); }} diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx index 3894d6fbed382..34a176400dbb9 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx @@ -81,7 +81,7 @@ test('createNewEmbeddable() add embeddable to container', async () => { expect(Object.values(container.getInput().panels).length).toBe(0); component.instance().createNewEmbeddable(CONTACT_CARD_EMBEDDABLE); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const ids = Object.keys(container.getInput().panels); const embeddableId = ids[0]; @@ -123,7 +123,7 @@ test('selecting embeddable in "Create new ..." list calls createNewEmbeddable()' getFactory={getEmbeddableFactory} getAllFactories={start.getEmbeddableFactories} notifications={core.notifications} - SavedObjectFinder={props => } + SavedObjectFinder={(props) => } /> ) as ReactWrapper; diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx index 4c23916675e8f..d3e100366f2df 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx @@ -95,7 +95,8 @@ export class AddPanelFlyout extends React.Component { public onAddPanel = async (savedObjectId: string, savedObjectType: string, name: string) => { const factoryForSavedObjectType = [...this.props.getAllFactories()].find( - factory => factory.savedObjectMetaData && factory.savedObjectMetaData.type === savedObjectType + (factory) => + factory.savedObjectMetaData && factory.savedObjectMetaData.type === savedObjectType ); if (!factoryForSavedObjectType) { throw new EmbeddableFactoryNotFoundError(savedObjectType); @@ -111,8 +112,10 @@ export class AddPanelFlyout extends React.Component { private getCreateMenuItems(): ReactElement[] { return [...this.props.getAllFactories()] - .filter(factory => factory.isEditable() && !factory.isContainerType && factory.canCreateNew()) - .map(factory => ( + .filter( + (factory) => factory.isEditable() && !factory.isContainerType && factory.canCreateNew() + ) + .map((factory) => ( { const SavedObjectFinder = this.props.SavedObjectFinder; const metaData = [...this.props.getAllFactories()] .filter( - embeddableFactory => + (embeddableFactory) => Boolean(embeddableFactory.savedObjectMetaData) && !embeddableFactory.isContainerType ) .map(({ savedObjectMetaData }) => savedObjectMetaData as any); diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx index 6275dbd4eaa45..a4c80e1d86a80 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx @@ -41,11 +41,9 @@ describe('SavedObjectFinderCreateNew', () => { const onClick = jest.fn(); for (let i = 0; i < 3; i++) { items.push( - {`item${i + 1}`} + {`item${ + i + 1 + }`} ); } @@ -69,11 +67,9 @@ describe('SavedObjectFinderCreateNew', () => { const onClick = jest.fn(); for (let i = 0; i < 3; i++) { items.push( - {`item${i + 1}`} + {`item${ + i + 1 + }`} ); } diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts index 2f66d8eb0d619..6fddcbc84faf7 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts @@ -66,7 +66,7 @@ beforeEach(async () => { } }); -test('Updates the embeddable title when given', async done => { +test('Updates the embeddable title when given', async (done) => { const getUserData = () => Promise.resolve({ title: 'What is up?' }); const customizePanelAction = new CustomizePanelTitleAction(getUserData); expect(embeddable.getInput().title).toBeUndefined(); diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx index 663fa50420ccc..b590f20092939 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx @@ -64,7 +64,7 @@ export class CustomizePanelModal extends Component { }; private onHideTitleToggle = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ hideTitle: !prevState.hideTitle, })); }; @@ -118,7 +118,7 @@ export class CustomizePanelModal extends Component { disabled={this.state.hideTitle} placeholder={this.props.embeddable.getOutput().defaultTitle} value={this.state.title || ''} - onChange={e => this.updateTitle(e.target.value)} + onChange={(e) => this.updateTitle(e.target.value)} aria-label={i18n.translate( 'embeddableApi.customizePanel.modal.optionsMenuForm.panelTitleInputAriaLabel', { diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx index bb2eb52f9df72..8ba7be7880a7b 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx @@ -45,7 +45,7 @@ export interface PanelHeaderProps { } function renderBadges(badges: Array>, embeddable: IEmbeddable) { - return badges.map(badge => ( + return badges.map((badge) => ( >, embeddable: IEmbeddable ) { - return notifications.map(notification => { + return notifications.map((notification) => { const context = { embeddable }; let badge = ( diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx index 5548c9a0596b4..b4c349600e8f6 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx @@ -137,11 +137,11 @@ export class PanelOptionsMenu extends React.Component { + .then((actionContextMenuPanel) => { if (!this.mounted) return; this.setState({ actionContextMenuPanel }); }) - .catch(error => console.error(error)); // eslint-disable-line no-console + .catch((error) => console.error(error)); // eslint-disable-line no-console }; this.setState(({ isPopoverOpen }) => ({ isPopoverOpen: !isPopoverOpen }), after); }; diff --git a/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx b/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx index 7b396ce1bd10a..bb859d7b8d0c1 100644 --- a/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx @@ -58,7 +58,7 @@ export class GetMessageModal extends Component { this.setState({ message: e.target.value })} + onChange={(e) => this.setState({ message: e.target.value })} /> diff --git a/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx b/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx index 222fe1f6ed870..04898550532df 100644 --- a/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx @@ -57,7 +57,7 @@ export function createSendMessageAction(overlays: CoreStart['overlays']) { toMountPoint( modal.close()} - onDone={message => { + onDone={(message) => { modal.close(); sendMessage(context, message); }} diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx index 078e21df0f0ce..b82cd9ca7cc31 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx @@ -42,7 +42,7 @@ export interface ContactCardEmbeddableOptions { function getFullName(input: ContactCardEmbeddableInput) { const { nameTitle, firstName, lastName } = input; - const nameParts = [nameTitle, firstName, lastName].filter(name => name !== undefined); + const nameParts = [nameTitle, firstName, lastName].filter((name) => name !== undefined); return nameParts.join(' '); } diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx index f977329562b9b..893b6b04e50bc 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx @@ -50,7 +50,7 @@ export class ContactCardEmbeddableFactory } public getExplicitInput = (): Promise> => { - return new Promise(resolve => { + return new Promise((resolve) => { const modalSession = this.overlays.openModal( toMountPoint( this.setState({ firstName: e.target.value })} + onChange={(e) => this.setState({ firstName: e.target.value })} /> @@ -68,7 +68,7 @@ export class ContactCardInitializer extends Component this.setState({ lastName: e.target.value })} + onChange={(e) => this.setState({ lastName: e.target.value })} /> diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx index 49e9c34d95c95..6453046b86e20 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx @@ -52,7 +52,7 @@ export class HelloWorldContainerComponent extends Component { constructor(props: Props) { super(props); - Object.values(this.props.container.getInput().panels).forEach(panelState => { + Object.values(this.props.container.getInput().panels).forEach((panelState) => { this.roots[panelState.explicitInput.id] = React.createRef(); }); @@ -102,7 +102,7 @@ export class HelloWorldContainerComponent extends Component { } private renderList() { - const list = Object.values(this.state.panels).map(panelState => { + const list = Object.values(this.state.panels).map((panelState) => { const item = ( { const coreStart = coreMock.createStart(); const { setup, doStart } = testPlugin(coreSetup, coreStart); - const customProvider: EmbeddableFactoryProvider = def => ({ + const customProvider: EmbeddableFactoryProvider = (def) => ({ ...defaultEmbeddableFactoryProvider(def), getDisplayName: () => 'Intercepted!', }); @@ -66,7 +66,7 @@ test('custom embeddable factory provider test for intercepting embeddable creati const { setup, doStart } = testPlugin(coreSetup, coreStart); let updateCount = 0; - const customProvider: EmbeddableFactoryProvider = def => { + const customProvider: EmbeddableFactoryProvider = (def) => { return { ...defaultEmbeddableFactoryProvider(def), create: async (input, parent) => { @@ -105,6 +105,6 @@ test('custom embeddable factory provider test for intercepting embeddable creati expect(updateCount).toEqual(2); embeddable!.destroy(); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(updateCount).toEqual(0); }); diff --git a/src/plugins/embeddable/public/plugin.tsx b/src/plugins/embeddable/public/plugin.tsx index 36f49f2508e80..40a288545ef27 100644 --- a/src/plugins/embeddable/public/plugin.tsx +++ b/src/plugins/embeddable/public/plugin.tsx @@ -92,7 +92,7 @@ export class EmbeddablePublicPlugin implements Plugin { + this.embeddableFactoryDefinitions.forEach((def) => { this.embeddableFactories.set( def.type, this.customEmbeddableFactoryProvider @@ -166,7 +166,7 @@ export class EmbeddablePublicPlugin implements Plugin { - this.embeddableFactoryDefinitions.forEach(def => this.ensureFactoryExists(def.type)); + this.embeddableFactoryDefinitions.forEach((def) => this.ensureFactoryExists(def.type)); }; private ensureFactoryExists = (type: string) => { diff --git a/src/plugins/embeddable/public/tests/container.test.ts b/src/plugins/embeddable/public/tests/container.test.ts index d2769e208ba42..4cd01abaf7995 100644 --- a/src/plugins/embeddable/public/tests/container.test.ts +++ b/src/plugins/embeddable/public/tests/container.test.ts @@ -91,7 +91,7 @@ async function creatHelloWorldContainerAndEmbeddable( return { container, embeddable, coreSetup, coreStart, setup, start, uiActions }; } -test('Container initializes embeddables', async done => { +test('Container initializes embeddables', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -130,7 +130,7 @@ test('Container.addNewEmbeddable', async () => { expect(embeddableInContainer.id).toBe(embeddable.id); }); -test('Container.removeEmbeddable removes and cleans up', async done => { +test('Container.removeEmbeddable removes and cleans up', async (done) => { const { start, coreStart, uiActions } = await creatHelloWorldContainerAndEmbeddable(); const container = new HelloWorldContainer( { @@ -294,7 +294,7 @@ test('Container view mode change propagates to children', async () => { expect(embeddable.getInput().viewMode).toBe(ViewMode.EDIT); }); -test(`Container updates its state when a child's input is updated`, async done => { +test(`Container updates its state when a child's input is updated`, async (done) => { const { container, embeddable, @@ -381,7 +381,7 @@ test(`Derived container state passed to children`, async () => { subscription.unsubscribe(); }); -test(`Can subscribe to children embeddable updates`, async done => { +test(`Can subscribe to children embeddable updates`, async (done) => { const { embeddable } = await creatHelloWorldContainerAndEmbeddable( { id: 'hello container', @@ -404,7 +404,7 @@ test(`Can subscribe to children embeddable updates`, async done => { embeddable.updateInput({ nameTitle: 'Dr.' }); }); -test('Test nested reactions', async done => { +test('Test nested reactions', async (done) => { const { container, embeddable } = await creatHelloWorldContainerAndEmbeddable( { id: 'hello', panels: {}, viewMode: ViewMode.VIEW }, { @@ -472,7 +472,7 @@ test('Explicit embeddable input mapped to undefined will default to inherited', ]); }); -test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async done => { +test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: {} }); const embeddable = await container.addNewEmbeddable< @@ -523,7 +523,7 @@ test('Panel removed from input state', async () => { }; container.updateInput(newInput); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(container.getChild(embeddable.id)).toBeUndefined(); expect(container.getOutput().embeddableLoaded[embeddable.id]).toBeUndefined(); @@ -554,7 +554,7 @@ test('Panel added to input state', async () => { ); container2.updateInput(container.getInput()); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(container.getChild(embeddable.id)).toBeDefined(); expect(container.getOutput().embeddableLoaded[embeddable.id]).toBe(true); @@ -562,7 +562,7 @@ test('Panel added to input state', async () => { expect(container.getOutput().embeddableLoaded[embeddable2.id]).toBe(true); }); -test('Container changes made directly after adding a new embeddable are propagated', async done => { +test('Container changes made directly after adding a new embeddable are propagated', async (done) => { const coreSetup = coreMock.createSetup(); const coreStart = coreMock.createStart(); const { setup, doStart, uiActions } = testPlugin(coreSetup, coreStart); @@ -618,7 +618,7 @@ test('Container changes made directly after adding a new embeddable are propagat container.updateInput({ viewMode: ViewMode.VIEW }); }); -test('container stores ErrorEmbeddables when a factory for a child cannot be found (so the panel can be removed)', async done => { +test('container stores ErrorEmbeddables when a factory for a child cannot be found (so the panel can be removed)', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -639,7 +639,7 @@ test('container stores ErrorEmbeddables when a factory for a child cannot be fou }); }); -test('container stores ErrorEmbeddables when a saved object cannot be found', async done => { +test('container stores ErrorEmbeddables when a saved object cannot be found', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -660,7 +660,7 @@ test('container stores ErrorEmbeddables when a saved object cannot be found', as }); }); -test('ErrorEmbeddables get updated when parent does', async done => { +test('ErrorEmbeddables get updated when parent does', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -723,7 +723,7 @@ test('untilEmbeddableLoaded() throws an error if there is no such child panel in expect(error.message).toMatchInlineSnapshot(`"Panel not found"`); }); -test('untilEmbeddableLoaded() resolves if child is loaded in the container', async done => { +test('untilEmbeddableLoaded() resolves if child is loaded in the container', async (done) => { const { setup, doStart, coreStart, uiActions } = testPlugin( coreMock.createSetup(), coreMock.createStart() @@ -759,7 +759,7 @@ test('untilEmbeddableLoaded() resolves if child is loaded in the container', asy done(); }); -test('untilEmbeddableLoaded resolves with undefined if child is subsequently removed', async done => { +test('untilEmbeddableLoaded resolves with undefined if child is subsequently removed', async (done) => { const { doStart, setup, coreStart, uiActions } = testPlugin( coreMock.createSetup(), coreMock.createStart() @@ -793,7 +793,7 @@ test('untilEmbeddableLoaded resolves with undefined if child is subsequently rem } ); - container.untilEmbeddableLoaded('123').then(embed => { + container.untilEmbeddableLoaded('123').then((embed) => { expect(embed).toBeUndefined(); done(); }); @@ -801,7 +801,7 @@ test('untilEmbeddableLoaded resolves with undefined if child is subsequently rem container.updateInput({ panels: {} }); }); -test('adding a panel then subsequently removing it before its loaded removes the panel', async done => { +test('adding a panel then subsequently removing it before its loaded removes the panel', async (done) => { const { doStart, coreStart, uiActions, setup } = testPlugin( coreMock.createSetup(), coreMock.createStart() diff --git a/src/plugins/embeddable/public/tests/explicit_input.test.ts b/src/plugins/embeddable/public/tests/explicit_input.test.ts index ef3c4b6f17e7f..6bea4fe46a497 100644 --- a/src/plugins/embeddable/public/tests/explicit_input.test.ts +++ b/src/plugins/embeddable/public/tests/explicit_input.test.ts @@ -79,7 +79,7 @@ test('Explicit embeddable input mapped to undefined will default to inherited', ]); }); -test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async done => { +test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async (done) => { const container = new HelloWorldContainer( { id: 'hello', panels: {} }, { diff --git a/src/plugins/embeddable/public/tests/helpers.ts b/src/plugins/embeddable/public/tests/helpers.ts index de15ef61c2c60..8bdfbc60e1a41 100644 --- a/src/plugins/embeddable/public/tests/helpers.ts +++ b/src/plugins/embeddable/public/tests/helpers.ts @@ -22,7 +22,7 @@ export const expectErrorAsync = (fn: (...args: unknown[]) => Promise): .then(() => { throw new Error('Expected an error throw.'); }) - .catch(error => { + .catch((error) => { if (error.message === 'Expected an error throw.') { throw error; } diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx index 8f4b2b976d141..35d8cdaa67fc4 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx @@ -43,7 +43,7 @@ const toArray = (value: string | string[]): string[] => export const WithPrivileges = ({ privileges: requiredPrivileges, children }: Props) => { const { isLoading, privileges } = useAuthorizationContext(); - const privilegesToArray: Privilege[] = toArray(requiredPrivileges).map(p => { + const privilegesToArray: Privilege[] = toArray(requiredPrivileges).map((p) => { const [section, privilege] = p.split('.'); if (!privilege) { // Oh! we forgot to use the dot "." notation. @@ -54,7 +54,7 @@ export const WithPrivileges = ({ privileges: requiredPrivileges, children }: Pro const hasPrivileges = isLoading ? false - : privilegesToArray.every(privilege => { + : privilegesToArray.every((privilege) => { const [section, requiredPrivilege] = privilege; if (!privileges.missingPrivileges[section]) { // if the section does not exist in our missingPriviledges, everything is OK diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx index d2e13fe7622f9..d1bb6e0e25806 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx @@ -165,7 +165,7 @@ export const mountHook = ( const hookValueCallback = jest.fn(); let component!: ReactWrapper; - const act: ReactHookWrapper['act'] = actor => { + const act: ReactHookWrapper['act'] = (actor) => { reactAct(() => { actor(getLastHookValue(), (args: Args) => component.setProps(args)); component.update(); @@ -184,7 +184,7 @@ export const mountHook = ( hookValueCallback(body(props)); return null; }; - const TestComponent: React.FunctionComponent = args => + const TestComponent: React.FunctionComponent = (args) => WrapperComponent ? ( @@ -205,4 +205,4 @@ export const mountHook = ( }; }; -export const nextTick = () => new Promise(res => process.nextTick(res)); +export const nextTick = () => new Promise((res) => process.nextTick(res)); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/router_helpers.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/router_helpers.tsx index 4621315209b55..94ff4798d0226 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/router_helpers.tsx +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/router_helpers.tsx @@ -51,7 +51,7 @@ export const WithRoute = (componentRoutePath = '/', onRouter = (router: any) => return (props: any) => ( } + render={(routerProps) => } /> ); }; @@ -66,7 +66,7 @@ interface Router { export const reactRouterMock: Router = { history: { push: () => {}, - createHref: location => location.pathname!, + createHref: (location) => location.pathname!, location: { pathname: '', search: '', diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/utils.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/utils.ts index bfde6b1fdd089..90788c4f4e521 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/utils.ts +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/utils.ts @@ -22,7 +22,7 @@ import Chance from 'chance'; const chance = new Chance(); const CHARS_POOL = 'abcdefghijklmnopqrstuvwxyz'; -export const nextTick = (time = 0) => new Promise(resolve => setTimeout(resolve, time)); +export const nextTick = (time = 0) => new Promise((resolve) => setTimeout(resolve, time)); export const getRandomNumber = (range: { min: number; max: number } = { min: 1, max: 20 }) => chance.integer(range); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/testbed/testbed.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/testbed/testbed.ts index 3fe9466dcf568..1dba177ffc230 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/testbed/testbed.ts +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/testbed/testbed.ts @@ -88,7 +88,7 @@ export const registerTestBed = ( */ onRouter(reactRouterMock); - const setup: SetupFunc = props => { + const setup: SetupFunc = (props) => { // If a function is provided we execute it const storeToMount = typeof store === 'function' ? store() : store!; const mountConfig = { @@ -136,7 +136,7 @@ export const registerTestBed = ( const exists: TestBed['exists'] = (testSubject, count = 1) => find(testSubject).length === count; - const setProps: TestBed['setProps'] = updatedProps => { + const setProps: TestBed['setProps'] = (updatedProps) => { if (memoryRouter.wrapComponent !== false) { throw new Error( 'setProps() can only be called on a component **not** wrapped by a router route.' @@ -180,7 +180,7 @@ export const registerTestBed = ( ); } - return new Promise(resolve => setTimeout(resolve, WAIT_INTERVAL)).then(() => { + return new Promise((resolve) => setTimeout(resolve, WAIT_INTERVAL)).then(() => { component.update(); return process(); }); @@ -211,7 +211,7 @@ export const registerTestBed = ( if (!isAsync) { return; } - return new Promise(resolve => setTimeout(resolve)); + return new Promise((resolve) => setTimeout(resolve)); }; const selectCheckBox: TestBed['form']['selectCheckBox'] = ( @@ -225,7 +225,7 @@ export const registerTestBed = ( checkBox.simulate('change', { target: { checked: isChecked } }); }; - const toggleEuiSwitch: TestBed['form']['toggleEuiSwitch'] = testSubject => { + const toggleEuiSwitch: TestBed['form']['toggleEuiSwitch'] = (testSubject) => { const checkBox = find(testSubject); if (!checkBox.length) { throw new Error(`"${testSubject}" was not found.`); @@ -248,7 +248,7 @@ export const registerTestBed = ( const getErrorsMessages: TestBed['form']['getErrorsMessages'] = () => { const errorMessagesWrappers = component.find('.euiFormErrorText'); - return errorMessagesWrappers.map(err => err.text()); + return errorMessagesWrappers.map((err) => err.text()); }; /** @@ -262,7 +262,7 @@ export const registerTestBed = ( * * @param tableTestSubject The data test subject of the EUI table */ - const getMetaData: TestBed['table']['getMetaData'] = tableTestSubject => { + const getMetaData: TestBed['table']['getMetaData'] = (tableTestSubject) => { const table = find(tableTestSubject); if (!table.length) { @@ -272,9 +272,9 @@ export const registerTestBed = ( const rows = table .find('tr') .slice(1) // we remove the first row as it is the table header - .map(row => ({ + .map((row) => ({ reactWrapper: row, - columns: row.find('td').map(col => ({ + columns: row.find('td').map((col) => ({ reactWrapper: col, // We can't access the td value with col.text() because // eui adds an extra div in td on mobile => (.euiTableRowCell__mobileHeader) @@ -283,7 +283,7 @@ export const registerTestBed = ( })); // Also output the raw cell values, in the following format: [[td0, td1, td2], [td0, td1, td2]] - const tableCellsValues = rows.map(({ columns }) => columns.map(col => col.value)); + const tableCellsValues = rows.map(({ columns }) => columns.map((col) => col.value)); return { rows, tableCellsValues }; }; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js index 4ac6b0b8a256a..f038766766fe0 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js @@ -41,7 +41,7 @@ export const CronDaily = ({ minute, minuteOptions, hour, hourOptions, onChange } aria-label={i18n.translate('esUi.cronEditor.cronDaily.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronDaily.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -57,7 +57,7 @@ export const CronDaily = ({ minute, minuteOptions, hour, hourOptions, onChange } aria-label={i18n.translate('esUi.cronEditor.cronDaily.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyDailyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js index 576658882589f..18e9ffcb27c56 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js @@ -53,27 +53,27 @@ function makeSequence(min, max) { return values; } -const MINUTE_OPTIONS = makeSequence(0, 59).map(value => ({ +const MINUTE_OPTIONS = makeSequence(0, 59).map((value) => ({ value: value.toString(), text: padLeft(value, 2, '0'), })); -const HOUR_OPTIONS = makeSequence(0, 23).map(value => ({ +const HOUR_OPTIONS = makeSequence(0, 23).map((value) => ({ value: value.toString(), text: padLeft(value, 2, '0'), })); -const DAY_OPTIONS = makeSequence(1, 7).map(value => ({ +const DAY_OPTIONS = makeSequence(1, 7).map((value) => ({ value: value.toString(), text: getDayName(value - 1), })); -const DATE_OPTIONS = makeSequence(1, 31).map(value => ({ +const DATE_OPTIONS = makeSequence(1, 31).map((value) => ({ value: value.toString(), text: getOrdinalValue(value), })); -const MONTH_OPTIONS = makeSequence(1, 12).map(value => ({ +const MONTH_OPTIONS = makeSequence(1, 12).map((value) => ({ value: value.toString(), text: getMonthName(value - 1), })); @@ -208,7 +208,7 @@ export class CronEditor extends Component { }; } - onChangeFrequency = frequency => { + onChangeFrequency = (frequency) => { const { onChange, fieldToPreferredValueMap } = this.props; // Update fields which aren't editable with acceptable baseline values. @@ -232,7 +232,7 @@ export class CronEditor extends Component { }); }; - onChangeFields = fields => { + onChangeFields = (fields) => { const { onChange, frequency, fieldToPreferredValueMap } = this.props; const editableFields = Object.keys(frequencyToFieldsMap[frequency]); @@ -354,7 +354,7 @@ export class CronEditor extends Component { this.onChangeFrequency(e.target.value)} + onChange={(e) => this.onChangeFrequency(e.target.value)} fullWidth prepend={i18n.translate('esUi.cronEditor.textEveryLabel', { defaultMessage: 'Every', diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js index 194fccf110174..a04e83195b97f 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js @@ -36,7 +36,7 @@ export const CronHourly = ({ minute, minuteOptions, onChange }) => ( onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronHourly.fieldMinute.textAtLabel', { defaultMessage: 'At', diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js index f3ffc082a4c60..28057bd7d9293 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js @@ -44,7 +44,7 @@ export const CronMonthly = ({ onChange({ date: e.target.value })} + onChange={(e) => onChange({ date: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronMonthly.textOnTheLabel', { defaultMessage: 'On the', @@ -68,7 +68,7 @@ export const CronMonthly = ({ aria-label={i18n.translate('esUi.cronEditor.cronMonthly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronMonthly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -84,7 +84,7 @@ export const CronMonthly = ({ aria-label={i18n.translate('esUi.cronEditor.cronMonthly.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyMonthlyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js index b328b5cb958b4..c06eecbb381b3 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js @@ -44,7 +44,7 @@ export const CronWeekly = ({ onChange({ day: e.target.value })} + onChange={(e) => onChange({ day: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronWeekly.textOnLabel', { defaultMessage: 'On', @@ -68,7 +68,7 @@ export const CronWeekly = ({ aria-label={i18n.translate('esUi.cronEditor.cronWeekly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronWeekly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -81,7 +81,7 @@ export const CronWeekly = ({ onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} aria-label={i18n.translate('esUi.cronEditor.cronWeekly.minuteSelectLabel', { defaultMessage: 'Minute', })} diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js index 26a57756273bd..c3b9691750937 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js @@ -46,7 +46,7 @@ export const CronYearly = ({ onChange({ month: e.target.value })} + onChange={(e) => onChange({ month: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldMonth.textInLabel', { defaultMessage: 'In', @@ -65,7 +65,7 @@ export const CronYearly = ({ onChange({ date: e.target.value })} + onChange={(e) => onChange({ date: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldDate.textOnTheLabel', { defaultMessage: 'On the', @@ -89,7 +89,7 @@ export const CronYearly = ({ aria-label={i18n.translate('esUi.cronEditor.cronYearly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -105,7 +105,7 @@ export const CronYearly = ({ aria-label={i18n.translate('esUi.cronEditor.cronYearly.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyYearlyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts index 398cf531612ef..41f6a65a5b410 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts @@ -21,7 +21,7 @@ import ace from 'brace'; const { TextHighlightRules } = ace.acequire('ace/mode/text_highlight_rules'); const oop = ace.acequire('ace/lib/oop'); -export const ElasticsearchSqlHighlightRules = function(this: any) { +export const ElasticsearchSqlHighlightRules = function (this: any) { // See https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-commands.html const keywords = 'describe|between|in|like|not|and|or|desc|select|from|where|having|group|by|order' + diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts index 3663b92d92a6f..951cf5fa279b5 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts @@ -27,7 +27,7 @@ import { ScriptHighlightRules } from './script_highlight_rules'; const { JsonHighlightRules } = ace.acequire('ace/mode/json_highlight_rules'); const oop = ace.acequire('ace/lib/oop'); -const jsonRules = function(root: any) { +const jsonRules = function (root: any) { root = root ? root : 'json'; const rules: any = {}; const xJsonRules = [ diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts index 9fbfedba1d23f..8d4ebcfad9496 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts @@ -43,16 +43,16 @@ const XJsonMode: any = function XJsonMode(this: any) { oop.inherits(XJsonMode, JSONMode); // Then clobber `createWorker` method to install our worker source. Per ace's wiki: https://github.com/ajaxorg/ace/wiki/Syntax-validation -(XJsonMode.prototype as any).createWorker = function(session: ace.IEditSession) { +(XJsonMode.prototype as any).createWorker = function (session: ace.IEditSession) { const xJsonWorker = new WorkerClient(['ace'], workerModule, 'JsonWorker'); xJsonWorker.attachToDocument(session.getDocument()); - xJsonWorker.on('annotate', function(e: { data: any }) { + xJsonWorker.on('annotate', function (e: { data: any }) { session.setAnnotations(e.data); }); - xJsonWorker.on('terminate', function() { + xJsonWorker.on('terminate', function () { session.clearAnnotations(); }); diff --git a/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts b/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts index 92c14ade791cd..419e80ad1608f 100644 --- a/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts +++ b/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts @@ -36,7 +36,7 @@ describe('JSON to XJSON conversion tools', () => { }); }); -_.each(collapsingTests.split(/^=+$/m), function(fixture) { +_.each(collapsingTests.split(/^=+$/m), function (fixture) { if (fixture.trim() === '') { return; } @@ -45,12 +45,12 @@ _.each(collapsingTests.split(/^=+$/m), function(fixture) { const expanded = fixture[1].trim(); const collapsed = fixture[2].trim(); - test('Literal collapse - ' + name, function() { + test('Literal collapse - ' + name, function () { expect(utils.collapseLiteralStrings(expanded)).toEqual(collapsed); }); }); -_.each(expandingTests.split(/^=+$/m), function(fixture) { +_.each(expandingTests.split(/^=+$/m), function (fixture) { if (fixture.trim() === '') { return; } @@ -59,7 +59,7 @@ _.each(expandingTests.split(/^=+$/m), function(fixture) { const collapsed = fixture[1].trim(); const expanded = fixture[2].trim(); - test('Literal expand - ' + name, function() { + test('Literal expand - ' + name, function () { expect(utils.expandLiteralStrings(collapsed)).toEqual(expanded); }); }); diff --git a/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts b/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts index cf81a2abebabf..a6792543cd726 100644 --- a/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts +++ b/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts @@ -39,7 +39,7 @@ describe('Index name validation', () => { }); it('should not allow illegal characters', () => { - INDEX_ILLEGAL_CHARACTERS_VISIBLE.forEach(char => { + INDEX_ILLEGAL_CHARACTERS_VISIBLE.forEach((char) => { const illegalCharacters = findIllegalCharactersInIndexName(`name${char}`); expect(illegalCharacters).toEqual([char]); }); diff --git a/src/plugins/es_ui_shared/public/request/request.test.js b/src/plugins/es_ui_shared/public/request/request.test.js index cc554b531d88a..190c32517eefe 100644 --- a/src/plugins/es_ui_shared/public/request/request.test.js +++ b/src/plugins/es_ui_shared/public/request/request.test.js @@ -31,11 +31,11 @@ const TestHook = ({ callback }) => { let element; -const testHook = callback => { +const testHook = (callback) => { element = mount(); }; -const wait = async wait => new Promise(resolve => setTimeout(resolve, wait || 1)); +const wait = async (wait) => new Promise((resolve) => setTimeout(resolve, wait || 1)); // FLAKY: // - https://github.com/elastic/kibana/issues/42561 diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx index a10da62fa6906..9fb804eb7fafa 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx @@ -70,7 +70,7 @@ export const ComboBoxField = ({ field, euiFieldProps = {}, ...rest }: Props) => }; const onComboChange = (options: EuiComboBoxOptionOption[]) => { - field.setValue(options.map(option => option.label)); + field.setValue(options.map((option) => option.label)); }; const onSearchComboChange = (value: string) => { @@ -95,7 +95,7 @@ export const ComboBoxField = ({ field, euiFieldProps = {}, ...rest }: Props) => placeholder={i18n.translate('esUi.forms.comboBoxField.placeHolderText', { defaultMessage: 'Type and then hit "ENTER"', })} - selectedOptions={(field.value as any[]).map(v => ({ label: v }))} + selectedOptions={(field.value as any[]).map((v) => ({ label: v }))} onCreateOption={onCreateComboOption} onChange={onComboChange} onSearchChange={onSearchComboChange} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx index 9cd5cb3d0f2b9..fd57e098cf806 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx @@ -34,7 +34,7 @@ export const JsonEditorField = ({ field, ...rest }: Props) => { const { label, helpText, value, setValue } = field; const onJsonUpdate: OnJsonEditorUpdateHandler = useCallback( - updatedJson => { + (updatedJson) => { setValue(updatedJson.data.raw); }, [setValue] diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx index e77337e4ecf53..a33c8009802ee 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx @@ -45,7 +45,7 @@ export const MultiSelectField = ({ field, euiFieldProps = {}, ...rest }: Props) { + onChange={(options) => { field.setValue(options); }} options={field.value as any[]} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx index 6e6aeb4de18fe..c22394435be83 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx @@ -50,7 +50,7 @@ export const SelectField = ({ field, euiFieldProps, ...rest }: Props) => { { + onChange={(e) => { field.setValue(e.target.value); }} options={[]} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx index 14a468613ec56..46e2d663eb324 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx @@ -48,7 +48,7 @@ export const SuperSelectField = ({ field, euiFieldProps = { options: [] }, ...re { + onChange={(value) => { field.setValue(value); }} isInvalid={isInvalid} diff --git a/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts b/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts index 274aa82b31834..a3ee2b8b84189 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts @@ -25,13 +25,13 @@ export const multiSelectComponent: Record = { // This deSerializer takes the previously selected options and map them // against the default select options values. selectedValueToOptions(selectOptions) { - return defaultFormValue => { + return (defaultFormValue) => { // If there are no default form value, it means that no previous value has been selected. if (!defaultFormValue) { return selectOptions; } - return (selectOptions as EuiSelectableOption[]).map(option => ({ + return (selectOptions as EuiSelectableOption[]).map((option) => ({ ...option, checked: (defaultFormValue as string[]).includes(option.label) ? 'on' : undefined, })); diff --git a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts index bae6b4c2652ca..98287f6bac35d 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts @@ -46,7 +46,7 @@ export const multiSelectComponent: Record> = { * @param value The Eui Selectable options array */ optionsToSelectedValue(options: EuiSelectableOption[]): string[] { - return options.filter(option => option.checked === 'on').map(option => option.label); + return options.filter((option) => option.checked === 'on').map((option) => option.label); }, }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx index 8b11b619ea8e0..3e4ce4a412b3b 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx @@ -38,7 +38,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} @@ -106,7 +106,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} @@ -145,7 +145,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts index ddf2212490476..4c4a7f0642022 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts @@ -42,7 +42,7 @@ export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) = ? (pathsToWatch as string[]) : ([pathsToWatch] as string[]); - if (valuesToWatchArray.some(value => previousRawData.current[value] !== raw[value])) { + if (valuesToWatchArray.some((value) => previousRawData.current[value] !== raw[value])) { previousRawData.current = raw; setFormData(raw); } diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts index 3f71f83c55694..1605c09f575f6 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts @@ -93,15 +93,15 @@ export const UseArray = ({ ); const addItem = () => { - setItems(previousItems => { + setItems((previousItems) => { const itemIndex = previousItems.length; return [...previousItems, getNewItemAtIndex(itemIndex)]; }); }; const removeItem = (id: number) => { - setItems(previousItems => { - const updatedItems = previousItems.filter(item => item.id !== id); + setItems((previousItems) => { + const updatedItems = previousItems.filter((item) => item.id !== id); return updatePaths(updatedItems); }); }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx index 136f3e7ad5688..589879f37900e 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx @@ -107,7 +107,7 @@ export const UseField = React.memo(UseFieldComp) as typeof UseFieldComp; * @param partialProps Partial props to apply to all instances */ export function getUseField(partialProps: Partial>) { - return function(props: Partial>) { + return function (props: Partial>) { const componentProps = { ...partialProps, ...props } as Props; return {...componentProps} />; }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx index a81af924eb3bd..d69527e36249b 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx @@ -41,7 +41,7 @@ export const UseMultiFields = ({ fields, children }: Props) => { const { id } = fieldsArray[index]; return ( - {field => { + {(field) => { hookFields[id] = field; return index === fieldsArray.length - 1 ? children(hookFields) : renderField(index + 1); }} diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx index 5dcd076b41533..a7b8713a23a74 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx @@ -32,7 +32,7 @@ export const FormProvider = ({ children, form }: Props) => ( {children} ); -export const useFormContext = function() { +export const useFormContext = function () { const context = useContext(FormContext) as FormHook; if (context === undefined) { throw new Error('useFormContext must be used within a '); diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts index 3814bbe62e120..9800af2398927 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts @@ -79,8 +79,8 @@ export const useField = ( ? (validationTypeToFilterOut as string[]) : ([validationTypeToFilterOut] as string[]); - return _errors.filter(error => - validationTypeToArray.every(_type => error.validationType !== _type) + return _errors.filter((error) => + validationTypeToArray.every((_type) => error.validationType !== _type) ); }; @@ -275,7 +275,7 @@ export const useField = ( // -- API // ---------------------------------- const clearErrors: FieldHook['clearErrors'] = (validationType = VALIDATION_TYPES.FIELD) => { - setErrors(previousErrors => filterErrors(previousErrors, validationType)); + setErrors((previousErrors) => filterErrors(previousErrors, validationType)); }; /** @@ -331,7 +331,7 @@ export const useField = ( * * @param newValue The new value to assign to the field */ - const setValue: FieldHook['setValue'] = newValue => { + const setValue: FieldHook['setValue'] = (newValue) => { if (isPristine) { setPristine(false); } @@ -340,8 +340,8 @@ export const useField = ( setStateValue(formattedValue); }; - const _setErrors: FieldHook['setErrors'] = _errors => { - setErrors(_errors.map(error => ({ validationType: VALIDATION_TYPES.FIELD, ...error }))); + const _setErrors: FieldHook['setErrors'] = (_errors) => { + setErrors(_errors.map((error) => ({ validationType: VALIDATION_TYPES.FIELD, ...error }))); }; /** @@ -349,7 +349,7 @@ export const useField = ( * * @param event Form input change event */ - const onChange: FieldHook['onChange'] = event => { + const onChange: FieldHook['onChange'] = (event) => { const newValue = {}.hasOwnProperty.call(event!.target, 'checked') ? event.target.checked : event.target.value; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts index f539f306db700..f9286d99cbf80 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts @@ -73,7 +73,7 @@ export function useForm( useEffect(() => { return () => { - formUpdateSubscribers.current.forEach(subscription => subscription.unsubscribe()); + formUpdateSubscribers.current.forEach((subscription) => subscription.unsubscribe()); formUpdateSubscribers.current = []; isUnmounted.current = true; }; @@ -116,7 +116,7 @@ export function useForm( ) => { if (getDataOptions.unflatten) { const nonEmptyFields = stripEmptyFields(fieldsRefs.current); - const fieldsValue = mapFormFields(nonEmptyFields, field => field.__serializeOutput()); + const fieldsValue = mapFormFields(nonEmptyFields, (field) => field.__serializeOutput()); return serializer(unflattenObject(fieldsValue)) as T; } @@ -147,7 +147,7 @@ export function useForm( const updateFormValidity = () => { const fieldsArray = fieldsToArray(); - const areAllFieldsValidated = fieldsArray.every(field => field.isValidated); + const areAllFieldsValidated = fieldsArray.every((field) => field.isValidated); if (!areAllFieldsValidated) { // If *not* all the fiels have been validated, the validity of the form is unknown, thus still "undefined" @@ -160,10 +160,10 @@ export function useForm( return isFormValid; }; - const validateFields: FormHook['__validateFields'] = async fieldNames => { + const validateFields: FormHook['__validateFields'] = async (fieldNames) => { const fieldsToValidate = fieldNames - .map(name => fieldsRefs.current[name]) - .filter(field => field !== undefined); + .map((name) => fieldsRefs.current[name]) + .filter((field) => field !== undefined); if (fieldsToValidate.length === 0) { // Nothing to validate @@ -171,7 +171,7 @@ export function useForm( } const formData = getFormData({ unflatten: false }); - await Promise.all(fieldsToValidate.map(field => field.validate({ formData }))); + await Promise.all(fieldsToValidate.map((field) => field.validate({ formData }))); const isFormValid = updateFormValidity(); const areFieldsValid = fieldsToValidate.every(isFieldValid); @@ -181,7 +181,7 @@ export function useForm( const validateAllFields = async (): Promise => { const fieldsArray = fieldsToArray(); - const fieldsToValidate = fieldsArray.filter(field => !field.isValidated); + const fieldsToValidate = fieldsArray.filter((field) => !field.isValidated); let isFormValid: boolean | undefined = isValid; @@ -197,12 +197,12 @@ export function useForm( return isFormValid; } - ({ isFormValid } = await validateFields(fieldsToValidate.map(field => field.path))); + ({ isFormValid } = await validateFields(fieldsToValidate.map((field) => field.path))); return isFormValid!; }; - const addField: FormHook['__addField'] = field => { + const addField: FormHook['__addField'] = (field) => { fieldsRefs.current[field.path] = field; if (!{}.hasOwnProperty.call(getFormData$().value, field.path)) { @@ -211,11 +211,11 @@ export function useForm( } }; - const removeField: FormHook['__removeField'] = _fieldNames => { + const removeField: FormHook['__removeField'] = (_fieldNames) => { const fieldNames = Array.isArray(_fieldNames) ? _fieldNames : [_fieldNames]; const currentFormData = { ...getFormData$().value } as FormData; - fieldNames.forEach(name => { + fieldNames.forEach((name) => { delete fieldsRefs.current[name]; delete currentFormData[name]; }); @@ -245,16 +245,16 @@ export function useForm( const getFields: FormHook['getFields'] = () => fieldsRefs.current; - const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = fieldName => + const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = (fieldName) => get(defaultValueDeserialized, fieldName); - const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = fieldName => { + const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = (fieldName) => { const config = (get(schema ? schema : {}, fieldName) as FieldConfig) || {}; return config; }; - const submitForm: FormHook['submit'] = async e => { + const submitForm: FormHook['submit'] = async (e) => { if (e) { e.preventDefault(); } @@ -278,8 +278,8 @@ export function useForm( return { data: formData, isValid: isFormValid! }; }; - const subscribe: FormHook['subscribe'] = handler => { - const subscription = getFormData$().subscribe(raw => { + const subscribe: FormHook['subscribe'] = (handler) => { + const subscription = getFormData$().subscribe((raw) => { if (!isUnmounted.current) { handler({ isValid, data: { raw, format: getFormData }, validate: validateAllFields }); } @@ -290,7 +290,7 @@ export function useForm( return { unsubscribe() { formUpdateSubscribers.current = formUpdateSubscribers.current.filter( - sub => sub !== subscription + (sub) => sub !== subscription ); return subscription.unsubscribe(); }, diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts index c805a9ca40e63..8f516c9c8a46f 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts @@ -49,7 +49,7 @@ export class Subject { next(value: T) { if (value !== this.value) { this.value = value; - this.callbacks.forEach(fn => fn(value)); + this.callbacks.forEach((fn) => fn(value)); } } } diff --git a/src/plugins/expressions/common/execution/container.ts b/src/plugins/expressions/common/execution/container.ts index d6271869134d1..6302c0adb550b 100644 --- a/src/plugins/expressions/common/execution/container.ts +++ b/src/plugins/expressions/common/execution/container.ts @@ -66,16 +66,16 @@ export interface ExecutionPureTransitions { } export const executionPureTransitions: ExecutionPureTransitions = { - start: state => () => ({ + start: (state) => () => ({ ...state, state: 'pending', }), - setResult: state => result => ({ + setResult: (state) => (result) => ({ ...state, state: 'result', result, }), - setError: state => error => ({ + setError: (state) => (error) => ({ ...state, state: 'error', error, diff --git a/src/plugins/expressions/common/execution/execution.test.ts b/src/plugins/expressions/common/execution/execution.test.ts index 4776204a8ab2f..6a2f4bb269ff3 100644 --- a/src/plugins/expressions/common/execution/execution.test.ts +++ b/src/plugins/expressions/common/execution/execution.test.ts @@ -264,9 +264,9 @@ describe('Execution', () => { expect(execution.state.get().result).toBe(undefined); execution.start(null); expect(execution.state.get().result).toBe(undefined); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(execution.state.get().result).toBe(undefined); - await new Promise(r => setTimeout(r, 11)); + await new Promise((r) => setTimeout(r, 11)); expect(execution.state.get().result).toBe(null); }); }); diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index 6ee12d97a6422..7bfb14b8bfa1c 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -193,16 +193,16 @@ export class Execution< const { resolve, reject } = this.firstResultFuture; const chainPromise = this.invokeChain(this.state.get().ast.chain, input); - this.race(chainPromise).then(resolve, error => { + this.race(chainPromise).then(resolve, (error) => { if (this.abortController.signal.aborted) resolve(createAbortErrorValue()); else reject(error); }); this.firstResultFuture.promise.then( - result => { + (result) => { this.state.transitions.setResult(result); }, - error => { + (error) => { this.state.transitions.setError(error); } ); @@ -396,7 +396,7 @@ export class Execution< // Actually resolve unless the argument definition says not to const resolvedArgValues = await Promise.all( - argNames.map(argName => { + argNames.map((argName) => { const interpretFns = resolveArgFns[argName]; if (!argDefs[argName].resolve) return interpretFns; return Promise.all(interpretFns.map((fn: any) => fn())); diff --git a/src/plugins/expressions/common/executor/container.ts b/src/plugins/expressions/common/executor/container.ts index c9c1ab34e7ac3..fea58ec6294de 100644 --- a/src/plugins/expressions/common/executor/container.ts +++ b/src/plugins/expressions/common/executor/container.ts @@ -43,9 +43,9 @@ export interface ExecutorPureTransitions { } export const pureTransitions: ExecutorPureTransitions = { - addFunction: state => fn => ({ ...state, functions: { ...state.functions, [fn.name]: fn } }), - addType: state => type => ({ ...state, types: { ...state.types, [type.name]: type } }), - extendContext: state => extraContext => ({ + addFunction: (state) => (fn) => ({ ...state, functions: { ...state.functions, [fn.name]: fn } }), + addType: (state) => (type) => ({ ...state, types: { ...state.types, [type.name]: type } }), + extendContext: (state) => (extraContext) => ({ ...state, context: { ...state.context, ...extraContext }, }), @@ -58,8 +58,8 @@ export interface ExecutorPureSelectors { } export const pureSelectors: ExecutorPureSelectors = { - getFunction: state => id => state.functions[id] || null, - getType: state => id => state.types[id] || null, + getFunction: (state) => (id) => state.functions[id] || null, + getType: (state) => (id) => state.types[id] || null, getContext: ({ context }) => () => context, }; diff --git a/src/plugins/expressions/common/executor/executor.test.ts b/src/plugins/expressions/common/executor/executor.test.ts index 4e43cedd18157..81845401d32e4 100644 --- a/src/plugins/expressions/common/executor/executor.test.ts +++ b/src/plugins/expressions/common/executor/executor.test.ts @@ -51,7 +51,7 @@ describe('Executor', () => { for (const type of expressionTypes.typeSpecs) executor.registerType(type); const types = executor.getTypes(); expect(Object.keys(types).sort()).toEqual( - expressionTypes.typeSpecs.map(spec => spec.name).sort() + expressionTypes.typeSpecs.map((spec) => spec.name).sort() ); }); }); @@ -81,7 +81,7 @@ describe('Executor', () => { executor.registerFunction(functionDefinition); const functions = executor.getFunctions(); expect(Object.keys(functions).sort()).toEqual( - expressionFunctions.functionSpecs.map(spec => spec.name).sort() + expressionFunctions.functionSpecs.map((spec) => spec.name).sort() ); }); }); diff --git a/src/plugins/expressions/common/expression_functions/specs/font.ts b/src/plugins/expressions/common/expression_functions/specs/font.ts index 3e305998a0157..c8016bfacc710 100644 --- a/src/plugins/expressions/common/expression_functions/specs/font.ts +++ b/src/plugins/expressions/common/expression_functions/specs/font.ts @@ -26,14 +26,14 @@ const dashify = (str: string) => { return str .trim() .replace(/([a-z])([A-Z])/g, '$1-$2') - .replace(/\W/g, m => (/[À-ž]/.test(m) ? m : '-')) + .replace(/\W/g, (m) => (/[À-ž]/.test(m) ? m : '-')) .replace(/^-+|-+$/g, '') .toLowerCase(); }; const inlineStyle = (obj: Record) => { if (!obj) return ''; - const styles = Object.keys(obj).map(key => { + const styles = Object.keys(obj).map((key) => { const prop = dashify(key); const line = prop.concat(':').concat(String(obj[key])); return line; @@ -123,7 +123,7 @@ export const font: ExpressionFunctionDefinition<'font', null, Arguments, Style> values: { list: Object.values(FontWeight) .slice(0, -1) - .map(weight => `\`"${weight}"\``) + .map((weight) => `\`"${weight}"\``) .join(', '), end: `\`"${Object.values(FontWeight).slice(-1)[0]}"\``, }, diff --git a/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts b/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts index bc721a772d50f..016208aefdfc6 100644 --- a/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts +++ b/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts @@ -26,7 +26,7 @@ import { ExecutionContext } from '../../../execution/types'; * overriding with any provided args. */ export const functionWrapper = (spec: AnyExpressionFunctionDefinition) => { - const defaultArgs = mapValues(spec.args, argSpec => argSpec.default); + const defaultArgs = mapValues(spec.args, (argSpec) => argSpec.default); return ( context: object | null, args: Record = {}, diff --git a/src/plugins/expressions/common/expression_types/expression_type.test.ts b/src/plugins/expressions/common/expression_types/expression_type.test.ts index a692ec9501cc5..b94d9a305121f 100644 --- a/src/plugins/expressions/common/expression_types/expression_type.test.ts +++ b/src/plugins/expressions/common/expression_types/expression_type.test.ts @@ -25,8 +25,8 @@ export const boolean: ExpressionTypeDefinition<'boolean', boolean> = { name: 'boolean', from: { null: () => false, - number: n => Boolean(n), - string: s => Boolean(s), + number: (n) => Boolean(n), + string: (s) => Boolean(s), }, to: { render: (value): ExpressionValueRender<{ text: string }> => { diff --git a/src/plugins/expressions/common/expression_types/specs/boolean.ts b/src/plugins/expressions/common/expression_types/specs/boolean.ts index fee4608418406..d730f95d7c423 100644 --- a/src/plugins/expressions/common/expression_types/specs/boolean.ts +++ b/src/plugins/expressions/common/expression_types/specs/boolean.ts @@ -27,8 +27,8 @@ export const boolean: ExpressionTypeDefinition<'boolean', boolean> = { name, from: { null: () => false, - number: n => Boolean(n), - string: s => Boolean(s), + number: (n) => Boolean(n), + string: (s) => Boolean(s), }, to: { render: (value): ExpressionValueRender<{ text: string }> => { diff --git a/src/plugins/expressions/common/expression_types/specs/datatable.ts b/src/plugins/expressions/common/expression_types/specs/datatable.ts index 92254a3d02438..c113765f8e7e7 100644 --- a/src/plugins/expressions/common/expression_types/specs/datatable.ts +++ b/src/plugins/expressions/common/expression_types/specs/datatable.ts @@ -72,7 +72,7 @@ interface RenderedDatatable { export const datatable: ExpressionTypeDefinition = { name, - validate: table => { + validate: (table) => { // TODO: Check columns types. Only string, boolean, number, date, allowed for now. if (!table.columns) { throw new Error('datatable must have a columns array, even if it is empty'); @@ -82,20 +82,20 @@ export const datatable: ExpressionTypeDefinition { + serialize: (table) => { const { columns, rows } = table; return { ...table, - rows: rows.map(row => { - return columns.map(column => row[column.name]); + rows: rows.map((row) => { + return columns.map((column) => row[column.name]); }), }; }, - deserialize: table => { + deserialize: (table) => { const { columns, rows } = table; return { ...table, - rows: rows.map(row => { + rows: rows.map((row) => { return zipObject(map(columns, 'name'), row); }), }; @@ -127,8 +127,8 @@ export const datatable: ExpressionTypeDefinition { const validFields = ['x', 'y', 'color', 'size', 'text']; - const columns = table.columns.filter(column => validFields.includes(column.name)); - const rows = table.rows.map(row => pick(row, validFields)); + const columns = table.columns.filter((column) => validFields.includes(column.name)); + const rows = table.rows.map((row) => pick(row, validFields)); return { type: 'pointseries', columns: columns.reduce>((acc, column) => { diff --git a/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts b/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts index 7742594d751de..7f2f3c37c587c 100644 --- a/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts +++ b/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts @@ -53,7 +53,7 @@ export const kibanaDatatable = { return { type: name, rows: context.rows, - columns: context.columns.map(column => { + columns: context.columns.map((column) => { return { id: column.name, name: column.name, diff --git a/src/plugins/expressions/common/expression_types/specs/num.ts b/src/plugins/expressions/common/expression_types/specs/num.ts index 99b3bc3419173..191e617fdc858 100644 --- a/src/plugins/expressions/common/expression_types/specs/num.ts +++ b/src/plugins/expressions/common/expression_types/specs/num.ts @@ -36,11 +36,11 @@ export const num: ExpressionTypeDefinition<'num', ExpressionValueNum> = { type: 'num', value: 0, }), - boolean: b => ({ + boolean: (b) => ({ type: 'num', value: Number(b), }), - string: n => { + string: (n) => { const value = Number(n); if (Number.isNaN(value)) { throw new Error( @@ -57,7 +57,7 @@ export const num: ExpressionTypeDefinition<'num', ExpressionValueNum> = { value, }; }, - '*': value => ({ + '*': (value) => ({ type: 'num', value: Number(value), }), diff --git a/src/plugins/expressions/common/expression_types/specs/number.ts b/src/plugins/expressions/common/expression_types/specs/number.ts index f346ae837adb4..10986659c7848 100644 --- a/src/plugins/expressions/common/expression_types/specs/number.ts +++ b/src/plugins/expressions/common/expression_types/specs/number.ts @@ -28,8 +28,8 @@ export const number: ExpressionTypeDefinition = { name, from: { null: () => 0, - boolean: b => Number(b), - string: n => { + boolean: (b) => Number(b), + string: (n) => { const value = Number(n); if (Number.isNaN(value)) { throw new Error( diff --git a/src/plugins/expressions/common/expression_types/specs/shape.ts b/src/plugins/expressions/common/expression_types/specs/shape.ts index 315838043cb49..80ac67c84c3c0 100644 --- a/src/plugins/expressions/common/expression_types/specs/shape.ts +++ b/src/plugins/expressions/common/expression_types/specs/shape.ts @@ -25,7 +25,7 @@ const name = 'shape'; export const shape: ExpressionTypeDefinition> = { name: 'shape', to: { - render: input => { + render: (input) => { return { type: 'render', as: name, diff --git a/src/plugins/expressions/common/expression_types/specs/string.ts b/src/plugins/expressions/common/expression_types/specs/string.ts index d46f0e5f6b7c2..46f460891c2fb 100644 --- a/src/plugins/expressions/common/expression_types/specs/string.ts +++ b/src/plugins/expressions/common/expression_types/specs/string.ts @@ -27,8 +27,8 @@ export const string: ExpressionTypeDefinition = { name, from: { null: () => '', - boolean: b => String(b), - number: n => String(n), + boolean: (b) => String(b), + number: (n) => String(n), }, to: { render: (text: T): ExpressionValueRender<{ text: T }> => { diff --git a/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts b/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts index e9ff6e0698560..f269c0ea19934 100644 --- a/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts +++ b/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts @@ -30,7 +30,7 @@ export const sleep: ExpressionFunctionDefinition<'sleep', any, { time: number }, }, help: '', fn: async (input, args, context) => { - await new Promise(r => setTimeout(r, args.time)); + await new Promise((r) => setTimeout(r, args.time)); return input; }, }; diff --git a/src/plugins/expressions/common/util/get_by_alias.ts b/src/plugins/expressions/common/util/get_by_alias.ts index 6868abb5da923..35a98871afabc 100644 --- a/src/plugins/expressions/common/util/get_by_alias.ts +++ b/src/plugins/expressions/common/util/get_by_alias.ts @@ -30,7 +30,7 @@ export function getByAlias( return Object.values(node).find(({ name, aliases }) => { if (!name) return false; if (name.toLowerCase() === lowerCaseName) return true; - return (aliases || []).some(alias => { + return (aliases || []).some((alias) => { return alias.toLowerCase() === lowerCaseName; }); }); diff --git a/src/plugins/expressions/public/loader.ts b/src/plugins/expressions/public/loader.ts index 418ff6fdf8614..9428d7db1d9d0 100644 --- a/src/plugins/expressions/public/loader.ts +++ b/src/plugins/expressions/public/loader.ts @@ -56,7 +56,7 @@ export class ExpressionLoader { // as loading$ could emit straight away in the constructor // and we want to notify subscribers about it, but all subscriptions will happen later this.loading$ = this.loadingSubject.asObservable().pipe( - filter(_ => _ === true), + filter((_) => _ === true), map(() => void 0) ); @@ -67,14 +67,14 @@ export class ExpressionLoader { this.update$ = this.renderHandler.update$; this.events$ = this.renderHandler.events$; - this.update$.subscribe(value => { + this.update$.subscribe((value) => { if (value) { const { newExpression, newParams } = value; this.update(newExpression, newParams); } }); - this.data$.subscribe(data => { + this.data$.subscribe((data) => { this.render(data); }); diff --git a/src/plugins/expressions/public/mocks.tsx b/src/plugins/expressions/public/mocks.tsx index b8f2f693e9c77..3a5ece271c4ee 100644 --- a/src/plugins/expressions/public/mocks.tsx +++ b/src/plugins/expressions/public/mocks.tsx @@ -75,7 +75,7 @@ const createStartContract = (): Start => { getType: jest.fn(), getTypes: jest.fn(), loader: jest.fn(), - ReactExpressionRenderer: jest.fn(props => <>), + ReactExpressionRenderer: jest.fn((props) => <>), render: jest.fn(), run: jest.fn(), }; diff --git a/src/plugins/expressions/public/plugin.ts b/src/plugins/expressions/public/plugin.ts index 720c3b701d504..ec60fbdf44c3a 100644 --- a/src/plugins/expressions/public/plugin.ts +++ b/src/plugins/expressions/public/plugin.ts @@ -145,7 +145,7 @@ export class ExpressionsPublicPlugin // For every sever-side function, register a client-side // function that matches its definition, but which simply // calls the server-side function endpoint. - Object.keys(serverFunctionList).forEach(functionName => { + Object.keys(serverFunctionList).forEach((functionName) => { if (expressionsSetup.getFunction(functionName)) { return; } diff --git a/src/plugins/expressions/public/react_expression_renderer.test.tsx b/src/plugins/expressions/public/react_expression_renderer.test.tsx index caa9bc68dffb8..702f88d785756 100644 --- a/src/plugins/expressions/public/react_expression_renderer.test.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.test.tsx @@ -111,7 +111,7 @@ describe('ExpressionRenderer', () => { const instance = mount(
{message}
} + renderError={(message) =>
{message}
} /> ); diff --git a/src/plugins/expressions/public/react_expression_renderer.tsx b/src/plugins/expressions/public/react_expression_renderer.tsx index 9e237d36ef627..a83c63443906b 100644 --- a/src/plugins/expressions/public/react_expression_renderer.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.tsx @@ -104,7 +104,7 @@ export const ReactExpressionRenderer = ({ }); if (onEvent) { subs.push( - expressionLoaderRef.current.events$.subscribe(event => { + expressionLoaderRef.current.events$.subscribe((event) => { onEvent(event); }) ); @@ -112,11 +112,11 @@ export const ReactExpressionRenderer = ({ subs.push( expressionLoaderRef.current.loading$.subscribe(() => { hasHandledErrorRef.current = false; - setState(prevState => ({ ...prevState, isLoading: true })); + setState((prevState) => ({ ...prevState, isLoading: true })); }), expressionLoaderRef.current.render$ .pipe(filter(() => !hasHandledErrorRef.current)) - .subscribe(item => { + .subscribe((item) => { setState(() => ({ ...defaultState, isEmpty: false, @@ -125,7 +125,7 @@ export const ReactExpressionRenderer = ({ ); return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); if (expressionLoaderRef.current) { expressionLoaderRef.current.destroy(); expressionLoaderRef.current = null; diff --git a/src/plugins/expressions/public/render.test.ts b/src/plugins/expressions/public/render.test.ts index b9601f6d1e920..4e79d0d03ace1 100644 --- a/src/plugins/expressions/public/render.test.ts +++ b/src/plugins/expressions/public/render.test.ts @@ -128,8 +128,8 @@ describe('ExpressionRenderHandler', () => { it('sends a next observable once rendering is complete', () => { const expressionRenderHandler = new ExpressionRenderHandler(element); expect.assertions(1); - return new Promise(resolve => { - expressionRenderHandler.render$.subscribe(renderCount => { + return new Promise((resolve) => { + expressionRenderHandler.render$.subscribe((renderCount) => { expect(renderCount).toBe(1); resolve(); }); diff --git a/src/plugins/expressions/public/render.ts b/src/plugins/expressions/public/render.ts index c8a4022a01131..0d88b3d27f658 100644 --- a/src/plugins/expressions/public/render.ts +++ b/src/plugins/expressions/public/render.ts @@ -68,7 +68,7 @@ export class ExpressionRenderHandler { this.onRenderError = onRenderError || defaultRenderErrorHandler; this.renderSubject = new Rx.BehaviorSubject(null as any | null); - this.render$ = this.renderSubject.asObservable().pipe(filter(_ => _ !== null)) as Observable< + this.render$ = this.renderSubject.asObservable().pipe(filter((_) => _ !== null)) as Observable< any >; @@ -86,10 +86,10 @@ export class ExpressionRenderHandler { reload: () => { this.updateSubject.next(null); }, - update: params => { + update: (params) => { this.updateSubject.next(params); }, - event: data => { + event: (data) => { this.eventsSubject.next(data); }, }; diff --git a/src/plugins/expressions/server/legacy.ts b/src/plugins/expressions/server/legacy.ts index 1487f9f6734e9..4dd9419e59e2d 100644 --- a/src/plugins/expressions/server/legacy.ts +++ b/src/plugins/expressions/server/legacy.ts @@ -114,7 +114,7 @@ export const createLegacyServerEndpoints = ( * Register an endpoint that executes a batch of functions, and streams the * results back using ND-JSON. */ - plugins.bfetch.addBatchProcessingRoute(`/api/interpreter/fns`, request => { + plugins.bfetch.addBatchProcessingRoute(`/api/interpreter/fns`, (request) => { return { onBatchItem: async (fnCall: any) => { const [coreStart] = await core.getStartServices(); diff --git a/src/plugins/home/public/application/components/feature_directory.js b/src/plugins/home/public/application/components/feature_directory.js index 7f685d9d7d804..e9ab348f164c7 100644 --- a/src/plugins/home/public/application/components/feature_directory.js +++ b/src/plugins/home/public/application/components/feature_directory.js @@ -40,7 +40,7 @@ import { createAppNavigationHandler } from './app_navigation_handler'; const ALL_TAB_ID = 'all'; const OTHERS_TAB_ID = 'others'; -const isOtherCategory = directory => { +const isOtherCategory = (directory) => { return ( directory.category !== FeatureCatalogueCategory.DATA && directory.category !== FeatureCatalogueCategory.ADMIN @@ -81,7 +81,7 @@ export class FeatureDirectory extends React.Component { }; } - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -102,7 +102,7 @@ export class FeatureDirectory extends React.Component { renderDirectories = () => { return this.props.directories - .filter(directory => { + .filter((directory) => { if (this.state.selectedTabId === ALL_TAB_ID) { return true; } @@ -111,7 +111,7 @@ export class FeatureDirectory extends React.Component { } return this.state.selectedTabId === directory.category; }) - .map(directory => { + .map((directory) => { return ( { + renderDirectories = (category) => { const { addBasePath, directories } = this.props; return directories - .filter(directory => { + .filter((directory) => { return directory.showOnHomePage && directory.category === category; }) - .map(directory => { + .map((directory) => { return ( { decrement: sinon.mock(), }, localStorage: { - getItem: sinon.spy(path => { + getItem: sinon.spy((path) => { expect(path).toEqual('home:welcome:show'); return 'false'; }), @@ -77,11 +77,11 @@ describe('home', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); return component; } diff --git a/src/plugins/home/public/application/components/home_app.js b/src/plugins/home/public/application/components/home_app.js index bbbb75cd664f7..648915b6dae0c 100644 --- a/src/plugins/home/public/application/components/home_app.js +++ b/src/plugins/home/public/application/components/home_app.js @@ -51,7 +51,7 @@ export function HomeApp({ directories }) { const mlEnabled = environment.ml; const apmUiEnabled = environment.apmUi; - const renderTutorialDirectory = props => { + const renderTutorialDirectory = (props) => { return ( { + const renderTutorial = (props) => { return ( { +const createRecentlyAccessed = (length) => { const recentlyAccessed = []; let i = 0; while (recentlyAccessed.length < length) { diff --git a/src/plugins/home/public/application/components/sample_data_set_cards.js b/src/plugins/home/public/application/components/sample_data_set_cards.js index 404c82676c1c3..255fc57054083 100644 --- a/src/plugins/home/public/application/components/sample_data_set_cards.js +++ b/src/plugins/home/public/application/components/sample_data_set_cards.js @@ -82,12 +82,12 @@ export class SampleDataSetCards extends React.Component { }); }; - install = async id => { - const targetSampleDataSet = this.state.sampleDataSets.find(sampleDataSet => { + install = async (id) => { + const targetSampleDataSet = this.state.sampleDataSets.find((sampleDataSet) => { return sampleDataSet.id === id; }); - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: true }, })); @@ -95,7 +95,7 @@ export class SampleDataSetCards extends React.Component { await installSampleDataSet(id, targetSampleDataSet.defaultIndex); } catch (fetchError) { if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, })); } @@ -110,9 +110,9 @@ export class SampleDataSetCards extends React.Component { } if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, - sampleDataSets: prevState.sampleDataSets.map(sampleDataSet => { + sampleDataSets: prevState.sampleDataSets.map((sampleDataSet) => { if (sampleDataSet.id === id) { sampleDataSet.status = INSTALLED_STATUS; } @@ -130,12 +130,12 @@ export class SampleDataSetCards extends React.Component { }); }; - uninstall = async id => { - const targetSampleDataSet = this.state.sampleDataSets.find(sampleDataSet => { + uninstall = async (id) => { + const targetSampleDataSet = this.state.sampleDataSets.find((sampleDataSet) => { return sampleDataSet.id === id; }); - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: true }, })); @@ -143,7 +143,7 @@ export class SampleDataSetCards extends React.Component { await uninstallSampleDataSet(id, targetSampleDataSet.defaultIndex); } catch (fetchError) { if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, })); } @@ -158,9 +158,9 @@ export class SampleDataSetCards extends React.Component { } if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, - sampleDataSets: prevState.sampleDataSets.map(sampleDataSet => { + sampleDataSets: prevState.sampleDataSets.map((sampleDataSet) => { if (sampleDataSet.id === id) { sampleDataSet.status = UNINSTALLED_STATUS; } @@ -178,7 +178,7 @@ export class SampleDataSetCards extends React.Component { }); }; - lightOrDarkImage = sampleDataSet => { + lightOrDarkImage = (sampleDataSet) => { return getServices().uiSettings.get('theme:darkMode') && sampleDataSet.darkPreviewImagePath ? sampleDataSet.darkPreviewImagePath : sampleDataSet.previewImagePath; @@ -187,7 +187,7 @@ export class SampleDataSetCards extends React.Component { render() { return ( - {this.state.sampleDataSets.map(sampleDataSet => { + {this.state.sampleDataSets.map((sampleDataSet) => { return ( { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/home/public/application/components/sample_data_view_data_button.test.js b/src/plugins/home/public/application/components/sample_data_view_data_button.test.js index f594ec1264c94..933a58c29ecb4 100644 --- a/src/plugins/home/public/application/components/sample_data_view_data_button.test.js +++ b/src/plugins/home/public/application/components/sample_data_view_data_button.test.js @@ -24,7 +24,7 @@ import { SampleDataViewDataButton } from './sample_data_view_data_button'; jest.mock('../kibana_services', () => ({ getServices: () => ({ - addBasePath: path => `root${path}`, + addBasePath: (path) => `root${path}`, }), })); diff --git a/src/plugins/home/public/application/components/tutorial/instruction.js b/src/plugins/home/public/application/components/tutorial/instruction.js index a44fb26bffbbb..e4b4e34a95662 100644 --- a/src/plugins/home/public/application/components/tutorial/instruction.js +++ b/src/plugins/home/public/application/components/tutorial/instruction.js @@ -52,13 +52,13 @@ export function Instruction({ commands, paramValues, textPost, textPre, replaceT let commandBlock; if (commands) { const cmdText = commands - .map(cmd => { + .map((cmd) => { return replaceTemplateStrings(cmd, paramValues); }) .join('\n'); copyButton = ( - {copy => ( + {(copy) => ( { + this.tabs = props.instructionVariants.map((variant) => { return { id: variant.id, name: getDisplayText(variant.id), @@ -60,10 +60,10 @@ class InstructionSetUi extends React.Component { } handleToggleVisibility = () => { - this.setState(prevState => ({ isParamFormVisible: !prevState.isParamFormVisible })); + this.setState((prevState) => ({ isParamFormVisible: !prevState.isParamFormVisible })); }; - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -182,7 +182,7 @@ class InstructionSetUi extends React.Component { } renderInstructions = () => { - const instructionVariant = this.props.instructionVariants.find(variant => { + const instructionVariant = this.props.instructionVariants.find((variant) => { return variant.id === this.state.selectedTabId; }); if (!instructionVariant) { diff --git a/src/plugins/home/public/application/components/tutorial/number_parameter.js b/src/plugins/home/public/application/components/tutorial/number_parameter.js index b3962385b332a..68475f9082bbf 100644 --- a/src/plugins/home/public/application/components/tutorial/number_parameter.js +++ b/src/plugins/home/public/application/components/tutorial/number_parameter.js @@ -21,7 +21,7 @@ import React from 'react'; import PropTypes from 'prop-types'; export function NumberParameter({ id, label, value, setParameter }) { - const handleChange = evt => { + const handleChange = (evt) => { setParameter(id, parseFloat(evt.target.value)); }; diff --git a/src/plugins/home/public/application/components/tutorial/parameter_form.js b/src/plugins/home/public/application/components/tutorial/parameter_form.js index 35db68abee427..99159ae12b16f 100644 --- a/src/plugins/home/public/application/components/tutorial/parameter_form.js +++ b/src/plugins/home/public/application/components/tutorial/parameter_form.js @@ -25,7 +25,7 @@ import { EuiPanel } from '@elastic/eui'; export class ParameterForm extends React.Component { renderInputs = () => { - return this.props.params.map(param => { + return this.props.params.map((param) => { switch (param.type) { case 'number': return ( diff --git a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js index bf69c419f6464..790c6d9c2574e 100644 --- a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js +++ b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js @@ -90,11 +90,11 @@ class SavedObjectsInstallerUi extends React.Component { return; } - const errors = resp.savedObjects.filter(savedObject => { + const errors = resp.savedObjects.filter((savedObject) => { return Boolean(savedObject.error); }); - const overwriteErrors = errors.filter(savedObject => { + const overwriteErrors = errors.filter((savedObject) => { return savedObject.error.statusCode === 409; }); if (overwriteErrors.length > 0) { diff --git a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js index b3f42436c48c2..6cc02184fbc16 100644 --- a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js +++ b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js @@ -52,7 +52,7 @@ describe('bulkCreate', () => { findTestSubject(component, 'loadSavedObjects').simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -73,7 +73,7 @@ describe('bulkCreate', () => { findTestSubject(component, 'loadSavedObjects').simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/home/public/application/components/tutorial/string_parameter.js b/src/plugins/home/public/application/components/tutorial/string_parameter.js index 0973737136cff..a99e39c298ecf 100644 --- a/src/plugins/home/public/application/components/tutorial/string_parameter.js +++ b/src/plugins/home/public/application/components/tutorial/string_parameter.js @@ -21,7 +21,7 @@ import React from 'react'; import PropTypes from 'prop-types'; export function StringParameter({ id, label, value, setParameter }) { - const handleChange = evt => { + const handleChange = (evt) => { setParameter(id, evt.target.value); }; diff --git a/src/plugins/home/public/application/components/tutorial/tutorial.js b/src/plugins/home/public/application/components/tutorial/tutorial.js index 762d7fde252a1..576f732278b8e 100644 --- a/src/plugins/home/public/application/components/tutorial/tutorial.js +++ b/src/plugins/home/public/application/components/tutorial/tutorial.js @@ -147,7 +147,7 @@ class TutorialUi extends React.Component { const paramValues = {}; if (instructions.params) { - instructions.params.forEach(param => { + instructions.params.forEach((param) => { paramValues[param.id] = param.defaultValue; }); } @@ -162,7 +162,7 @@ class TutorialUi extends React.Component { }); }; - setVisibleInstructions = instructionsType => { + setVisibleInstructions = (instructionsType) => { this.setState( { visibleInstructions: instructionsType, @@ -172,21 +172,21 @@ class TutorialUi extends React.Component { }; setParameter = (paramId, newValue) => { - this.setState(previousState => { + this.setState((previousState) => { const paramValues = _.cloneDeep(previousState.paramValues); paramValues[paramId] = newValue; return { paramValues: paramValues }; }); }; - checkInstructionSetStatus = async instructionSetIndex => { + checkInstructionSetStatus = async (instructionSetIndex) => { const instructionSet = this.getInstructionSets()[instructionSetIndex]; const esHitsCheckConfig = _.get(instructionSet, `statusCheck.esHitsCheck`); if (esHitsCheckConfig) { const statusCheckState = await this.fetchEsHitsStatus(esHitsCheckConfig); - this.setState(prevState => ({ + this.setState((prevState) => ({ statusCheckStates: { ...prevState.statusCheckStates, [instructionSetIndex]: statusCheckState, @@ -200,7 +200,7 @@ class TutorialUi extends React.Component { * @param esHitsCheckConfig * @return {Promise} */ - fetchEsHitsStatus = async esHitsCheckConfig => { + fetchEsHitsStatus = async (esHitsCheckConfig) => { const searchHeader = JSON.stringify({ index: esHitsCheckConfig.index }); const searchBody = JSON.stringify({ query: esHitsCheckConfig.query, size: 1 }); const response = await fetch(this.props.addBasePath('/elasticsearch/_msearch'), { @@ -260,9 +260,9 @@ class TutorialUi extends React.Component { } }; - onStatusCheck = instructionSetIndex => { + onStatusCheck = (instructionSetIndex) => { this.setState( - prevState => ({ + (prevState) => ({ statusCheckStates: { ...prevState.statusCheckStates, [instructionSetIndex]: StatusCheckStates.FETCHING, @@ -272,7 +272,7 @@ class TutorialUi extends React.Component { ); }; - renderInstructionSets = instructions => { + renderInstructionSets = (instructions) => { let offset = 1; return instructions.instructionSets.map((instructionSet, index) => { const currentOffset = offset; @@ -320,7 +320,7 @@ class TutorialUi extends React.Component { label = this.state.tutorial.artifacts.application.label; url = this.props.addBasePath(this.state.tutorial.artifacts.application.path); } else if (_.has(this.state, 'tutorial.artifacts.dashboards')) { - const overviewDashboard = this.state.tutorial.artifacts.dashboards.find(dashboard => { + const overviewDashboard = this.state.tutorial.artifacts.dashboards.find((dashboard) => { return dashboard.isOverview; }); if (overviewDashboard) { diff --git a/src/plugins/home/public/application/components/tutorial/tutorial.test.js b/src/plugins/home/public/application/components/tutorial/tutorial.test.js index 41d83d7562f6e..23b0dc50018c1 100644 --- a/src/plugins/home/public/application/components/tutorial/tutorial.test.js +++ b/src/plugins/home/public/application/components/tutorial/tutorial.test.js @@ -67,10 +67,10 @@ const loadTutorialPromise = Promise.resolve(tutorial); const getTutorial = () => { return loadTutorialPromise; }; -const addBasePath = path => { +const addBasePath = (path) => { return `BASE_PATH/${path}`; }; -const replaceTemplateStrings = text => { +const replaceTemplateStrings = (text) => { return text; }; @@ -130,11 +130,7 @@ describe('isCloudEnabled is false', () => { ); await loadTutorialPromise; component.update(); - component - .find('button#onPremElasticCloud') - .closest('div') - .find('input') - .simulate('change'); + component.find('button#onPremElasticCloud').closest('div').find('input').simulate('change'); component.update(); expect(component.state('visibleInstructions')).toBe('onPremElasticCloud'); }); diff --git a/src/plugins/home/public/application/components/tutorial_directory.js b/src/plugins/home/public/application/components/tutorial_directory.js index 18007931a194a..4d2cec158f63e 100644 --- a/src/plugins/home/public/application/components/tutorial_directory.js +++ b/src/plugins/home/public/application/components/tutorial_directory.js @@ -93,7 +93,7 @@ class TutorialDirectoryUi extends React.Component { let openTab = ALL_TAB_ID; if ( props.openTab && - this.tabs.some(tab => { + this.tabs.some((tab) => { return tab.id === props.openTab; }) ) { @@ -126,7 +126,7 @@ class TutorialDirectoryUi extends React.Component { return; } - let tutorialCards = tutorialConfigs.map(tutorialConfig => { + let tutorialCards = tutorialConfigs.map((tutorialConfig) => { // add base path to SVG based icons let icon = tutorialConfig.euiIconType; if (icon && icon.includes('/')) { @@ -161,7 +161,7 @@ class TutorialDirectoryUi extends React.Component { }); if (this.props.isCloudEnabled) { - tutorialCards = tutorialCards.filter(tutorial => { + tutorialCards = tutorialCards.filter((tutorial) => { return _.has(tutorial, 'elasticCloud'); }); } @@ -176,7 +176,7 @@ class TutorialDirectoryUi extends React.Component { }); } - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -202,13 +202,13 @@ class TutorialDirectoryUi extends React.Component { return ( {this.state.tutorialCards - .filter(tutorial => { + .filter((tutorial) => { return ( this.state.selectedTabId === ALL_TAB_ID || this.state.selectedTabId === tutorial.category ); }) - .map(tutorial => { + .map((tutorial) => { return ( { + const tutorial = tutorials.find((tutorial) => { return tutorial.id === id; }); diff --git a/src/plugins/home/public/plugin.ts b/src/plugins/home/public/plugin.ts index f5ad5e321d274..d05fce652bd40 100644 --- a/src/plugins/home/public/plugin.ts +++ b/src/plugins/home/public/plugin.ts @@ -128,7 +128,7 @@ export class HomePublicPlugin window.location.hash === '' ) { // ...wait for the app to mount initially and then... - currentAppId$.pipe(first()).subscribe(appId => { + currentAppId$.pipe(first()).subscribe((appId) => { if (appId === 'home') { // ...navigate to default app set by `kibana.defaultAppId`. // This doesn't do anything as along as the default settings are kept. diff --git a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts index 187a75b376d64..c70fc0464b131 100644 --- a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts +++ b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts @@ -73,7 +73,7 @@ export class FeatureCatalogueRegistry { } const capabilities = this.capabilities; return [...this.features.values()] - .filter(entry => capabilities.catalogue[entry.id] !== false) + .filter((entry) => capabilities.catalogue[entry.id] !== false) .sort(compareByKey('title')); } } diff --git a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts index b0cc2e2db3cc9..c4fb636cc9f8f 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts @@ -31,7 +31,7 @@ const ecommerceDescription = i18n.translate('home.sampleData.ecommerceSpecDescri }); const initialAppLinks = [] as AppLinkSchema[]; -export const ecommerceSpecProvider = function(): SampleDatasetSchema { +export const ecommerceSpecProvider = function (): SampleDatasetSchema { return { id: 'ecommerce', name: ecommerceName, diff --git a/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts b/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts index fc3cb6094b5ea..0d5b4a8816a03 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts @@ -31,7 +31,7 @@ const flightsDescription = i18n.translate('home.sampleData.flightsSpecDescriptio }); const initialAppLinks = [] as AppLinkSchema[]; -export const flightsSpecProvider = function(): SampleDatasetSchema { +export const flightsSpecProvider = function (): SampleDatasetSchema { return { id: 'flights', name: flightsName, diff --git a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts index d8f205dff24e8..900b9ab82f47f 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts @@ -31,7 +31,7 @@ const logsDescription = i18n.translate('home.sampleData.logsSpecDescription', { }); const initialAppLinks = [] as AppLinkSchema[]; -export const logsSpecProvider = function(): SampleDatasetSchema { +export const logsSpecProvider = function (): SampleDatasetSchema { return { id: 'logs', name: logsName, diff --git a/src/plugins/home/server/services/sample_data/lib/create_index_name.ts b/src/plugins/home/server/services/sample_data/lib/create_index_name.ts index 9aecef405d7ce..e8901a3f1bd3e 100644 --- a/src/plugins/home/server/services/sample_data/lib/create_index_name.ts +++ b/src/plugins/home/server/services/sample_data/lib/create_index_name.ts @@ -17,7 +17,7 @@ * under the License. */ -export const createIndexName = function(sampleDataSetId: string, dataIndexId: string): string { +export const createIndexName = function (sampleDataSetId: string, dataIndexId: string): string { // Sample data schema was updated to support multiple indices in 6.5. // This if statement ensures that sample data sets that used a single index prior to the schema change // have the same index name to avoid orphaned indices when uninstalling. diff --git a/src/plugins/home/server/services/sample_data/lib/load_data.ts b/src/plugins/home/server/services/sample_data/lib/load_data.ts index 481ed8da93dba..4dc55b9685302 100644 --- a/src/plugins/home/server/services/sample_data/lib/load_data.ts +++ b/src/plugins/home/server/services/sample_data/lib/load_data.ts @@ -52,7 +52,7 @@ export function loadData(path: any, bulkInsert: (docs: any[]) => Promise) reject(err); }; - lineStream.on('line', async line => { + lineStream.on('line', async (line) => { if (line.length === 0 || line.charAt(0) === '#') { return; } diff --git a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts index e905cb0637b7b..b8077a255ecf6 100644 --- a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts +++ b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts @@ -31,9 +31,7 @@ const dataIndexSchema = Joi.object({ fields: Joi.object().required(), // times fields that will be updated relative to now when data is installed - timeFields: Joi.array() - .items(Joi.string()) - .required(), + timeFields: Joi.array().items(Joi.string()).required(), // Reference to now in your test data set. // When data is installed, timestamps are converted to the present time. @@ -41,9 +39,7 @@ const dataIndexSchema = Joi.object({ // For example: // sample data set: timestamp: 2018-01-01T00:00:00Z, currentTimeMarker: 2018-01-01T12:00:00Z // installed data set: timestamp: 2018-04-18T20:33:14Z, currentTimeMarker: 2018-04-19T08:33:14Z - currentTimeMarker: Joi.string() - .isoDate() - .required(), + currentTimeMarker: Joi.string().isoDate().required(), // Set to true to move timestamp to current week, preserving day of week and time of day // Relative distance from timestamp to currentTimeMarker will not remain the same @@ -67,19 +63,13 @@ export const sampleDataSchema = { // saved object id of main dashboard for sample data set overviewDashboard: Joi.string().required(), - appLinks: Joi.array() - .items(appLinkSchema) - .default([]), + appLinks: Joi.array().items(appLinkSchema).default([]), // saved object id of default index-pattern for sample data set defaultIndex: Joi.string().required(), // Kibana saved objects (index patter, visualizations, dashboard, ...) // Should provide a nice demo of Kibana's functionality with the sample data set - savedObjects: Joi.array() - .items(Joi.object()) - .required(), - dataIndices: Joi.array() - .items(dataIndexSchema) - .required(), + savedObjects: Joi.array().items(Joi.object()).required(), + dataIndices: Joi.array().items(dataIndexSchema).required(), }; diff --git a/src/plugins/home/server/services/sample_data/routes/install.ts b/src/plugins/home/server/services/sample_data/routes/install.ts index e2c5ce6883230..940162b10385b 100644 --- a/src/plugins/home/server/services/sample_data/routes/install.ts +++ b/src/plugins/home/server/services/sample_data/routes/install.ts @@ -162,7 +162,7 @@ export function createInstallRoute( logger.warn(errMsg); return res.internalError({ body: errMsg }); } - const errors = createResults.saved_objects.filter(savedObjectCreateResult => { + const errors = createResults.saved_objects.filter((savedObjectCreateResult) => { return Boolean(savedObjectCreateResult.error); }); if (errors.length > 0) { diff --git a/src/plugins/home/server/services/sample_data/routes/list.ts b/src/plugins/home/server/services/sample_data/routes/list.ts index 37ebab1c168d2..4fb67c6c78840 100644 --- a/src/plugins/home/server/services/sample_data/routes/list.ts +++ b/src/plugins/home/server/services/sample_data/routes/list.ts @@ -27,7 +27,7 @@ const UNKNOWN = 'unknown'; export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSchema[]) => { router.get({ path: '/api/sample_data', validate: false }, async (context, req, res) => { - const registeredSampleDatasets = sampleDatasets.map(sampleDataset => { + const registeredSampleDatasets = sampleDatasets.map((sampleDataset) => { return { id: sampleDataset.id, name: sampleDataset.name, @@ -42,7 +42,7 @@ export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSc statusMsg: sampleDataset.statusMsg, }; }); - const isInstalledPromises = registeredSampleDatasets.map(async sampleDataset => { + const isInstalledPromises = registeredSampleDatasets.map(async (sampleDataset) => { for (let i = 0; i < sampleDataset.dataIndices.length; i++) { const dataIndexConfig = sampleDataset.dataIndices[i]; const index = createIndexName(sampleDataset.id, dataIndexConfig.id); diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.ts index b6d04c5c0b6a3..356c886436413 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.ts @@ -97,7 +97,7 @@ export class SampleDataRegistry { getSampleDatasets: () => this.sampleDatasets, addSavedObjectsToSampleDataset: (id: string, savedObjects: SavedObject[]) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === id; }); @@ -109,7 +109,7 @@ export class SampleDataRegistry { }, addAppLinksToSampleDataset: (id: string, appLinks: AppLinkSchema[]) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === id; }); @@ -130,14 +130,14 @@ export class SampleDataRegistry { embeddableType, embeddableConfig, }: SampleDatasetDashboardPanel) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === sampleDataId; }); if (!sampleDataset) { throw new Error(`Unable to find sample dataset with id: ${sampleDataId}`); } - const dashboard = sampleDataset.savedObjects.find(savedObject => { + const dashboard = sampleDataset.savedObjects.find((savedObject) => { return savedObject.id === dashboardId && savedObject.type === 'dashboard'; }) as SavedObject<{ panelsJSON: string }>; if (!dashboard) { diff --git a/src/plugins/home/server/services/sample_data/usage/usage.ts b/src/plugins/home/server/services/sample_data/usage/usage.ts index 59599a1bee68f..ba67906febf1a 100644 --- a/src/plugins/home/server/services/sample_data/usage/usage.ts +++ b/src/plugins/home/server/services/sample_data/usage/usage.ts @@ -37,7 +37,7 @@ export function usage( logger.warn(`saved objects repository incrementCounter encountered an error: ${err}`); }; - const internalRepositoryPromise = savedObjects.then(so => so.createInternalRepository()); + const internalRepositoryPromise = savedObjects.then((so) => so.createInternalRepository()); return { addInstall: async (dataSet: string) => { diff --git a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts index eb001ac96cceb..24f5a39feb4c5 100644 --- a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts +++ b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts @@ -47,9 +47,7 @@ const artifactsSchema = Joi.object({ documentationUrl: Joi.string().required(), }), // Kibana dashboards created by this product. - dashboards: Joi.array() - .items(dashboardSchema) - .required(), + dashboards: Joi.array().items(dashboardSchema).required(), application: Joi.object({ path: Joi.string().required(), label: Joi.string().required(), @@ -63,9 +61,7 @@ const statusCheckSchema = Joi.object({ success: Joi.string(), error: Joi.string(), esHitsCheck: Joi.object({ - index: Joi.alternatives() - .try(Joi.string(), Joi.array().items(Joi.string())) - .required(), + index: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())).required(), query: Joi.object().required(), }).required(), }); @@ -79,9 +75,7 @@ const instructionSchema = Joi.object({ const instructionVariantSchema = Joi.object({ id: Joi.string().required(), - instructions: Joi.array() - .items(instructionSchema) - .required(), + instructions: Joi.array().items(instructionSchema).required(), }); const instructionSetSchema = Joi.object({ @@ -92,9 +86,7 @@ const instructionSetSchema = Joi.object({ iconType: Joi.string(), }), // Variants (OSes, languages, etc.) for which tutorial instructions are specified. - instructionVariants: Joi.array() - .items(instructionVariantSchema) - .required(), + instructionVariants: Joi.array().items(instructionVariantSchema).required(), statusCheck: statusCheckSchema, }); @@ -104,15 +96,11 @@ const paramSchema = Joi.object({ .regex(/^[a-zA-Z_]+$/) .required(), label: Joi.string().required(), - type: Joi.string() - .valid(Object.values(PARAM_TYPES)) - .required(), + type: Joi.string().valid(Object.values(PARAM_TYPES)).required(), }); const instructionsSchema = Joi.object({ - instructionSets: Joi.array() - .items(instructionSetSchema) - .required(), + instructionSets: Joi.array().items(instructionSetSchema).required(), params: Joi.array().items(paramSchema), }); @@ -120,9 +108,7 @@ export const tutorialSchema = { id: Joi.string() .regex(/^[a-zA-Z0-9-]+$/) .required(), - category: Joi.string() - .valid(Object.values(TUTORIAL_CATEGORY)) - .required(), + category: Joi.string().valid(Object.values(TUTORIAL_CATEGORY)).required(), name: Joi.string().required(), isBeta: Joi.boolean().default(false), shortDescription: Joi.string().required(), diff --git a/src/plugins/home/server/services/tutorials/tutorials_registry.ts b/src/plugins/home/server/services/tutorials/tutorials_registry.ts index ed28e42dbcf99..2122251743382 100644 --- a/src/plugins/home/server/services/tutorials/tutorials_registry.ts +++ b/src/plugins/home/server/services/tutorials/tutorials_registry.ts @@ -45,7 +45,7 @@ export class TutorialsRegistry { ); return res.ok({ - body: this.tutorialProviders.map(tutorialProvider => { + body: this.tutorialProviders.map((tutorialProvider) => { return tutorialProvider(scopedContext); // All the tutorialProviders need to be refactored so that they don't need the server. }), }); @@ -65,7 +65,7 @@ export class TutorialsRegistry { unregisterTutorial: (specProvider: TutorialProvider) => { this.tutorialProviders = this.tutorialProviders.filter( - provider => provider !== specProvider + (provider) => provider !== specProvider ); }, diff --git a/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx b/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx index d8a44675d80a0..cd21712ca28ed 100644 --- a/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx +++ b/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx @@ -98,7 +98,7 @@ export class CreateButton extends Component { anchorPosition="downLeft" > { + items={options.map((option) => { return ( { it('should render normally', () => { - const component = shallow( {}} prependBasePath={x => x} />); + const component = shallow( {}} prependBasePath={(x) => x} />); expect(component).toMatchSnapshot(); }); @@ -35,7 +35,7 @@ describe('EmptyState', () => { const onRefreshHandler = sinon.stub(); const component = shallow( - x} /> + x} /> ); component.find('[data-test-subj="refreshIndicesButton"]').simulate('click'); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx index e9eff57e17788..c590d2a7ddfe2 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx @@ -114,7 +114,7 @@ export class IndicesList extends React.Component ); - const items = PER_PAGE_INCREMENTS.map(increment => { + const items = PER_PAGE_INCREMENTS.map((increment) => { return ( { const component = createComponent({ initialQuery: 'kibana' }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected await component.update(); @@ -101,7 +101,7 @@ describe('StepIndexPattern', () => { instance.onQueryChanged({ target: { value: '?' } } as React.ChangeEvent); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); expect({ @@ -115,7 +115,7 @@ describe('StepIndexPattern', () => { instance.onQueryChanged({ target: { value: 'k' } } as React.ChangeEvent); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -142,7 +142,7 @@ describe('StepIndexPattern', () => { const instance = component.instance() as StepIndexPattern; instance.onQueryChanged({ target: { value: 'e' } } as React.ChangeEvent); instance.lastQuery = 'k'; - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Honesty, the state would match the result of the `k` query but // it's hard to mock this in tests but if remove our fix @@ -155,7 +155,7 @@ describe('StepIndexPattern', () => { // Provide `es` so we do not auto append * and enter our other code flow instance.onQueryChanged({ target: { value: 'es' } } as React.ChangeEvent); instance.lastQuery = 'k'; - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(component.state('exactMatchedIndices')).toEqual([]); }); }); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx index 5c8fa92d355a3..952eff4536346 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx @@ -103,7 +103,7 @@ export class StepIndexPattern extends Component + const existingIndexPatterns = savedObjects.map((obj) => obj && obj.attributes ? obj.attributes.title : '' ) as string[]; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx index d22b503937290..98e06d8a0f697 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx @@ -133,7 +133,7 @@ export class StepTimeField extends Component { - this.setState(state => ({ + this.setState((state) => ({ isAdvancedOptionsVisible: !state.isAdvancedOptionsVisible, })); }; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx index 62bf47546e103..89ed7dd97c3b6 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx @@ -109,7 +109,7 @@ export class CreateIndexPatternWizard extends Component< try { return await asyncFn; } catch (errors) { - this.setState(prevState => ({ + this.setState((prevState) => ({ toasts: prevState.toasts.concat([ { title: errorMsg, @@ -224,7 +224,7 @@ export class CreateIndexPatternWizard extends Component< }; onChangeIncludingSystemIndices = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isIncludingSystemIndices: !prevState.isIncludingSystemIndices, })); }; @@ -305,8 +305,8 @@ export class CreateIndexPatternWizard extends Component< } removeToast = (id: string) => { - this.setState(prevState => ({ - toasts: prevState.toasts.filter(toast => toast.id !== id), + this.setState((prevState) => ({ + toasts: prevState.toasts.filter((toast) => toast.id !== id), })); }; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts index ca4fc8122903c..48c708b016aef 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts @@ -18,5 +18,5 @@ */ export function containsIllegalCharacters(pattern: string, illegalCharacters: string[]) { - return illegalCharacters.some(char => pattern.includes(char)); + return illegalCharacters.some((char) => pattern.includes(char)); } diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts index e5fcfe056923a..a38f3cbd8fe81 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts @@ -20,25 +20,25 @@ import { ensureMinimumTime } from './ensure_minimum_time'; describe('ensureMinimumTime', () => { - it('resolves single promise', async done => { - const promiseA = new Promise(resolve => resolve('a')); + it('resolves single promise', async (done) => { + const promiseA = new Promise((resolve) => resolve('a')); const a = await ensureMinimumTime(promiseA, 0); expect(a).toBe('a'); done(); }); - it('resolves multiple promises', async done => { - const promiseA = new Promise(resolve => resolve('a')); - const promiseB = new Promise(resolve => resolve('b')); + it('resolves multiple promises', async (done) => { + const promiseA = new Promise((resolve) => resolve('a')); + const promiseB = new Promise((resolve) => resolve('b')); const [a, b] = await ensureMinimumTime([promiseA, promiseB], 0); expect(a).toBe('a'); expect(b).toBe('b'); done(); }); - it('resolves in the amount of time provided, at minimum', async done => { + it('resolves in the amount of time provided, at minimum', async (done) => { const startTime = new Date().getTime(); - const promise = new Promise(resolve => resolve()); + const promise = new Promise((resolve) => resolve()); await ensureMinimumTime(promise, 100); const endTime = new Date().getTime(); expect(endTime - startTime).toBeGreaterThanOrEqual(100); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts index 84852ece485eb..3b3895cbb9ad9 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts @@ -54,7 +54,7 @@ export async function ensureMinimumTime( if (asyncActionDuration < bufferedMinimumTimeMs) { const additionalWaitingTime = bufferedMinimumTimeMs - (asyncActionCompletionTime - asyncActionStartTime); - await new Promise(resolve => setTimeout(resolve, additionalWaitingTime)); + await new Promise((resolve) => setTimeout(resolve, additionalWaitingTime)); } return returnValue; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts index 809c9f77b2832..b7056ad17343a 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts @@ -21,7 +21,7 @@ import { i18n } from '@kbn/i18n'; import { IFieldType } from '../../../../../../plugins/data/public'; export function extractTimeFields(fields: IFieldType[]) { - const dateFields = fields.filter(field => field.type === 'date'); + const dateFields = fields.filter((field) => field.type === 'date'); const label = i18n.translate( 'indexPatternManagement.createIndexPattern.stepTime.noTimeFieldsLabel', { @@ -54,7 +54,7 @@ export function extractTimeFields(fields: IFieldType[]) { }; return [ - ...dateFields.map(field => ({ + ...dateFields.map((field) => ({ display: field.name, fieldName: field.name, })), diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts index 1c67fea9fa352..b1faca8a04964 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts @@ -92,7 +92,7 @@ function esClientFactory(search: (params: any) => any): LegacyApiCaller { search, msearch: () => ({ abort: () => {}, - ...new Promise(resolve => resolve({})), + ...new Promise((resolve) => resolve({})), }), }; } @@ -120,7 +120,7 @@ describe('getIndices', () => { it('should trim the input', async () => { let index; const esClient = esClientFactory( - jest.fn().mockImplementation(params => { + jest.fn().mockImplementation((params) => { index = params.index; }) ); @@ -132,7 +132,7 @@ describe('getIndices', () => { it('should use the limit', async () => { let limit; const esClient = esClientFactory( - jest.fn().mockImplementation(params => { + jest.fn().mockImplementation((params) => { limit = params.body.aggs.indices.terms.size; }) ); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts index cc3fd4075aa0e..7e2eeb17ab387 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts @@ -41,7 +41,7 @@ function filterSystemIndices(indices: MatchedIndex[], isIncludingSystemIndices: const acceptableIndices = isIncludingSystemIndices ? indices : // All system indices begin with a period. - indices.filter(index => !isSystemIndex(index.name)); + indices.filter((index) => !isSystemIndex(index.name)); return acceptableIndices.slice(0, MAX_NUMBER_OF_MATCHING_INDICES); } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx index f1c020cc409e0..ec28719429fba 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx @@ -100,14 +100,14 @@ export const EditIndexPattern = withRouter( ({ indexPattern, config, services, history, location }: EditIndexPatternProps) => { const [fields, setFields] = useState(indexPattern.getNonScriptedFields()); const [conflictedFields, setConflictedFields] = useState( - indexPattern.fields.filter(field => field.type === 'conflict') + indexPattern.fields.filter((field) => field.type === 'conflict') ); const [defaultIndex, setDefaultIndex] = useState(config.get('defaultIndex')); const [tags, setTags] = useState([]); useEffect(() => { setFields(indexPattern.getNonScriptedFields()); - setConflictedFields(indexPattern.fields.filter(field => field.type === 'conflict')); + setConflictedFields(indexPattern.fields.filter((field) => field.type === 'conflict')); }, [indexPattern]); useEffect(() => { @@ -127,7 +127,7 @@ export const EditIndexPattern = withRouter( const refreshFields = () => { services.overlays .openConfirm(confirmMessage, confirmModalOptionsRefresh) - .then(async isConfirmed => { + .then(async (isConfirmed) => { if (isConfirmed) { await indexPattern.init(true); setFields(indexPattern.getNonScriptedFields()); @@ -144,7 +144,7 @@ export const EditIndexPattern = withRouter( services.indexPatternManagement ); config.remove('defaultIndex'); - const otherPatterns = filter(indexPatterns, pattern => { + const otherPatterns = filter(indexPatterns, (pattern) => { return pattern.id !== indexPattern.id; }); @@ -153,12 +153,12 @@ export const EditIndexPattern = withRouter( } } - Promise.resolve(indexPattern.destroy()).then(function() { + Promise.resolve(indexPattern.destroy()).then(function () { history.push(''); }); } - services.overlays.openConfirm('', confirmModalOptionsDelete).then(isConfirmed => { + services.overlays.openConfirm('', confirmModalOptionsDelete).then((isConfirmed) => { if (isConfirmed) { doRemove(); } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts index f99a5b072b423..1febef1b3bb75 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts @@ -69,7 +69,7 @@ export function createEditIndexPatternPageStateContainer({ stateContainer: { ...stateContainer, // state syncing utility requires state containers to handle "null" - set: state => state && stateContainer.set(state), + set: (state) => state && stateContainer.set(state), }, stateStorage: kbnUrlStateStorage, }); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx index 2f3360880479c..8c024fa7adcf5 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx @@ -71,7 +71,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); @@ -91,7 +91,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.setProps({ fieldFilter: 'Elast' }); component.update(); @@ -112,7 +112,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.setProps({ indexedFieldTypeFilter: 'date' }); component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx index 6b1048d3c9d0c..3344c46c35ac6 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx @@ -73,7 +73,7 @@ export class IndexedFieldsTable extends Component< return ( (fields && - fields.map(field => { + fields.map((field) => { return { ...field, displayName: field.displayName, @@ -95,11 +95,11 @@ export class IndexedFieldsTable extends Component< (fields, fieldFilter, indexedFieldTypeFilter) => { if (fieldFilter) { const normalizedFieldFilter = fieldFilter.toLowerCase(); - fields = fields.filter(field => field.name.toLowerCase().includes(normalizedFieldFilter)); + fields = fields.filter((field) => field.name.toLowerCase().includes(normalizedFieldFilter)); } if (indexedFieldTypeFilter) { - fields = fields.filter(field => field.type === indexedFieldTypeFilter); + fields = fields.filter((field) => field.type === indexedFieldTypeFilter); } return fields; @@ -115,7 +115,7 @@ export class IndexedFieldsTable extends Component< this.props.helpers.redirectToRoute(field)} + editField={(field) => this.props.helpers.redirectToRoute(field)} /> ); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx index 32520eadaf199..532af2757915b 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx @@ -95,7 +95,7 @@ export class ScriptedFieldsTable extends Component< if (scriptedFieldLanguageFilter) { languageFilteredFields = fields.filter( - field => field.lang === this.props.scriptedFieldLanguageFilter + (field) => field.lang === this.props.scriptedFieldLanguageFilter ); } @@ -104,7 +104,7 @@ export class ScriptedFieldsTable extends Component< if (fieldFilter) { const normalizedFieldFilter = fieldFilter.toLowerCase(); - filteredFields = languageFilteredFields.filter(field => + filteredFields = languageFilteredFields.filter((field) => field.name.toLowerCase().includes(normalizedFieldFilter) ); } @@ -151,7 +151,7 @@ export class ScriptedFieldsTable extends Component<
this.props.helpers.redirectToRoute(field)} + editField={(field) => this.props.helpers.redirectToRoute(field)} deleteField={this.startDeleteField} /> diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx index 2a5e29827ccc5..1d840743065a1 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx @@ -49,7 +49,7 @@ export const AddFilter = ({ onAddFilter }: AddFilterProps) => { setFilter(e.target.value.trim())} + onChange={(e) => setFilter(e.target.value.trim())} placeholder={sourcePlaceholder} /> diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx index 421b5b67c2288..ab5a253a98e29 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx @@ -103,10 +103,7 @@ describe('Table', () => { // Wrap in a div because: https://github.com/airbnb/enzyme/issues/1213
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Ensure the state change propagates component.update(); @@ -123,10 +120,7 @@ describe('Table', () => {
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Ensure the state change propagates component.update(); @@ -159,10 +153,7 @@ describe('Table', () => {
{localComponent.prop('columns')[2].render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Update the value localComponent.setState({ editingFilterValue: 'time*' }); @@ -191,10 +182,7 @@ describe('Table', () => {
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); editingComponent.update(); @@ -228,10 +216,7 @@ describe('Table', () => { // Fixes Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `symbol`.
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - deleteCellComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + deleteCellComponent.find('EuiButtonIcon').at(1).simulate('click'); expect(deleteFilter).toBeCalled(); }); @@ -254,10 +239,7 @@ describe('Table', () => { // Fixes Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `symbol`.
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); component.update(); @@ -295,10 +277,7 @@ describe('Table', () => {
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); // Ensure the state change propagates component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx index ccdda3915e979..e5c753886ea9f 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx @@ -80,7 +80,7 @@ export class SourceFiltersTable extends Component< (filters, filterFilter) => { if (filterFilter) { const filterFilterToLowercase = filterFilter.toLowerCase(); - return filters.filter(filter => + return filters.filter((filter) => filter.value.toLowerCase().includes(filterFilterToLowercase) ); } @@ -107,7 +107,7 @@ export class SourceFiltersTable extends Component< const { indexPattern, onAddOrRemoveFilter } = this.props; const { filterToDelete, filters } = this.state; - indexPattern.sourceFilters = filters.filter(filter => { + indexPattern.sourceFilters = filters.filter((filter) => { return filter.clientId !== filterToDelete.clientId; }); @@ -143,7 +143,7 @@ export class SourceFiltersTable extends Component< const { indexPattern } = this.props; const { filters } = this.state; - indexPattern.sourceFilters = filters.map(filter => { + indexPattern.sourceFilters = filters.map((filter) => { if (filter.clientId === clientId) { return { value, diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx index 5cf7fd9b2af06..c364fb89dc41a 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx @@ -85,7 +85,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location const refreshFilters = useCallback(() => { const tempIndexedFieldTypes: string[] = []; const tempScriptedFieldLanguages: string[] = []; - indexPattern.fields.forEach(field => { + indexPattern.fields.forEach((field) => { if (field.scripted) { if (field.lang) { tempScriptedFieldLanguages.push(field.lang); @@ -118,7 +118,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setFieldFilter(e.target.value)} + onChange={(e) => setFieldFilter(e.target.value)} data-test-subj="indexPatternFieldFilter" aria-label={searchAriaLabel} /> @@ -128,7 +128,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setIndexedFieldTypeFilter(e.target.value)} + onChange={(e) => setIndexedFieldTypeFilter(e.target.value)} data-test-subj="indexedFieldTypeFilterDropdown" aria-label={filterAriaLabel} /> @@ -139,7 +139,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setScriptedFieldLanguageFilter(e.target.value)} + onChange={(e) => setScriptedFieldLanguageFilter(e.target.value)} data-test-subj="scriptedFieldLanguageFilterDropdown" /> @@ -272,8 +272,8 @@ export function Tabs({ config, indexPattern, fields, services, history, location return ( tab.id === selectedTabId)} - onTabClick={tab => { + selectedTab={euiTabs.find((tab) => tab.id === selectedTabId)} + onTabClick={(tab) => { setSelectedTabId(tab.id); syncingStateFunc.setCurrentTab(tab.id); }} diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts index b9b59142290dc..3088990aae981 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts @@ -25,7 +25,7 @@ import { TAB_INDEXED_FIELDS, TAB_SCRIPTED_FIELDS, TAB_SOURCE_FILTERS } from '../ function filterByName(items: IndexPatternField[], filter: string) { const lowercaseFilter = (filter || '').toLowerCase(); - return items.filter(item => item.name.toLowerCase().includes(lowercaseFilter)); + return items.filter((item) => item.name.toLowerCase().includes(lowercaseFilter)); } function getCounts( @@ -35,7 +35,7 @@ function getCounts( }, fieldFilter = '' ) { - const fieldCount = countBy(filterByName(fields, fieldFilter), function(field) { + const fieldCount = countBy(filterByName(fields, fieldFilter), function (field) { return field.scripted ? 'scripted' : 'indexed'; }); @@ -43,7 +43,7 @@ function getCounts( indexed: 0, scripted: 0, sourceFilters: sourceFilters.excludes - ? sourceFilters.excludes.filter(value => + ? sourceFilters.excludes.filter((value) => value.toLowerCase().includes(fieldFilter.toLowerCase()) ).length : 0, @@ -145,7 +145,7 @@ export function convertToEuiSelectOption(options: string[], type: string) { ] : []; return euiOptions.concat( - unique(options).map(option => { + unique(options).map((option) => { return { value: option, text: option, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/color/color.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/color/color.tsx index ba3e114800600..32b5d28872ac8 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/color/color.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/color/color.tsx @@ -105,7 +105,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onColorChange( { regex: e.target.value, @@ -129,7 +129,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onColorChange( { range: e.target.value, @@ -153,7 +153,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(newColor) => { this.onColorChange( { text: newColor, @@ -177,7 +177,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(newColor) => { this.onColorChange( { background: newColor, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx index 55860707a3ee9..e75750210d9c5 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx @@ -37,12 +37,8 @@ export class DateFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx index 25152370ac928..4c5227ae79118 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx @@ -77,7 +77,7 @@ export class DateNanosFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx index 68ece63c2efbe..de3038c3fd4f5 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx @@ -34,7 +34,7 @@ export const convertSampleInput = ( let samples: Sample[] = []; try { - samples = inputs.map(input => { + samples = inputs.map((input) => { return { input, output: converter(input), diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx index cdda56b4f1f51..bf25df069435f 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx @@ -116,7 +116,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< text: fmt.text, }; })} - onChange={e => { + onChange={(e) => { this.onChange({ inputFormat: e.target.value }); }} isInvalid={!!error} @@ -139,7 +139,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< text: fmt.text, }; })} - onChange={e => { + onChange={(e) => { this.onChange({ outputFormat: e.target.value }); }} isInvalid={!!error} @@ -160,7 +160,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< value={formatParams.outputPrecision} min={0} max={20} - onChange={e => { + onChange={(e) => { this.onChange({ outputPrecision: e.target.value ? Number(e.target.value) : null }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx index 05771afdd33e2..62c88b195f8b6 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx @@ -70,7 +70,7 @@ export class NumberFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx index fbbbb22e3d18f..0f80bfa681bf3 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx @@ -93,7 +93,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< return ( { + onChange={(e) => { this.onLookupChange( { key: e.target.value, @@ -117,7 +117,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< return ( { + onChange={(e) => { this.onLookupChange( { value: e.target.value, @@ -182,7 +182,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< defaultMessage: 'Leave blank to keep value as-is', } )} - onChange={e => { + onChange={(e) => { this.onChange({ unknownKeyValue: e.target.value }); }} /> diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx index d1befb77bae64..7a3bb6f5cd398 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx @@ -74,7 +74,7 @@ export class StringFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ transform: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx index 9b4d5a0f033a9..3881940a78627 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx @@ -58,7 +58,7 @@ export class TruncateFormatEditor extends DefaultFormatEditor { + onChange={(e) => { if (e.target.checkValidity()) { this.onChange({ fieldLength: e.target.value ? Number(e.target.value) : null, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx index 5b706f1627bce..30acf09526f85 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx @@ -151,7 +151,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ width: e.target.value }); }} /> @@ -164,7 +164,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ height: e.target.value }); }} /> @@ -201,7 +201,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< text: type.text, }; })} - onChange={e => { + onChange={(e) => { this.onTypeChange(e.target.value); }} /> @@ -225,7 +225,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< ) } checked={!formatParams.openLinkInCurrentTab} - onChange={e => { + onChange={(e) => { this.onChange({ openLinkInCurrentTab: !e.target.checked }); }} /> @@ -253,7 +253,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ urlTemplate: e.target.value }); }} /> @@ -280,7 +280,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ labelTemplate: e.target.value }); }} /> diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx index 0e324a67bac36..207b0b96ee7c8 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_help/test_script.tsx @@ -121,7 +121,7 @@ export class TestScript extends Component { this.setState({ isLoading: false, - previewData: scriptResponse.hits.hits.map(hit => ({ + previewData: scriptResponse.hits.hits.map((hit) => ({ _id: hit._id, ...hit._source, ...hit.fields, @@ -187,11 +187,11 @@ export class TestScript extends Component { const fields: EuiComboBoxOptionOption[] = []; this.props.indexPattern.fields - .filter(field => { + .filter((field) => { const isMultiField = field.subType && field.subType.multi; return !field.name.startsWith('_') && !isMultiField && !field.scripted; }) - .forEach(field => { + .forEach((field) => { if (fieldsByTypeMap.has(field.type)) { const fieldsList = fieldsByTypeMap.get(field.type); fieldsList.push(field.name); @@ -230,7 +230,7 @@ export class TestScript extends Component { })} options={fields} selectedOptions={this.state.additionalFields} - onChange={selected => this.onAdditionalFieldsChange(selected as AdditionalField[])} + onChange={(selected) => this.onAdditionalFieldsChange(selected as AdditionalField[])} data-test-subj="additionalFieldsSelect" fullWidth /> diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.test.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.test.tsx index 21b0e793bbaf0..1898e2397ae7f 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.test.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.test.tsx @@ -82,7 +82,7 @@ const fields: IndexPatternField[] = [ // @ts-ignore fields.getByName = (name: string) => { - return fields.find(field => field.name === name); + return fields.find((field) => field.name === name); }; class Format { @@ -127,7 +127,7 @@ describe('FieldEditor', () => { () => (({} as unknown) as FieldFormatInstanceType) ); - services.fieldFormats.getByFieldType = jest.fn(fieldType => { + services.fieldFormats.getByFieldType = jest.fn((fieldType) => { if (fieldType === 'number') { return [({} as unknown) as FieldFormatInstanceType]; } else { @@ -145,7 +145,7 @@ describe('FieldEditor', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); }); @@ -157,7 +157,7 @@ describe('FieldEditor', () => { script: 'doc.test.value', }; indexPattern.fields.push(testField as IndexPatternField); - indexPattern.fields.getByName = name => { + indexPattern.fields.getByName = (name) => { const flds = { [testField.name]: testField, }; @@ -172,7 +172,7 @@ describe('FieldEditor', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); }); @@ -185,7 +185,7 @@ describe('FieldEditor', () => { lang: 'testlang', }; indexPattern.fields.push((testField as unknown) as IndexPatternField); - indexPattern.fields.getByName = name => { + indexPattern.fields.getByName = (name) => { const flds = { [testField.name]: testField, }; @@ -200,7 +200,7 @@ describe('FieldEditor', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); }); @@ -215,7 +215,7 @@ describe('FieldEditor', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); (component.instance() as FieldEditor).onFieldChange('name', 'foobar'); component.update(); expect(component).toMatchSnapshot(); @@ -238,7 +238,7 @@ describe('FieldEditor', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); (component.instance() as FieldEditor).onFieldChange('name', 'foobar'); component.update(); expect(component).toMatchSnapshot(); diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx index 635772fbbfe5c..ace6167239b8c 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx @@ -199,7 +199,7 @@ export class FieldEditor extends PureComponent f.name === field.name), + isCreating: !indexPattern.fields.find((f) => f.name === field.name), isDeprecatedLang: this.deprecatedLangs.includes(field.lang || ''), errors: [], scriptingLangs, @@ -229,7 +229,7 @@ export class FieldEditor extends PureComponent uiSettings.get(key)); + field.format = new DefaultFieldFormat(null, (key) => uiSettings.get(key)); this.setState({ fieldTypeFormats: getFieldTypeFormatsList( @@ -261,7 +261,7 @@ export class FieldEditor extends PureComponent uiSettings.get(key)); + field.format = new FieldFormat(params, (key) => uiSettings.get(key)); this.setState({ fieldFormatId: FieldFormat.id, @@ -331,7 +331,7 @@ export class FieldEditor extends PureComponent { + onChange={(e) => { this.onFieldChange('name', e.target.value); }} isInvalid={isInvalid} @@ -385,11 +385,11 @@ export class FieldEditor extends PureComponent { + options={scriptingLangs.map((lang) => { return { value: lang, text: lang }; })} data-test-subj="editorFieldLang" - onChange={e => { + onChange={(e) => { this.onLangChange(e.target.value); }} /> @@ -407,11 +407,11 @@ export class FieldEditor extends PureComponent { + options={fieldTypes.map((type) => { return { value: type, text: type }; })} data-test-subj="editorFieldType" - onChange={e => { + onChange={(e) => { this.onTypeChange(e.target.value as KBN_FIELD_TYPES); }} /> @@ -506,11 +506,11 @@ export class FieldEditor extends PureComponent { + options={fieldTypeFormats.map((format) => { return { value: format.id || '', text: format.title }; })} data-test-subj="editorSelectedFormatId" - onChange={e => { + onChange={(e) => { this.onFormatChange(e.target.value); }} /> @@ -544,7 +544,7 @@ export class FieldEditor extends PureComponent { + onChange={(e) => { this.onFieldChange('count', e.target.value ? Number(e.target.value) : ''); }} /> diff --git a/src/plugins/index_pattern_management/public/components/index_pattern_table/index_pattern_table.tsx b/src/plugins/index_pattern_management/public/components/index_pattern_table/index_pattern_table.tsx index 599ed1fa04ee2..9ab95a62c8a8d 100644 --- a/src/plugins/index_pattern_management/public/components/index_pattern_table/index_pattern_table.tsx +++ b/src/plugins/index_pattern_management/public/components/index_pattern_table/index_pattern_table.tsx @@ -128,7 +128,7 @@ export const IndexPatternTable = ({ services.setBreadcrumbs(getListBreadcrumbs()); useEffect(() => { - (async function() { + (async function () { const options = await getIndexPatternCreationOptions(history.push); const gettedIndexPatterns: IndexPatternTableItem[] = await getIndexPatterns( services.savedObjectsClient, diff --git a/src/plugins/index_pattern_management/public/components/utils.ts b/src/plugins/index_pattern_management/public/components/utils.ts index 11da73aafb7b1..cd0bd66e8a0c5 100644 --- a/src/plugins/index_pattern_management/public/components/utils.ts +++ b/src/plugins/index_pattern_management/public/components/utils.ts @@ -32,9 +32,9 @@ export async function getIndexPatterns( fields: ['title', 'type'], perPage: 10000, }) - .then(response => + .then((response) => response.savedObjects - .map(pattern => { + .map((pattern) => { const id = pattern.id; const title = pattern.get('title'); const isDefault = defaultIndex === id; diff --git a/src/plugins/index_pattern_management/public/plugin.ts b/src/plugins/index_pattern_management/public/plugin.ts index aa28422956a38..ebcd92f25c13b 100644 --- a/src/plugins/index_pattern_management/public/plugin.ts +++ b/src/plugins/index_pattern_management/public/plugin.ts @@ -74,8 +74,8 @@ export class IndexPatternManagementPlugin const newAppPath = `kibana#/management/kibana/${IPM_APP_ID}`; const legacyPatternsPath = 'management/kibana/index_patterns'; - kibanaLegacy.forwardApp('management/kibana/index_pattern', newAppPath, path => '/create'); - kibanaLegacy.forwardApp(legacyPatternsPath, newAppPath, path => { + kibanaLegacy.forwardApp('management/kibana/index_pattern', newAppPath, (path) => '/create'); + kibanaLegacy.forwardApp(legacyPatternsPath, newAppPath, (path) => { const pathInApp = path.substr(legacyPatternsPath.length + 1); return pathInApp && `/patterns${pathInApp}`; }); @@ -84,7 +84,7 @@ export class IndexPatternManagementPlugin id: IPM_APP_ID, title: sectionsHeader, order: 0, - mount: async params => { + mount: async (params) => { const { mountManagementSection } = await import('./management_app'); return mountManagementSection(core.getStartServices, params); diff --git a/src/plugins/index_pattern_management/public/service/creation/manager.ts b/src/plugins/index_pattern_management/public/service/creation/manager.ts index c97d7a084dca3..96c47e3379f1f 100644 --- a/src/plugins/index_pattern_management/public/service/creation/manager.ts +++ b/src/plugins/index_pattern_management/public/service/creation/manager.ts @@ -28,7 +28,7 @@ export class IndexPatternCreationManager { addCreationConfig: (Config: typeof IndexPatternCreationConfig) => { const config = new Config({ httpClient }); - if (this.configs.findIndex(c => c.key === config.key) !== -1) { + if (this.configs.findIndex((c) => c.key === config.key) !== -1) { throw new Error(`${config.key} exists in IndexPatternCreationManager.`); } @@ -40,7 +40,7 @@ export class IndexPatternCreationManager { start() { const getType = (key: string | undefined): IndexPatternCreationConfig => { if (key) { - const index = this.configs.findIndex(config => config.key === key); + const index = this.configs.findIndex((config) => config.key === key); const config = this.configs[index]; if (config) { @@ -59,7 +59,7 @@ export class IndexPatternCreationManager { const options: IndexPatternCreationOption[] = []; await Promise.all( - this.configs.map(async config => { + this.configs.map(async (config) => { const option = config.getIndexPatternCreationOption ? await config.getIndexPatternCreationOption(urlHandler) : null; diff --git a/src/plugins/index_pattern_management/public/service/field_format_editors/field_format_editors.ts b/src/plugins/index_pattern_management/public/service/field_format_editors/field_format_editors.ts index f85238c5d9622..b497dc4cd8ae1 100644 --- a/src/plugins/index_pattern_management/public/service/field_format_editors/field_format_editors.ts +++ b/src/plugins/index_pattern_management/public/service/field_format_editors/field_format_editors.ts @@ -36,7 +36,7 @@ export class FieldFormatEditors { return { getAll: () => [...this.editors], getById: (id: string) => { - return this.editors.find(editor => editor.formatId === id); + return this.editors.find((editor) => editor.formatId === id); }, }; } diff --git a/src/plugins/index_pattern_management/public/service/list/manager.ts b/src/plugins/index_pattern_management/public/service/list/manager.ts index 6e8b430ffdc26..bdb31364219c0 100644 --- a/src/plugins/index_pattern_management/public/service/list/manager.ts +++ b/src/plugins/index_pattern_management/public/service/list/manager.ts @@ -29,7 +29,7 @@ export class IndexPatternListManager { addListConfig: (Config: typeof IndexPatternListConfig) => { const config = new Config(); - if (this.configs.findIndex(c => c.key === config.key) !== -1) { + if (this.configs.findIndex((c) => c.key === config.key) !== -1) { throw new Error(`${config.key} exists in IndexPatternListManager.`); } this.configs.push(config); @@ -59,7 +59,7 @@ export class IndexPatternListManager { ), areScriptedFieldsEnabled: (indexPattern: IIndexPattern): boolean => - this.configs.every(config => + this.configs.every((config) => config.areScriptedFieldsEnabled ? config.areScriptedFieldsEnabled(indexPattern) : true ), }; diff --git a/src/plugins/input_control_vis/public/components/editor/controls_tab.tsx b/src/plugins/input_control_vis/public/components/editor/controls_tab.tsx index b7114f1029ef2..19046f7f62fba 100644 --- a/src/plugins/input_control_vis/public/components/editor/controls_tab.tsx +++ b/src/plugins/input_control_vis/public/components/editor/controls_tab.tsx @@ -191,7 +191,7 @@ class ControlsTabUi extends PureComponent this.setState({ type: event.target.value as CONTROL_TYPES })} + onChange={(event) => this.setState({ type: event.target.value as CONTROL_TYPES })} aria-label={intl.formatMessage({ id: 'inputControl.editor.controlsTab.select.controlTypeAriaLabel', defaultMessage: 'Select control type', diff --git a/src/plugins/input_control_vis/public/components/editor/field_select.tsx b/src/plugins/input_control_vis/public/components/editor/field_select.tsx index 779f3ad6b1a8a..2885cbf24553f 100644 --- a/src/plugins/input_control_vis/public/components/editor/field_select.tsx +++ b/src/plugins/input_control_vis/public/components/editor/field_select.tsx @@ -117,7 +117,7 @@ class FieldSelectUi extends Component { fieldsByTypeMap.forEach((fieldsList, fieldType) => { fields.push({ label: fieldType, - options: fieldsList.sort().map(fieldName => { + options: fieldsList.sort().map((fieldName) => { return { value: fieldName, label: fieldName }; }), }); diff --git a/src/plugins/input_control_vis/public/components/editor/list_control_editor.tsx b/src/plugins/input_control_vis/public/components/editor/list_control_editor.tsx index 3da3ae9ba757c..cf105d16f0535 100644 --- a/src/plugins/input_control_vis/public/components/editor/list_control_editor.tsx +++ b/src/plugins/input_control_vis/public/components/editor/list_control_editor.tsx @@ -167,7 +167,7 @@ export class ListControlEditor extends PureComponent< { + onChange={(event) => { this.props.handleParentChange(this.props.controlIndex, event.target.value); }} /> @@ -194,7 +194,7 @@ export class ListControlEditor extends PureComponent< /> } checked={this.props.controlParams.options.multiselect ?? true} - onChange={event => { + onChange={(event) => { this.props.handleOptionsChange( this.props.controlIndex, 'multiselect', @@ -231,7 +231,7 @@ export class ListControlEditor extends PureComponent< /> } checked={this.props.controlParams.options.dynamicOptions ?? false} - onChange={event => { + onChange={(event) => { this.props.handleOptionsChange( this.props.controlIndex, 'dynamicOptions', @@ -266,7 +266,7 @@ export class ListControlEditor extends PureComponent< { + onChange={(event) => { this.props.handleOptionsChange( this.props.controlIndex, 'size', diff --git a/src/plugins/input_control_vis/public/components/editor/range_control_editor.tsx b/src/plugins/input_control_vis/public/components/editor/range_control_editor.tsx index b6b852bcfa707..92169705f0a10 100644 --- a/src/plugins/input_control_vis/public/components/editor/range_control_editor.tsx +++ b/src/plugins/input_control_vis/public/components/editor/range_control_editor.tsx @@ -104,7 +104,7 @@ export class RangeControlEditor extends Component< > { + onChange={(event) => { this.props.handleOptionsChange( this.props.controlIndex, 'step', @@ -127,7 +127,7 @@ export class RangeControlEditor extends Component< { + onChange={(event) => { this.props.handleOptionsChange( this.props.controlIndex, 'decimalPlaces', diff --git a/src/plugins/input_control_vis/public/components/vis/input_control_vis.tsx b/src/plugins/input_control_vis/public/components/vis/input_control_vis.tsx index c0ef99664fdf8..95edb4a35bc22 100644 --- a/src/plugins/input_control_vis/public/components/vis/input_control_vis.tsx +++ b/src/plugins/input_control_vis/public/components/vis/input_control_vis.tsx @@ -85,7 +85,7 @@ export class InputControlVis extends Component { dynamicOptions={control.options.dynamicOptions} controlIndex={index} stageFilter={this.props.stageFilter} - fetchOptions={query => { + fetchOptions={(query) => { this.props.refreshControl(index, query); }} /> diff --git a/src/plugins/input_control_vis/public/components/vis/list_control.tsx b/src/plugins/input_control_vis/public/components/vis/list_control.tsx index cf95eed470beb..8ca93a302be89 100644 --- a/src/plugins/input_control_vis/public/components/vis/list_control.tsx +++ b/src/plugins/input_control_vis/public/components/vis/list_control.tsx @@ -128,7 +128,7 @@ class ListControlUi extends PureComponent { + ?.map((option) => { return { label: this.props.formatOptionLabel(option).toString(), value: option, @@ -139,7 +139,7 @@ class ListControlUi extends PureComponent { + const selectedOptions = this.props.selectedOptions.map((selectedOption) => { return { label: this.props.formatOptionLabel(selectedOption).toString(), value: selectedOption, diff --git a/src/plugins/input_control_vis/public/control/control.test.ts b/src/plugins/input_control_vis/public/control/control.test.ts index a2d220c14a3f7..58dec461953ca 100644 --- a/src/plugins/input_control_vis/public/control/control.test.ts +++ b/src/plugins/input_control_vis/public/control/control.test.ts @@ -101,7 +101,7 @@ describe('ancestors', () => { }); describe('hasUnsetAncestor', () => { - test('should be true if parent is not set', function() { + test('should be true if parent is not set', function () { grandParentControl.set('myGrandParentValue'); childControl.setAncestors([parentControl, grandParentControl]); @@ -110,7 +110,7 @@ describe('ancestors', () => { expect(childControl.hasUnsetAncestor()).to.be(true); }); - test('should be true if grand parent is not set', function() { + test('should be true if grand parent is not set', function () { parentControl.set('myParentValue'); childControl.setAncestors([parentControl, grandParentControl]); @@ -119,7 +119,7 @@ describe('ancestors', () => { expect(childControl.hasUnsetAncestor()).to.be(true); }); - test('should be false if all ancestors are set', function() { + test('should be false if all ancestors are set', function () { grandParentControl.set('myGrandParentValue'); parentControl.set('myParentValue'); @@ -139,25 +139,25 @@ describe('ancestors', () => { lastAncestorValues = childControl.getAncestorValues(); }); - test('should be the same when ancestor values have not changed', function() { + test('should be the same when ancestor values have not changed', function () { const newAncestorValues = childControl.getAncestorValues(); expect(newAncestorValues).to.eql(lastAncestorValues); }); - test('should be different when grand parent value changes', function() { + test('should be different when grand parent value changes', function () { grandParentControl.set('new myGrandParentValue'); const newAncestorValues = childControl.getAncestorValues(); expect(newAncestorValues).to.not.eql(lastAncestorValues); }); - test('should be different when parent value changes', function() { + test('should be different when parent value changes', function () { parentControl.set('new myParentValue'); const newAncestorValues = childControl.getAncestorValues(); expect(newAncestorValues).to.not.eql(lastAncestorValues); }); }); - test('should build filters from ancestors', function() { + test('should build filters from ancestors', function () { grandParentControl.set('myGrandParentValue'); parentControl.set('myParentValue'); diff --git a/src/plugins/input_control_vis/public/control/control.ts b/src/plugins/input_control_vis/public/control/control.ts index c57b09a19ebc8..1e1e05c96cc1a 100644 --- a/src/plugins/input_control_vis/public/control/control.ts +++ b/src/plugins/input_control_vis/public/control/control.ts @@ -106,13 +106,13 @@ export abstract class Control { } getAncestorValues() { - return this.ancestors.map(ancestor => { + return this.ancestors.map((ancestor) => { return ancestor.value; }); } getAncestorFilters() { - return this.ancestors.map(ancestor => { + return this.ancestors.map((ancestor) => { return ancestor.filterManager.createFilter(ancestor.value); }); } diff --git a/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.test.ts b/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.test.ts index a9b7550be44ae..e0eeddf93f67e 100644 --- a/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.test.ts +++ b/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.test.ts @@ -35,10 +35,10 @@ class FilterManagerTest extends FilterManager { } } -describe('FilterManager', function() { +describe('FilterManager', function () { const controlId = 'control1'; - describe('findFilters', function() { + describe('findFilters', function () { const indexPatternMock = {} as IndexPattern; let kbnFilters: Filter[]; const queryFilterMock = new QueryFilterManager(setupMock.uiSettings); @@ -51,13 +51,13 @@ describe('FilterManager', function() { filterManager = new FilterManagerTest(controlId, 'field1', indexPatternMock, queryFilterMock); }); - test('should not find filters that are not controlled by any visualization', function() { + test('should not find filters that are not controlled by any visualization', function () { kbnFilters.push({} as Filter); const foundFilters = filterManager.findFilters(); expect(foundFilters.length).to.be(0); }); - test('should not find filters that are controlled by other Visualizations', function() { + test('should not find filters that are controlled by other Visualizations', function () { kbnFilters.push({ meta: { controlledBy: 'anotherControl', @@ -67,7 +67,7 @@ describe('FilterManager', function() { expect(foundFilters.length).to.be(0); }); - test('should find filter that is controlled by target Visualization', function() { + test('should find filter that is controlled by target Visualization', function () { kbnFilters.push({ meta: { controlledBy: controlId, diff --git a/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.ts b/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.ts index bb806b336c3e0..ece3f7a88ba37 100644 --- a/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.ts +++ b/src/plugins/input_control_vis/public/control/filter_manager/filter_manager.ts @@ -54,7 +54,7 @@ export abstract class FilterManager { this.queryFilter.getAppFilters(), this.queryFilter.getGlobalFilters(), ]); - return kbnFilters.filter(kbnFilter => { + return kbnFilters.filter((kbnFilter) => { return _.get(kbnFilter, 'meta.controlledBy') === this.controlId; }); } diff --git a/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.test.ts b/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.test.ts index 6398c10b63a8c..ec1f9d42aa67b 100644 --- a/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.test.ts +++ b/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.test.ts @@ -22,10 +22,10 @@ import expect from '@kbn/expect'; import { Filter, IndexPattern, FilterManager as QueryFilterManager } from '../../../../data/public'; import { PhraseFilterManager } from './phrase_filter_manager'; -describe('PhraseFilterManager', function() { +describe('PhraseFilterManager', function () { const controlId = 'control1'; - describe('createFilter', function() { + describe('createFilter', function () { const indexPatternId = '1'; const fieldMock = { name: 'field1', @@ -53,7 +53,7 @@ describe('PhraseFilterManager', function() { ); }); - test('should create match phrase filter from single value', function() { + test('should create match phrase filter from single value', function () { const newFilter = filterManager.createFilter(['ios']); expect(newFilter).to.have.property('meta'); expect(newFilter.meta.index).to.be(indexPatternId); @@ -63,7 +63,7 @@ describe('PhraseFilterManager', function() { expect(JSON.stringify(newFilter.query, null, '')).to.be('{"match_phrase":{"field1":"ios"}}'); }); - test('should create bool filter from multiple values', function() { + test('should create bool filter from multiple values', function () { const newFilter = filterManager.createFilter(['ios', 'win xp']); expect(newFilter).to.have.property('meta'); expect(newFilter.meta.index).to.be(indexPatternId); @@ -82,7 +82,7 @@ describe('PhraseFilterManager', function() { }); }); - describe('getValueFromFilterBar', function() { + describe('getValueFromFilterBar', function () { class MockFindFiltersPhraseFilterManager extends PhraseFilterManager { mockFilters: Filter[]; @@ -117,7 +117,7 @@ describe('PhraseFilterManager', function() { ); }); - test('should extract value from match phrase filter', function() { + test('should extract value from match phrase filter', function () { filterManager.setMockFilters([ { query: { @@ -133,7 +133,7 @@ describe('PhraseFilterManager', function() { expect(filterManager.getValueFromFilterBar()).to.eql(['ios']); }); - test('should extract value from multiple filters', function() { + test('should extract value from multiple filters', function () { filterManager.setMockFilters([ { query: { @@ -159,7 +159,7 @@ describe('PhraseFilterManager', function() { expect(filterManager.getValueFromFilterBar()).to.eql(['ios', 'win xp']); }); - test('should extract value from bool filter', function() { + test('should extract value from bool filter', function () { filterManager.setMockFilters([ { query: { @@ -183,7 +183,7 @@ describe('PhraseFilterManager', function() { expect(filterManager.getValueFromFilterBar()).to.eql(['ios', 'win xp']); }); - test('should return undefined when filter value can not be extracted from Kibana filter', function() { + test('should return undefined when filter value can not be extracted from Kibana filter', function () { filterManager.setMockFilters([ { query: { diff --git a/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.ts b/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.ts index bf167afa69bcf..4eff5112c0c07 100644 --- a/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.ts +++ b/src/plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.ts @@ -63,10 +63,10 @@ export class PhraseFilterManager extends FilterManager { } const values = kbnFilters - .map(kbnFilter => { + .map((kbnFilter) => { return this.getValueFromFilter(kbnFilter); }) - .filter(value => value != null); + .filter((value) => value != null); if (values.length === 0) { return; @@ -87,10 +87,10 @@ export class PhraseFilterManager extends FilterManager { // bool filter - multiple phrase filters if (_.has(kbnFilter, 'query.bool.should')) { return _.get(kbnFilter, 'query.bool.should') - .map(kbnQueryFilter => { + .map((kbnQueryFilter) => { return this.getValueFromFilter(kbnQueryFilter); }) - .filter(value => { + .filter((value) => { if (value) { return true; } diff --git a/src/plugins/input_control_vis/public/control/filter_manager/range_filter_manager.test.ts b/src/plugins/input_control_vis/public/control/filter_manager/range_filter_manager.test.ts index 6e66b6942e5d3..8556312d10f4a 100644 --- a/src/plugins/input_control_vis/public/control/filter_manager/range_filter_manager.test.ts +++ b/src/plugins/input_control_vis/public/control/filter_manager/range_filter_manager.test.ts @@ -27,10 +27,10 @@ import { FilterManager as QueryFilterManager, } from '../../../../data/public'; -describe('RangeFilterManager', function() { +describe('RangeFilterManager', function () { const controlId = 'control1'; - describe('createFilter', function() { + describe('createFilter', function () { const indexPatternId = '1'; const fieldMock = { name: 'field1', @@ -57,7 +57,7 @@ describe('RangeFilterManager', function() { ); }); - test('should create range filter from slider value', function() { + test('should create range filter from slider value', function () { const newFilter = filterManager.createFilter({ min: 1, max: 3 }); expect(newFilter).to.have.property('meta'); expect(newFilter.meta.index).to.be(indexPatternId); @@ -68,7 +68,7 @@ describe('RangeFilterManager', function() { }); }); - describe('getValueFromFilterBar', function() { + describe('getValueFromFilterBar', function () { class MockFindFiltersRangeFilterManager extends RangeFilterManager { mockFilters: RangeFilter[]; @@ -103,7 +103,7 @@ describe('RangeFilterManager', function() { ); }); - test('should extract value from range filter', function() { + test('should extract value from range filter', function () { filterManager.setMockFilters([ { range: { @@ -123,7 +123,7 @@ describe('RangeFilterManager', function() { expect(value?.max).to.be(3); }); - test('should return undefined when filter value can not be extracted from Kibana filter', function() { + test('should return undefined when filter value can not be extracted from Kibana filter', function () { filterManager.setMockFilters([ { range: { diff --git a/src/plugins/input_control_vis/public/control/list_control_factory.ts b/src/plugins/input_control_vis/public/control/list_control_factory.ts index 45dc13f4e3a34..65a3e37a93edf 100644 --- a/src/plugins/input_control_vis/public/control/list_control_factory.ts +++ b/src/plugins/input_control_vis/public/control/list_control_factory.ts @@ -33,7 +33,7 @@ import { InputControlSettings, InputControlVisDependencies } from '../plugin'; function getEscapedQuery(query = '') { // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html#_standard_operators - return query.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, match => `\\${match}`); + return query.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, (match) => `\\${match}`); } interface TermsAggArgs { diff --git a/src/plugins/input_control_vis/public/lineage/lineage_map.ts b/src/plugins/input_control_vis/public/lineage/lineage_map.ts index d74782c373942..c6c8bc88308b8 100644 --- a/src/plugins/input_control_vis/public/lineage/lineage_map.ts +++ b/src/plugins/input_control_vis/public/lineage/lineage_map.ts @@ -22,13 +22,13 @@ import { ControlParams } from '../editor_utils'; export function getLineageMap(controlParamsList: ControlParams[]) { function getControlParamsById(controlId: string) { - return controlParamsList.find(controlParams => { + return controlParamsList.find((controlParams) => { return controlParams.id === controlId; }); } const lineageMap = new Map(); - controlParamsList.forEach(rootControlParams => { + controlParamsList.forEach((rootControlParams) => { const lineage = [rootControlParams.id]; const getLineage = (controlParams: ControlParams) => { if ( diff --git a/src/plugins/input_control_vis/public/lineage/parent_candidates.ts b/src/plugins/input_control_vis/public/lineage/parent_candidates.ts index af4fddef19001..b2aba4b087490 100644 --- a/src/plugins/input_control_vis/public/lineage/parent_candidates.ts +++ b/src/plugins/input_control_vis/public/lineage/parent_candidates.ts @@ -25,7 +25,7 @@ export function getParentCandidates( lineageMap: Map ) { return controlParamsList - .filter(controlParams => { + .filter((controlParams) => { // Ignore controls that do not have index pattern and field set if (!controlParams.indexPattern || !controlParams.fieldName) { return false; diff --git a/src/plugins/input_control_vis/public/test_utils/update_component.ts b/src/plugins/input_control_vis/public/test_utils/update_component.ts index 881412a7c56fd..50faf1603dfd2 100644 --- a/src/plugins/input_control_vis/public/test_utils/update_component.ts +++ b/src/plugins/input_control_vis/public/test_utils/update_component.ts @@ -25,7 +25,7 @@ export const updateComponent = async ( | ReactWrapper, React.Component<{}, {}, any>> ) => { // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); }; diff --git a/src/plugins/input_control_vis/public/vis_controller.tsx b/src/plugins/input_control_vis/public/vis_controller.tsx index 97506556d7e0a..e4310960851ca 100644 --- a/src/plugins/input_control_vis/public/vis_controller.tsx +++ b/src/plugins/input_control_vis/public/vis_controller.tsx @@ -64,7 +64,7 @@ export const createInputControlVisController = (deps: InputControlVisDependencie destroy() { this.updateSubsciption.unsubscribe(); unmountComponentAtNode(this.el); - this.controls.forEach(control => control.destroy()); + this.controls.forEach((control) => control.destroy()); } drawVis = () => { @@ -92,13 +92,13 @@ export const createInputControlVisController = (deps: InputControlVisDependencie async initControls() { const controlParamsList = (this.visParams?.controls as ControlParams[])?.filter( - controlParams => { + (controlParams) => { // ignore controls that do not have indexPattern or field return controlParams.indexPattern && controlParams.fieldName; } ); - const controlFactoryPromises = controlParamsList.map(controlParams => { + const controlFactoryPromises = controlParamsList.map((controlParams) => { const factory = getControlFactory(controlParams); return factory(controlParams, this.visParams?.useTimeFilter, deps); @@ -114,7 +114,7 @@ export const createInputControlVisController = (deps: InputControlVisDependencie // first lineage item is the control. remove it lineage.shift(); const ancestors: Array = []; - lineage.forEach(ancestorId => { + lineage.forEach((ancestorId) => { const control = getControl(ancestorId); if (control) { @@ -146,19 +146,19 @@ export const createInputControlVisController = (deps: InputControlVisDependencie }; submitFilters = () => { - const stagedControls = this.controls.filter(control => { + const stagedControls = this.controls.filter((control) => { return control.hasChanged(); }); const newFilters = stagedControls - .map(control => control.getKbnFilter()) + .map((control) => control.getKbnFilter()) .filter((filter): filter is Filter => { return filter !== null; }); - stagedControls.forEach(control => { + stagedControls.forEach((control) => { // to avoid duplicate filters, remove any old filters for control - control.filterManager.findFilters().forEach(existingFilter => { + control.filterManager.findFilters().forEach((existingFilter) => { this.filterManager.removeFilter(existingFilter); }); }); @@ -166,9 +166,9 @@ export const createInputControlVisController = (deps: InputControlVisDependencie // Clean up filter pills for nested controls that are now disabled because ancestors are not set. // This has to be done after looking up the staged controls because otherwise removing a filter // will re-sync the controls of all other filters. - this.controls.map(control => { + this.controls.map((control) => { if (control.hasAncestors() && control.hasUnsetAncestor()) { - control.filterManager.findFilters().forEach(existingFilter => { + control.filterManager.findFilters().forEach((existingFilter) => { this.filterManager.removeFilter(existingFilter); }); } @@ -178,7 +178,7 @@ export const createInputControlVisController = (deps: InputControlVisDependencie }; clearControls = async () => { - this.controls.forEach(control => { + this.controls.forEach((control) => { control.clear(); }); await this.updateNestedControls(); @@ -186,7 +186,7 @@ export const createInputControlVisController = (deps: InputControlVisDependencie }; updateControlsFromKbn = async () => { - this.controls.forEach(control => { + this.controls.forEach((control) => { control.reset(); }); await this.updateNestedControls(); @@ -194,7 +194,7 @@ export const createInputControlVisController = (deps: InputControlVisDependencie }; async updateNestedControls() { - const fetchPromises = this.controls.map(async control => { + const fetchPromises = this.controls.map(async (control) => { if (control.hasAncestors()) { await control.fetch(); } @@ -203,12 +203,12 @@ export const createInputControlVisController = (deps: InputControlVisDependencie } hasChanges = () => { - return this.controls.map(control => control.hasChanged()).some(control => control); + return this.controls.map((control) => control.hasChanged()).some((control) => control); }; hasValues = () => { return this.controls - .map(control => { + .map((control) => { return control.hasValue(); }) .reduce((a, b) => { diff --git a/src/plugins/inspector/common/adapters/data/data_adapter.ts b/src/plugins/inspector/common/adapters/data/data_adapter.ts index c68ded588f022..34e6c278c693f 100644 --- a/src/plugins/inspector/common/adapters/data/data_adapter.ts +++ b/src/plugins/inspector/common/adapters/data/data_adapter.ts @@ -35,7 +35,7 @@ class DataAdapter extends EventEmitter { return Promise.resolve({ data: null, options: {} }); } const options = this.tabularOptions; - return Promise.resolve(this.tabular()).then(data => ({ data, options })); + return Promise.resolve(this.tabular()).then((data) => ({ data, options })); } } diff --git a/src/plugins/inspector/common/adapters/request/request_adapter.test.ts b/src/plugins/inspector/common/adapters/request/request_adapter.test.ts index 3f928c00533b0..bb20348dacbfd 100644 --- a/src/plugins/inspector/common/adapters/request/request_adapter.test.ts +++ b/src/plugins/inspector/common/adapters/request/request_adapter.test.ts @@ -29,7 +29,7 @@ describe('RequestAdapter', () => { describe('getRequests()', () => { function requestNames(requests: Request[]) { - return requests.map(req => req.name); + return requests.map((req) => req.name); } it('should return all started requests', () => { diff --git a/src/plugins/inspector/public/plugin.tsx b/src/plugins/inspector/public/plugin.tsx index cc9f2404d802f..29db88dc4a553 100644 --- a/src/plugins/inspector/public/plugin.tsx +++ b/src/plugins/inspector/public/plugin.tsx @@ -82,7 +82,7 @@ export class InspectorPublicPlugin implements Plugin { } public start(core: CoreStart) { - const isAvailable: Start['isAvailable'] = adapters => + const isAvailable: Start['isAvailable'] = (adapters) => this.views!.getVisible(adapters).length > 0; const closeButtonLabel = i18n.translate('inspector.closeButton', { diff --git a/src/plugins/inspector/public/ui/inspector_panel.tsx b/src/plugins/inspector/public/ui/inspector_panel.tsx index 953bf7e1f073b..85705b6b74f55 100644 --- a/src/plugins/inspector/public/ui/inspector_panel.tsx +++ b/src/plugins/inspector/public/ui/inspector_panel.tsx @@ -27,7 +27,7 @@ import { InspectorViewChooser } from './inspector_view_chooser'; function hasAdaptersChanged(oldAdapters: Adapters, newAdapters: Adapters) { return ( Object.keys(oldAdapters).length !== Object.keys(newAdapters).length || - Object.keys(oldAdapters).some(key => oldAdapters[key] !== newAdapters[key]) + Object.keys(oldAdapters).some((key) => oldAdapters[key] !== newAdapters[key]) ); } diff --git a/src/plugins/inspector/public/ui/inspector_view_chooser.tsx b/src/plugins/inspector/public/ui/inspector_view_chooser.tsx index ce6027ad383cf..e1502e5e912e6 100644 --- a/src/plugins/inspector/public/ui/inspector_view_chooser.tsx +++ b/src/plugins/inspector/public/ui/inspector_view_chooser.tsx @@ -51,7 +51,7 @@ export class InspectorViewChooser extends Component { }; toggleSelector = () => { - this.setState(prev => ({ + this.setState((prev) => ({ isSelectorOpen: !prev.isSelectorOpen, })); }; diff --git a/src/plugins/inspector/public/view_registry.test.ts b/src/plugins/inspector/public/view_registry.test.ts index 830ee107213fb..542328d4f48da 100644 --- a/src/plugins/inspector/public/view_registry.test.ts +++ b/src/plugins/inspector/public/view_registry.test.ts @@ -59,7 +59,7 @@ describe('InspectorViewRegistry', () => { registry.register(view1); registry.register(view2); const views = registry.getAll(); - expect(views.map(v => v.title)).toEqual(['view2', 'view1']); + expect(views.map((v) => v.title)).toEqual(['view2', 'view1']); }); describe('getVisible()', () => { @@ -78,7 +78,7 @@ describe('InspectorViewRegistry', () => { registry.register(view1); registry.register(view2); const views = registry.getVisible({}); - expect(views.map(v => v.title)).toEqual(['view1']); + expect(views.map((v) => v.title)).toEqual(['view1']); }); it('views without shouldShow should be included', () => { @@ -87,7 +87,7 @@ describe('InspectorViewRegistry', () => { registry.register(view1); registry.register(view2); const views = registry.getVisible({}); - expect(views.map(v => v.title)).toEqual(['view1', 'view2']); + expect(views.map((v) => v.title)).toEqual(['view1', 'view2']); }); it('should pass the adapters to the callbacks', () => { diff --git a/src/plugins/inspector/public/view_registry.ts b/src/plugins/inspector/public/view_registry.ts index 4a35baf1f3ef4..800d917af28ca 100644 --- a/src/plugins/inspector/public/view_registry.ts +++ b/src/plugins/inspector/public/view_registry.ts @@ -69,6 +69,6 @@ export class InspectorViewRegistry extends EventEmitter { if (!adapters) { return []; } - return this.views.filter(view => !view.shouldShow || view.shouldShow(adapters)); + return this.views.filter((view) => !view.shouldShow || view.shouldShow(adapters)); } } diff --git a/src/plugins/inspector/public/views/data/components/download_options.tsx b/src/plugins/inspector/public/views/data/components/download_options.tsx index e7bfbed23c074..cedb723091638 100644 --- a/src/plugins/inspector/public/views/data/components/download_options.tsx +++ b/src/plugins/inspector/public/views/data/components/download_options.tsx @@ -55,7 +55,7 @@ class DataDownloadOptions extends Component { - this.setState(state => ({ + this.setState((state) => ({ isPopoverOpen: !state.isPopoverOpen, })); }; diff --git a/src/plugins/inspector/public/views/data/lib/export_csv.ts b/src/plugins/inspector/public/views/data/lib/export_csv.ts index 269b9dd990173..c0e0153c6053e 100644 --- a/src/plugins/inspector/public/views/data/lib/export_csv.ts +++ b/src/plugins/inspector/public/views/data/lib/export_csv.ts @@ -49,18 +49,18 @@ function buildCsv( valueFormatter?: Function ) { // Build the header row by its names - const header = columns.map(col => escape(col.name, quoteValues)); + const header = columns.map((col) => escape(col.name, quoteValues)); // Convert the array of row objects to an array of row arrays - const orderedFieldNames = columns.map(col => col.field); - const csvRows = rows.map(row => { - return orderedFieldNames.map(field => + const orderedFieldNames = columns.map((col) => col.field); + const csvRows = rows.map((row) => { + return orderedFieldNames.map((field) => escape(valueFormatter ? valueFormatter(row[field]) : row[field], quoteValues) ); }); return ( - [header, ...csvRows].map(row => row.join(csvSeparator)).join(LINE_FEED_CHARACTER) + + [header, ...csvRows].map((row) => row.join(csvSeparator)).join(LINE_FEED_CHARACTER) + LINE_FEED_CHARACTER ); // Add \r\n after last line } diff --git a/src/plugins/inspector/public/views/requests/components/details/req_details_stats.tsx b/src/plugins/inspector/public/views/requests/components/details/req_details_stats.tsx index 767f1c2c5ebcf..90dd6b6c57e68 100644 --- a/src/plugins/inspector/public/views/requests/components/details/req_details_stats.tsx +++ b/src/plugins/inspector/public/views/requests/components/details/req_details_stats.tsx @@ -78,7 +78,7 @@ export class RequestDetailsStats extends Component { const sortedStats = Object.keys(stats) .sort() - .map(id => ({ id, ...stats[id] } as RequestDetailsStatRow)); + .map((id) => ({ id, ...stats[id] } as RequestDetailsStatRow)); return ( diff --git a/src/plugins/kibana_legacy/public/angular/angular_config.tsx b/src/plugins/kibana_legacy/public/angular/angular_config.tsx index 0ff79cca45de1..ed91d1726f1ac 100644 --- a/src/plugins/kibana_legacy/public/angular/angular_config.tsx +++ b/src/plugins/kibana_legacy/public/angular/angular_config.tsx @@ -208,10 +208,10 @@ const capture$httpLoadingCount = (newPlatform: CoreStart) => ( $http: IHttpService ) => { newPlatform.http.addLoadingCountSource( - new Rx.Observable(observer => { + new Rx.Observable((observer) => { const unwatch = $rootScope.$watch(() => { const reqs = $http.pendingRequests || []; - observer.next(reqs.filter(req => !isSystemApiRequest(req)).length); + observer.next(reqs.filter((req) => !isSystemApiRequest(req)).length); }); return unwatch; diff --git a/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js b/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js index b0ccb4dbc2375..a0faf4a6a071c 100644 --- a/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js +++ b/src/plugins/kibana_legacy/public/angular/kbn_top_nav.js @@ -24,7 +24,7 @@ export function createTopNavDirective() { return { restrict: 'E', template: '', - compile: elem => { + compile: (elem) => { const child = document.createElement('kbn-top-nav-helper'); // Copy attributes to the child directive @@ -44,7 +44,7 @@ export function createTopNavDirective() { $scope.$watch( () => { const config = $scope.$eval($attr.config) || []; - return config.map(item => { + return config.map((item) => { // Copy key into id, as it's a reserved react propery. // This is done for Angular directive backward compatibility. // In React only id is recognized. @@ -59,7 +59,7 @@ export function createTopNavDirective() { return item.disableButton; }); }, - newVal => { + (newVal) => { $scope.disabledButtons = newVal; }, true @@ -71,7 +71,7 @@ export function createTopNavDirective() { }; } -export const createTopNavHelper = ({ TopNavMenu }) => reactDirective => { +export const createTopNavHelper = ({ TopNavMenu }) => (reactDirective) => { return reactDirective(TopNavMenu, [ ['config', { watchDepth: 'value' }], ['disabledButtons', { watchDepth: 'reference' }], diff --git a/src/plugins/kibana_legacy/public/angular/promises.js b/src/plugins/kibana_legacy/public/angular/promises.js index 4881f1c1e5533..f5d188e227ca8 100644 --- a/src/plugins/kibana_legacy/public/angular/promises.js +++ b/src/plugins/kibana_legacy/public/angular/promises.js @@ -34,39 +34,39 @@ export function PromiseServiceCreator($q, $timeout) { } Promise.all = Promise.props = $q.all; - Promise.resolve = function(val) { + Promise.resolve = function (val) { const defer = $q.defer(); defer.resolve(val); return defer.promise; }; - Promise.reject = function(reason) { + Promise.reject = function (reason) { const defer = $q.defer(); defer.reject(reason); return defer.promise; }; Promise.cast = $q.when; - Promise.delay = function(ms) { + Promise.delay = function (ms) { return $timeout(_.noop, ms); }; - Promise.method = function(fn) { - return function() { + Promise.method = function (fn) { + return function () { const args = Array.prototype.slice.call(arguments); return Promise.try(fn, args, this); }; }; - Promise.nodeify = function(promise, cb) { - promise.then(function(val) { + Promise.nodeify = function (promise, cb) { + promise.then(function (val) { cb(void 0, val); }, cb); }; - Promise.map = function(arr, fn) { + Promise.map = function (arr, fn) { return Promise.all( - arr.map(function(i, el, list) { + arr.map(function (i, el, list) { return Promise.try(fn, [i, el, list]); }) ); }; - Promise.each = function(arr, fn) { + Promise.each = function (arr, fn) { const queue = arr.slice(0); let i = 0; return (function next() { @@ -74,18 +74,18 @@ export function PromiseServiceCreator($q, $timeout) { return Promise.try(fn, [arr.shift(), i++]).then(next); })(); }; - Promise.is = function(obj) { + Promise.is = function (obj) { // $q doesn't create instances of any constructor, promises are just objects with a then function // https://github.com/angular/angular.js/blob/58f5da86645990ef984353418cd1ed83213b111e/src/ng/q.js#L335 return obj && typeof obj.then === 'function'; }; - Promise.halt = _.once(function() { + Promise.halt = _.once(function () { const promise = new Promise(() => {}); promise.then = _.constant(promise); promise.catch = _.constant(promise); return promise; }); - Promise.try = function(fn, args, ctx) { + Promise.try = function (fn, args, ctx) { if (typeof fn !== 'function') { return Promise.reject(new TypeError('fn must be a function')); } @@ -108,16 +108,16 @@ export function PromiseServiceCreator($q, $timeout) { return Promise.resolve(value); }; - Promise.fromNode = function(takesCbFn) { - return new Promise(function(resolve, reject) { - takesCbFn(function(err, ...results) { + Promise.fromNode = function (takesCbFn) { + return new Promise(function (resolve, reject) { + takesCbFn(function (err, ...results) { if (err) reject(err); else if (results.length > 1) resolve(results); else resolve(results[0]); }); }); }; - Promise.race = function(iterable) { + Promise.race = function (iterable) { return new Promise((resolve, reject) => { for (const i of iterable) { Promise.resolve(i).then(resolve, reject); diff --git a/src/plugins/kibana_legacy/public/angular/watch_multi.js b/src/plugins/kibana_legacy/public/angular/watch_multi.js index 9de0d5f03346e..ed5f0288c0e93 100644 --- a/src/plugins/kibana_legacy/public/angular/watch_multi.js +++ b/src/plugins/kibana_legacy/public/angular/watch_multi.js @@ -20,7 +20,7 @@ import _ from 'lodash'; export function watchMultiDecorator($provide) { - $provide.decorator('$rootScope', function($delegate) { + $provide.decorator('$rootScope', function ($delegate) { /** * Watch multiple expressions with a single callback. Along * with making code simpler it also merges all of the watcher @@ -49,7 +49,7 @@ export function watchMultiDecorator($provide) { * @param {Function} fn - the callback function * @return {Function} - an unwatch function, just like the return value of $watch */ - $delegate.constructor.prototype.$watchMulti = function(expressions, fn) { + $delegate.constructor.prototype.$watchMulti = function (expressions, fn) { if (!Array.isArray(expressions)) { throw new TypeError('expected an array of expressions to watch'); } @@ -65,14 +65,14 @@ export function watchMultiDecorator($provide) { const neededInits = expressions.length; // first, register all of the multi-watchers - const unwatchers = expressions.map(function(expr, i) { + const unwatchers = expressions.map(function (expr, i) { expr = normalizeExpression($scope, expr); if (!expr) return; return expr.fn.call( $scope, expr.get, - function(newVal, oldVal) { + function (newVal, oldVal) { if (newVal === oldVal) { init += 1; } @@ -90,7 +90,7 @@ export function watchMultiDecorator($provide) { let flip = false; unwatchers.push( $scope.$watch( - function() { + function () { if (init < neededInits) return init; if (fire) { @@ -99,19 +99,19 @@ export function watchMultiDecorator($provide) { } return flip; }, - function() { + function () { if (init < neededInits) return false; fn(vals.slice(0), prev.slice(0)); - vals.forEach(function(v, i) { + vals.forEach(function (v, i) { prev[i] = v; }); } ) ); - return function() { - unwatchers.forEach(listener => listener()); + return function () { + unwatchers.forEach((listener) => listener()); }; }; diff --git a/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts b/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts index 58d086e7f24a9..a6aee351fde52 100644 --- a/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts +++ b/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts @@ -33,7 +33,7 @@ export const navigateToLegacyKibanaUrl = ( // try to find an existing redirect for the target path if possible // this avoids having to load the legacy app just to get redirected to a core application again afterwards - const relevantForward = forwards.find(forward => path.startsWith(`/${forward.legacyAppId}`)); + const relevantForward = forwards.find((forward) => path.startsWith(`/${forward.legacyAppId}`)); if (relevantForward) { targetAppPath = relevantForward.rewritePath(path); targetAppId = relevantForward.newAppId; diff --git a/src/plugins/kibana_legacy/public/navigate_to_default_app.ts b/src/plugins/kibana_legacy/public/navigate_to_default_app.ts index 20e54b25d07c2..80b8343d3b229 100644 --- a/src/plugins/kibana_legacy/public/navigate_to_default_app.ts +++ b/src/plugins/kibana_legacy/public/navigate_to_default_app.ts @@ -34,7 +34,7 @@ export function navigateToDefaultApp( // try to find an existing redirect for the target path if possible // this avoids having to load the legacy app just to get redirected to a core application again afterwards - const relevantForward = forwards.find(forward => defaultAppId.startsWith(forward.legacyAppId)); + const relevantForward = forwards.find((forward) => defaultAppId.startsWith(forward.legacyAppId)); if (relevantForward) { targetAppPath = relevantForward.rewritePath(`/${defaultAppId}`); targetAppId = relevantForward.newAppId; diff --git a/src/plugins/kibana_legacy/public/notify/lib/format_msg.ts b/src/plugins/kibana_legacy/public/notify/lib/format_msg.ts index 8179c8f368b27..afc1b9cbf1dd6 100644 --- a/src/plugins/kibana_legacy/public/notify/lib/format_msg.ts +++ b/src/plugins/kibana_legacy/public/notify/lib/format_msg.ts @@ -68,7 +68,7 @@ export function formatMsg(err: Record | string, source: string = '' return message; } -formatMsg.describeError = function(err: Record) { +formatMsg.describeError = function (err: Record) { if (!err) return undefined; if (err.shortMessage) return err.shortMessage; if (err.body && err.body.message) return err.body.message; diff --git a/src/plugins/kibana_legacy/public/notify/toasts/toast_notifications.ts b/src/plugins/kibana_legacy/public/notify/toasts/toast_notifications.ts index 649e50c2d1d6f..48511102481a0 100644 --- a/src/plugins/kibana_legacy/public/notify/toasts/toast_notifications.ts +++ b/src/plugins/kibana_legacy/public/notify/toasts/toast_notifications.ts @@ -25,7 +25,7 @@ export class ToastNotifications { private onChangeCallback?: () => void; constructor(private readonly toasts: NotificationsSetup['toasts']) { - toasts.get$().subscribe(list => { + toasts.get$().subscribe((list) => { this.list = list; if (this.onChangeCallback) { diff --git a/src/plugins/kibana_legacy/public/paginate/paginate.js b/src/plugins/kibana_legacy/public/paginate/paginate.js index f7e623cdabd86..ea93a969d08c7 100644 --- a/src/plugins/kibana_legacy/public/paginate/paginate.js +++ b/src/plugins/kibana_legacy/public/paginate/paginate.js @@ -26,13 +26,13 @@ export function PaginateDirectiveProvider($parse, $compile) { restrict: 'E', scope: true, link: { - pre: function($scope, $el, attrs) { + pre: function ($scope, $el, attrs) { if (_.isUndefined(attrs.bottomControls)) attrs.bottomControls = true; if ($el.find('paginate-controls.paginate-bottom').length === 0 && attrs.bottomControls) { $el.append($compile('')($scope)); } }, - post: function($scope, $el, attrs) { + post: function ($scope, $el, attrs) { if (_.isUndefined(attrs.topControls)) attrs.topControls = false; if ($el.find('paginate-controls.paginate-top').length === 0 && attrs.topControls) { $el.prepend($compile('')($scope)); @@ -57,7 +57,7 @@ export function PaginateDirectiveProvider($parse, $compile) { }, }, controllerAs: 'paginate', - controller: function($scope, $document) { + controller: function ($scope, $document) { const self = this; const ALL = 0; const allSizeTitle = i18n.translate('kibana_legacy.paginate.size.allDropDownOptionLabel', { @@ -72,10 +72,10 @@ export function PaginateDirectiveProvider($parse, $compile) { ]; // setup the watchers, called in the post-link function - self.init = function() { + self.init = function () { self.perPage = _.parseInt(self.perPage) || $scope[self.perPageProp]; - $scope.$watchMulti(['paginate.perPage', self.perPageProp, self.otherWidthGetter], function( + $scope.$watchMulti(['paginate.perPage', self.perPageProp, self.otherWidthGetter], function ( vals, oldVals ) { @@ -101,13 +101,13 @@ export function PaginateDirectiveProvider($parse, $compile) { }); $scope.$watch('page', self.changePage); - $scope.$watchCollection(self.getList, function(list) { + $scope.$watchCollection(self.getList, function (list) { $scope.list = list; self.renderList(); }); }; - self.goToPage = function(number) { + self.goToPage = function (number) { if (number) { if (number.hasOwnProperty('number')) number = number.number; $scope.page = $scope.pages[number - 1] || $scope.pages[0]; @@ -118,14 +118,14 @@ export function PaginateDirectiveProvider($parse, $compile) { $document.scrollTop(0); }; - self.renderList = function() { + self.renderList = function () { $scope.pages = []; if (!$scope.list) return; const perPage = _.parseInt(self.perPage); const count = perPage ? Math.ceil($scope.list.length / perPage) : 1; - _.times(count, function(i) { + _.times(count, function (i) { let page; if (perPage) { @@ -162,7 +162,7 @@ export function PaginateDirectiveProvider($parse, $compile) { } }; - self.changePage = function(page) { + self.changePage = function (page) { if (!page) { $scope.otherPages = null; return; diff --git a/src/plugins/kibana_legacy/public/plugin.ts b/src/plugins/kibana_legacy/public/plugin.ts index 76af344d1734a..c1a93f180db6f 100644 --- a/src/plugins/kibana_legacy/public/plugin.ts +++ b/src/plugins/kibana_legacy/public/plugin.ts @@ -161,7 +161,7 @@ export class KibanaLegacyPlugin { this.forwardDefinitions.push({ legacyAppId, newAppId, - rewritePath: rewritePath || (path => `#${path.replace(`/${legacyAppId}`, '') || '/'}`), + rewritePath: rewritePath || ((path) => `#${path.replace(`/${legacyAppId}`, '') || '/'}`), }); }, @@ -180,7 +180,7 @@ export class KibanaLegacyPlugin { } public start({ application, http: { basePath }, uiSettings }: CoreStart) { - this.currentAppIdSubscription = application.currentAppId$.subscribe(currentAppId => { + this.currentAppIdSubscription = application.currentAppId$.subscribe((currentAppId) => { this.currentAppId = currentAppId; }); injectHeaderStyle(uiSettings); diff --git a/src/plugins/kibana_legacy/public/utils/kbn_accessible_click.js b/src/plugins/kibana_legacy/public/utils/kbn_accessible_click.js index 26f41c9abac2b..ba1363ef06285 100644 --- a/src/plugins/kibana_legacy/public/utils/kbn_accessible_click.js +++ b/src/plugins/kibana_legacy/public/utils/kbn_accessible_click.js @@ -21,8 +21,8 @@ import { accessibleClickKeys, keyCodes } from '@elastic/eui'; export function KbnAccessibleClickProvider() { return { restrict: 'A', - controller: $element => { - $element.on('keydown', e => { + controller: ($element) => { + $element.on('keydown', (e) => { // Prevent a scroll from occurring if the user has hit space. if (e.keyCode === keyCodes.SPACE) { e.preventDefault(); @@ -58,7 +58,7 @@ export function KbnAccessibleClickProvider() { element.attr('role', 'button'); } - element.on('keyup', e => { + element.on('keyup', (e) => { // Support keyboard accessibility by emulating mouse click on ENTER or SPACE keypress. if (accessibleClickKeys[e.keyCode]) { // Delegate to the click handler on the element (assumed to be ng-click). diff --git a/src/plugins/kibana_legacy/public/utils/private.js b/src/plugins/kibana_legacy/public/utils/private.js index 18fdcb8c89215..8119a73215796 100644 --- a/src/plugins/kibana_legacy/public/utils/private.js +++ b/src/plugins/kibana_legacy/public/utils/private.js @@ -98,13 +98,7 @@ import _ from 'lodash'; const nextId = _.partial(_.uniqueId, 'privateProvider#'); function name(fn) { - return ( - fn.name || - fn - .toString() - .split('\n') - .shift() - ); + return fn.name || fn.toString().split('\n').shift(); } export function PrivateProvider() { @@ -124,12 +118,12 @@ export function PrivateProvider() { else return (fn.$$id = nextId()); } - provider.stub = function(fn, instance) { + provider.stub = function (fn, instance) { cache[identify(fn)] = instance; return instance; }; - provider.swap = function(fn, prov) { + provider.swap = function (fn, prov) { const id = identify(fn); swaps[id] = prov; }; @@ -139,7 +133,7 @@ export function PrivateProvider() { function PrivateFactory($injector) { // prevent circular deps by tracking where we came from const privPath = []; - const pathToString = function() { + const pathToString = function () { return privPath.map(name).join(' -> '); }; diff --git a/src/plugins/kibana_legacy/public/utils/register_listen_event_listener.js b/src/plugins/kibana_legacy/public/utils/register_listen_event_listener.js index 6cc9a5766d3fe..3aed59a87d83b 100644 --- a/src/plugins/kibana_legacy/public/utils/register_listen_event_listener.js +++ b/src/plugins/kibana_legacy/public/utils/register_listen_event_listener.js @@ -26,9 +26,9 @@ export function registerListenEventListener($rootScope) { * @param {Function} handler - the event handler * @return {undefined} */ - $rootScope.constructor.prototype.$listen = function(emitter, eventName, handler) { + $rootScope.constructor.prototype.$listen = function (emitter, eventName, handler) { emitter.on(eventName, handler); - this.$on('$destroy', function() { + this.$on('$destroy', function () { emitter.off(eventName, handler); }); }; diff --git a/src/plugins/kibana_react/public/adapters/ui_to_react_component.ts b/src/plugins/kibana_react/public/adapters/ui_to_react_component.ts index ee99ea3672672..f092c723d7646 100644 --- a/src/plugins/kibana_react/public/adapters/ui_to_react_component.ts +++ b/src/plugins/kibana_react/public/adapters/ui_to_react_component.ts @@ -26,7 +26,7 @@ import { UiComponent, UiComponentInstance } from '../../../kibana_utils/public'; export const uiToReactComponent = ( Comp: UiComponent, as: string = 'div' -): FC => props => { +): FC => (props) => { const ref = useRef(); const comp = useMemo>(() => Comp(), [Comp]); diff --git a/src/plugins/kibana_react/public/code_editor/index.tsx b/src/plugins/kibana_react/public/code_editor/index.tsx index 3c15feff3f2ab..0ef83811d96d3 100644 --- a/src/plugins/kibana_react/public/code_editor/index.tsx +++ b/src/plugins/kibana_react/public/code_editor/index.tsx @@ -20,7 +20,7 @@ import React from 'react'; import { useUiSetting } from '../ui_settings'; import { CodeEditor as BaseEditor, Props } from './code_editor'; -export const CodeEditor: React.FunctionComponent = props => { +export const CodeEditor: React.FunctionComponent = (props) => { const darkMode = useUiSetting('theme:darkMode'); return ; diff --git a/src/plugins/kibana_react/public/context/context.tsx b/src/plugins/kibana_react/public/context/context.tsx index cbf2ad07b463e..9fb0440bb587c 100644 --- a/src/plugins/kibana_react/public/context/context.tsx +++ b/src/plugins/kibana_react/public/context/context.tsx @@ -32,8 +32,9 @@ const defaultContextValue = { export const context = createContext>(defaultContextValue); -export const useKibana = (): KibanaReactContextValue => +export const useKibana = (): KibanaReactContextValue< + KibanaServices & Extra +> => useContext( (context as unknown) as React.Context> ); diff --git a/src/plugins/kibana_react/public/field_icon/field_icon.test.tsx b/src/plugins/kibana_react/public/field_icon/field_icon.test.tsx index 51ff5f603ea37..6a79f6b313d41 100644 --- a/src/plugins/kibana_react/public/field_icon/field_icon.test.tsx +++ b/src/plugins/kibana_react/public/field_icon/field_icon.test.tsx @@ -23,7 +23,7 @@ import { FieldIcon, typeToEuiIconMap } from './field_icon'; const availableTypes = Object.keys(typeToEuiIconMap); describe('FieldIcon renders known field types', () => { - availableTypes.forEach(type => { + availableTypes.forEach((type) => { test(`${type} is rendered`, () => { const component = shallow(); expect(component).toMatchSnapshot(); diff --git a/src/plugins/kibana_react/public/markdown/markdown.test.tsx b/src/plugins/kibana_react/public/markdown/markdown.test.tsx index 0036c4f6377be..5846b7a2d0dba 100644 --- a/src/plugins/kibana_react/public/markdown/markdown.test.tsx +++ b/src/plugins/kibana_react/public/markdown/markdown.test.tsx @@ -38,12 +38,9 @@ test('should render links with parentheses correctly', () => { const component = shallow( ); - expect( - component - .render() - .find('a') - .prop('href') - ).toBe('https://example.com/foo/bar?group=(()filters:!t)'); + expect(component.render().find('a').prop('href')).toBe( + 'https://example.com/foo/bar?group=(()filters:!t)' + ); }); test('should add `noreferrer` and `nooopener` to unknown links in new tabs', () => { @@ -53,24 +50,14 @@ test('should add `noreferrer` and `nooopener` to unknown links in new tabs', () markdown="[link](https://example.com/foo/bar?group=(()filters:!t))" /> ); - expect( - component - .render() - .find('a') - .prop('rel') - ).toBe('noopener noreferrer'); + expect(component.render().find('a').prop('rel')).toBe('noopener noreferrer'); }); test('should only add `nooopener` to known links in new tabs', () => { const component = shallow( ); - expect( - component - .render() - .find('a') - .prop('rel') - ).toBe('noopener'); + expect(component.render().find('a').prop('rel')).toBe('noopener'); }); describe('props', () => { @@ -95,19 +82,9 @@ describe('props', () => { test('should update markdown when openLinksInNewTab prop change', () => { const component = shallow(); - expect( - component - .render() - .find('a') - .prop('target') - ).not.toBe('_blank'); + expect(component.render().find('a').prop('target')).not.toBe('_blank'); component.setProps({ openLinksInNewTab: true }); - expect( - component - .render() - .find('a') - .prop('target') - ).toBe('_blank'); + expect(component.render().find('a').prop('target')).toBe('_blank'); }); test('should update markdown when whiteListedRules prop change', () => { diff --git a/src/plugins/kibana_react/public/markdown/markdown.tsx b/src/plugins/kibana_react/public/markdown/markdown.tsx index a0c2cdad78c66..15d1c4931e60b 100644 --- a/src/plugins/kibana_react/public/markdown/markdown.tsx +++ b/src/plugins/kibana_react/public/markdown/markdown.tsx @@ -53,10 +53,10 @@ export const markdownFactory = memoize( // https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer const originalLinkRender = markdownIt.renderer.rules.link_open || - function(tokens, idx, options, env, self) { + function (tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; - markdownIt.renderer.rules.link_open = function(tokens, idx, options, env, self) { + markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) { const href = tokens[idx].attrGet('href'); const target = '_blank'; const rel = getSecureRelForTarget({ href: href === null ? undefined : href, target }); diff --git a/src/plugins/kibana_react/public/notifications/create_notifications.tsx b/src/plugins/kibana_react/public/notifications/create_notifications.tsx index 774f74863ee6f..826435ec5b587 100644 --- a/src/plugins/kibana_react/public/notifications/create_notifications.tsx +++ b/src/plugins/kibana_react/public/notifications/create_notifications.tsx @@ -44,13 +44,13 @@ export const createNotifications = (services: KibanaServices): KibanaReactNotifi }); }; - const success: KibanaReactNotifications['toasts']['success'] = input => + const success: KibanaReactNotifications['toasts']['success'] = (input) => show({ color: 'success', iconType: 'check', ...input }); - const warning: KibanaReactNotifications['toasts']['warning'] = input => + const warning: KibanaReactNotifications['toasts']['warning'] = (input) => show({ color: 'warning', iconType: 'help', ...input }); - const danger: KibanaReactNotifications['toasts']['danger'] = input => + const danger: KibanaReactNotifications['toasts']['danger'] = (input) => show({ color: 'danger', iconType: 'alert', ...input }); const notifications: KibanaReactNotifications = { diff --git a/src/plugins/kibana_react/public/split_panel/containers/panel_container.tsx b/src/plugins/kibana_react/public/split_panel/containers/panel_container.tsx index edd6a4145a1cc..45fe20095fd83 100644 --- a/src/plugins/kibana_react/public/split_panel/containers/panel_container.tsx +++ b/src/plugins/kibana_react/public/split_panel/containers/panel_container.tsx @@ -121,7 +121,7 @@ export function PanelsContainer({ className={className} ref={containerRef} style={{ display: 'flex', height: '100%', width: '100%' }} - onMouseMove={event => { + onMouseMove={(event) => { if (state.isDragging) { const { clientX: x } = event; const { current: registry } = registryRef; diff --git a/src/plugins/kibana_react/public/split_panel/split_panel.test.tsx b/src/plugins/kibana_react/public/split_panel/split_panel.test.tsx index 02153d1a1d3cd..eb0d0096a1c9f 100644 --- a/src/plugins/kibana_react/public/split_panel/split_panel.test.tsx +++ b/src/plugins/kibana_react/public/split_panel/split_panel.test.tsx @@ -44,10 +44,7 @@ describe('Split panel', () => { // the DOMElement width so that we have a lightweight test for width calculation // logic. const div = mount(
); - const proto = (div - .find('div') - .first() - .getDOMNode() as any).__proto__; + const proto = (div.find('div').first().getDOMNode() as any).__proto__; const originalGetBoundingClientRect = proto.getBoundingClientRect; proto.getBoundingClientRect = spy(() => { diff --git a/src/plugins/kibana_react/public/table_list_view/table_list_view.tsx b/src/plugins/kibana_react/public/table_list_view/table_list_view.tsx index 58003a7e9e841..22865f98c2349 100644 --- a/src/plugins/kibana_react/public/table_list_view/table_list_view.tsx +++ b/src/plugins/kibana_react/public/table_list_view/table_list_view.tsx @@ -166,7 +166,7 @@ class TableListView extends React.Component itemsById[id])); + await this.props.deleteItems(this.state.selectedIds.map((id) => itemsById[id])); } catch (error) { this.props.toastNotifications.addDanger({ title: toMountPoint( @@ -363,7 +363,7 @@ class TableListView extends React.Component { this.setState({ selectedIds: obj - .map(item => item.id) + .map((item) => item.id) .filter((id: undefined | string): id is string => Boolean(id)), }); }, diff --git a/src/plugins/kibana_usage_collection/server/collectors/application_usage/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/application_usage/index.test.ts index 5a8fa71363ba7..006b0854255ed 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/application_usage/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/application_usage/index.test.ts @@ -35,7 +35,7 @@ describe('telemetry_application_usage', () => { let collector: CollectorOptions; const usageCollectionMock: jest.Mocked = { - makeUsageCollector: jest.fn().mockImplementation(config => (collector = config)), + makeUsageCollector: jest.fn().mockImplementation((config) => (collector = config)), registerCollector: jest.fn(), } as any; @@ -77,7 +77,7 @@ describe('telemetry_application_usage', () => { test('paging in findAll works', async () => { const savedObjectClient = savedObjectsRepositoryMock.create(); let total = 201; - savedObjectClient.find.mockImplementation(async opts => { + savedObjectClient.find.mockImplementation(async (opts) => { if (opts.type === SAVED_OBJECTS_TOTAL_TYPE) { return { saved_objects: [ diff --git a/src/plugins/kibana_usage_collection/server/collectors/find_all.test.ts b/src/plugins/kibana_usage_collection/server/collectors/find_all.test.ts index a62c74c0c0838..d917cd2454e81 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/find_all.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/find_all.test.ts @@ -39,7 +39,7 @@ describe('telemetry_application_usage', () => { const savedObjectClient = savedObjectsRepositoryMock.create(); let total = 201; const doc = { id: 'test-id', attributes: { test: 1 } }; - savedObjectClient.find.mockImplementation(async opts => { + savedObjectClient.find.mockImplementation(async (opts) => { if ((opts.page || 1) > 2) { return { saved_objects: [], total } as any; } diff --git a/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts index 91ede686ded3d..ff0a537caf863 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts @@ -28,7 +28,7 @@ describe('telemetry_kibana', () => { let collector: CollectorOptions; const usageCollectionMock: jest.Mocked = { - makeUsageCollector: jest.fn().mockImplementation(config => (collector = config)), + makeUsageCollector: jest.fn().mockImplementation((config) => (collector = config)), registerCollector: jest.fn(), } as any; diff --git a/src/plugins/kibana_usage_collection/server/collectors/kibana/kibana_usage_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/kibana/kibana_usage_collector.ts index ccf6f7b1033c9..d0da6fcc523cc 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/kibana/kibana_usage_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/kibana/kibana_usage_collector.ts @@ -46,7 +46,7 @@ export function getKibanaUsageCollector( * 1. Make this data part of the "kibana_stats" type * 2. Organize the payload in the usage namespace of the data payload (usage.index, etc) */ - formatForBulkUpload: result => { + formatForBulkUpload: (result) => { return { type: KIBANA_STATS_TYPE, payload: { diff --git a/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts index a14edb55861be..2f6b564aacebb 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts @@ -28,7 +28,7 @@ describe('telemetry_application_usage_collector', () => { let collector: CollectorOptions; const usageCollectionMock: jest.Mocked = { - makeUsageCollector: jest.fn().mockImplementation(config => (collector = config)), + makeUsageCollector: jest.fn().mockImplementation((config) => (collector = config)), registerCollector: jest.fn(), } as any; diff --git a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts index 92e0e40776eb8..82e3496f19134 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts @@ -29,7 +29,7 @@ describe('telemetry_ops_stats', () => { let collector: CollectorOptions; const usageCollectionMock: jest.Mocked = { - makeStatsCollector: jest.fn().mockImplementation(config => (collector = config)), + makeStatsCollector: jest.fn().mockImplementation((config) => (collector = config)), registerCollector: jest.fn(), } as any; diff --git a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/ops_stats_collector.ts b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/ops_stats_collector.ts index 4967e20006ddd..df9d6eb146eab 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/ops_stats_collector.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/ops_stats_collector.ts @@ -40,7 +40,7 @@ export function getOpsStatsCollector( metrics$: Observable ) { let lastMetrics: OpsStatsMetrics | null = null; - metrics$.subscribe(_metrics => { + metrics$.subscribe((_metrics) => { const metrics = cloneDeep(_metrics); // Ensure we only include the same data that Metricbeat collection would get delete metrics.process.pid; diff --git a/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts index d6667a6384a1f..7b4ad08e44647 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts @@ -28,7 +28,7 @@ describe('telemetry_ui_metric', () => { let collector: CollectorOptions; const usageCollectionMock: jest.Mocked = { - makeUsageCollector: jest.fn().mockImplementation(config => (collector = config)), + makeUsageCollector: jest.fn().mockImplementation((config) => (collector = config)), registerCollector: jest.fn(), } as any; diff --git a/src/plugins/kibana_usage_collection/server/index.test.ts b/src/plugins/kibana_usage_collection/server/index.test.ts index 0060b6caa1815..4b24dd222a5e7 100644 --- a/src/plugins/kibana_usage_collection/server/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/index.test.ts @@ -32,11 +32,11 @@ describe('kibana_usage_collection', () => { const usageCollectors: Array<{ isReady: () => boolean }> = []; const usageCollection: jest.Mocked = { - makeStatsCollector: jest.fn().mockImplementation(opts => { + makeStatsCollector: jest.fn().mockImplementation((opts) => { usageCollectors.push(opts); return opts; }), - makeUsageCollector: jest.fn().mockImplementation(opts => { + makeUsageCollector: jest.fn().mockImplementation((opts) => { usageCollectors.push(opts); return opts; }), diff --git a/src/plugins/kibana_usage_collection/server/plugin.ts b/src/plugins/kibana_usage_collection/server/plugin.ts index 5e76083469d95..64d5367100236 100644 --- a/src/plugins/kibana_usage_collection/server/plugin.ts +++ b/src/plugins/kibana_usage_collection/server/plugin.ts @@ -58,7 +58,9 @@ export class KibanaUsageCollectionPlugin implements Plugin { { savedObjects, metrics, getStartServices }: CoreSetup, { usageCollection }: KibanaUsageCollectionPluginsDepsSetup ) { - this.registerUsageCollectors(usageCollection, metrics, opts => savedObjects.registerType(opts)); + this.registerUsageCollectors(usageCollection, metrics, (opts) => + savedObjects.registerType(opts) + ); } public start(core: CoreStart) { diff --git a/src/plugins/kibana_utils/common/calculate_object_hash.ts b/src/plugins/kibana_utils/common/calculate_object_hash.ts index 26062636d624c..0bbc6645d6336 100644 --- a/src/plugins/kibana_utils/common/calculate_object_hash.ts +++ b/src/plugins/kibana_utils/common/calculate_object_hash.ts @@ -48,9 +48,7 @@ function foldObject(hash: number, o: any, seen: any[]) { return foldValue(h, o[key], key, seen); } - return Object.keys(o) - .sort() - .reduce(foldKey, hash); + return Object.keys(o).sort().reduce(foldKey, hash); } function foldValue(input: number, value: any, key: string, seen: any[]) { diff --git a/src/plugins/kibana_utils/common/create_getter_setter.ts b/src/plugins/kibana_utils/common/create_getter_setter.ts index be2fd48ee6e7b..a0a2f15b635a6 100644 --- a/src/plugins/kibana_utils/common/create_getter_setter.ts +++ b/src/plugins/kibana_utils/common/create_getter_setter.ts @@ -28,7 +28,7 @@ export const createGetterSetter = (name: string): [Get, Set return value; }; - const set: Set = newValue => { + const set: Set = (newValue) => { value = newValue; }; diff --git a/src/plugins/kibana_utils/common/defer.test.ts b/src/plugins/kibana_utils/common/defer.test.ts index e05727847f247..0bd6922a235f1 100644 --- a/src/plugins/kibana_utils/common/defer.test.ts +++ b/src/plugins/kibana_utils/common/defer.test.ts @@ -19,7 +19,7 @@ import { Defer } from './defer'; -const tick = () => new Promise(resolve => setTimeout(resolve, 1)); +const tick = () => new Promise((resolve) => setTimeout(resolve, 1)); describe('new Defer()', () => { test('has .promise Promise object', () => { diff --git a/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.test.ts b/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.test.ts index 24f8f13f21478..4a612785eafe3 100644 --- a/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.test.ts +++ b/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.test.ts @@ -41,7 +41,7 @@ describe('distinctUntilChangedWithInitialValue', () => { const result = subject .pipe( distinctUntilChangedWithInitialValue( - new Promise(resolve => { + new Promise((resolve) => { resolve(1); setTimeout(() => { subject.next(2); diff --git a/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.ts b/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.ts index 6af9cc1e8ac3a..41d9b7b0d1f56 100644 --- a/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.ts +++ b/src/plugins/kibana_utils/common/distinct_until_changed_with_initial_value.ts @@ -24,7 +24,7 @@ export function distinctUntilChangedWithInitialValue( initialValue: T | Promise, compare?: (x: T, y: T) => boolean ): MonoTypeOperatorFunction { - return input$ => + return (input$) => scheduled( [isPromise(initialValue) ? from(initialValue) : [initialValue], input$], queueScheduler diff --git a/src/plugins/kibana_utils/common/of.test.ts b/src/plugins/kibana_utils/common/of.test.ts index 6c3f0ec1592bd..9ff8997f637e5 100644 --- a/src/plugins/kibana_utils/common/of.test.ts +++ b/src/plugins/kibana_utils/common/of.test.ts @@ -21,7 +21,7 @@ import { of } from './of'; describe('of()', () => { describe('when promise resolves', () => { - const promise = new Promise(resolve => resolve()).then(() => 123); + const promise = new Promise((resolve) => resolve()).then(() => 123); test('first member of 3-tuple is the promise value', async () => { const [result] = await of(promise); @@ -40,7 +40,7 @@ describe('of()', () => { }); describe('when promise rejects', () => { - const promise = new Promise(resolve => resolve()).then(() => { + const promise = new Promise((resolve) => resolve()).then(() => { // eslint-disable-next-line no-throw-literal throw 123; }); diff --git a/src/plugins/kibana_utils/common/state_containers/create_state_container.test.ts b/src/plugins/kibana_utils/common/state_containers/create_state_container.test.ts index d4877acaa5ca0..24ce343f73c9d 100644 --- a/src/plugins/kibana_utils/common/state_containers/create_state_container.test.ts +++ b/src/plugins/kibana_utils/common/state_containers/create_state_container.test.ts @@ -220,7 +220,7 @@ test('throws when state is modified inline', () => { test('throws when state is modified inline in subscription', () => { const container = createStateContainer({ a: 'b' }, { set: () => (newState: any) => newState }); - container.subscribe(value => { + container.subscribe((value) => { expect(() => { (value.a as any) = 'd'; }).toThrowErrorMatchingInlineSnapshot( diff --git a/src/plugins/kibana_utils/common/state_containers/create_state_container.ts b/src/plugins/kibana_utils/common/state_containers/create_state_container.ts index c6e1f53145312..69e204a642f93 100644 --- a/src/plugins/kibana_utils/common/state_containers/create_state_container.ts +++ b/src/plugins/kibana_utils/common/state_containers/create_state_container.ts @@ -108,8 +108,8 @@ export function createStateContainer< ]; return pureTransition ? freeze(pureTransition(state)(...action.args)) : state; }, - replaceReducer: nextReducer => (container.reducer = nextReducer), - dispatch: action => data$.next(container.reducer(get(), action)), + replaceReducer: (nextReducer) => (container.reducer = nextReducer), + dispatch: (action) => data$.next(container.reducer(get(), action)), transitions: Object.keys(pureTransitions).reduce>( (acc, type) => ({ ...acc, [type]: (...args: any) => container.dispatch({ type, args }) }), {} as PureTransitionsToTransitions @@ -121,7 +121,7 @@ export function createStateContainer< }), {} as PureSelectorsToSelectors ), - addMiddleware: middleware => + addMiddleware: (middleware) => (container.dispatch = middleware(container as any)(container.dispatch)), subscribe: (listener: (state: State) => void) => { const subscription = state$.subscribe(listener); diff --git a/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.test.tsx b/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.test.tsx index 0f25f65c30ade..81101f3180738 100644 --- a/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.test.tsx +++ b/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.test.tsx @@ -99,7 +99,7 @@ test('context receives stateContainer', () => { ReactDOM.render( /* eslint-disable no-shadow */ - {stateContainer => stateContainer.get().foo} + {(stateContainer) => stateContainer.get().foo} , /* eslint-enable no-shadow */ container @@ -305,21 +305,21 @@ describe('hooks', () => { container ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); act(() => { stateContainer.set({ a: 'c', foo: 'bar' }); }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); act(() => { stateContainer.set({ a: 'd', foo: 'bar 2' }); }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(2); }); @@ -341,21 +341,21 @@ describe('hooks', () => { container ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); act(() => { stateContainer.set({ foo: { bar: 'baz' } }); }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); act(() => { stateContainer.set({ foo: { bar: 'qux' } }); }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(2); }); @@ -383,14 +383,14 @@ describe('hooks', () => { container ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); act(() => { stateContainer.set({ foo: { bar: 'baz' } }); }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(cnt).toBe(1); }); diff --git a/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.ts b/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.ts index 90823359359a1..8536f97e00ed0 100644 --- a/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.ts +++ b/src/plugins/kibana_utils/common/state_containers/create_state_container_react_helpers.ts @@ -88,7 +88,7 @@ export const createStateContainerReactHelpers = (container, selector, comparator); }; - const connect: Connect> = mapStateToProp => component => props => + const connect: Connect> = (mapStateToProp) => (component) => (props) => h(component, { ...useSelector(mapStateToProp), ...props } as any); return { diff --git a/src/plugins/kibana_utils/demos/state_containers/todomvc.ts b/src/plugins/kibana_utils/demos/state_containers/todomvc.ts index 0a07d721479b3..e3d00334bdf59 100644 --- a/src/plugins/kibana_utils/demos/state_containers/todomvc.ts +++ b/src/plugins/kibana_utils/demos/state_containers/todomvc.ts @@ -54,21 +54,23 @@ export interface TodosSelectors { } export const pureTransitions: TodoActions = { - add: state => todo => ({ todos: [...state.todos, todo] }), - edit: state => todo => ({ - todos: state.todos.map(item => (item.id === todo.id ? { ...item, ...todo } : item)), + add: (state) => (todo) => ({ todos: [...state.todos, todo] }), + edit: (state) => (todo) => ({ + todos: state.todos.map((item) => (item.id === todo.id ? { ...item, ...todo } : item)), }), - delete: state => id => ({ todos: state.todos.filter(item => item.id !== id) }), - complete: state => id => ({ - todos: state.todos.map(item => (item.id === id ? { ...item, completed: true } : item)), + delete: (state) => (id) => ({ todos: state.todos.filter((item) => item.id !== id) }), + complete: (state) => (id) => ({ + todos: state.todos.map((item) => (item.id === id ? { ...item, completed: true } : item)), }), - completeAll: state => () => ({ todos: state.todos.map(item => ({ ...item, completed: true })) }), - clearCompleted: state => () => ({ todos: state.todos.filter(({ completed }) => !completed) }), + completeAll: (state) => () => ({ + todos: state.todos.map((item) => ({ ...item, completed: true })), + }), + clearCompleted: (state) => () => ({ todos: state.todos.filter(({ completed }) => !completed) }), }; export const pureSelectors: TodosSelectors = { - todos: state => () => state.todos, - todo: state => id => state.todos.find(todo => todo.id === id) ?? null, + todos: (state) => () => state.todos, + todo: (state) => (id) => state.todos.find((todo) => todo.id === id) ?? null, }; const container = createStateContainer( diff --git a/src/plugins/kibana_utils/demos/state_sync/url.ts b/src/plugins/kibana_utils/demos/state_sync/url.ts index 80c016950d224..e8e63eefe866c 100644 --- a/src/plugins/kibana_utils/demos/state_sync/url.ts +++ b/src/plugins/kibana_utils/demos/state_sync/url.ts @@ -25,7 +25,7 @@ import { INullableBaseStateContainer, } from '../../public/state_sync'; -const tick = () => new Promise(resolve => setTimeout(resolve)); +const tick = () => new Promise((resolve) => setTimeout(resolve)); const stateContainer = createStateContainer(defaultState, pureTransitions); const { start, stop } = syncState({ diff --git a/src/plugins/kibana_utils/public/core/create_start_service_getter.test.ts b/src/plugins/kibana_utils/public/core/create_start_service_getter.test.ts index 9d9b21269e102..1553257a04adb 100644 --- a/src/plugins/kibana_utils/public/core/create_start_service_getter.test.ts +++ b/src/plugins/kibana_utils/public/core/create_start_service_getter.test.ts @@ -27,7 +27,7 @@ describe('createStartServicesGetter', () => { const accessor: StartServicesAccessor = async () => await future.promise; const start = createStartServicesGetter(accessor); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(() => start()).toThrowErrorMatchingInlineSnapshot( `"Trying to access start services before start."` @@ -42,11 +42,11 @@ describe('createStartServicesGetter', () => { const accessor: StartServicesAccessor = async () => await future.promise; const start = createStartServicesGetter(accessor); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(() => start()).toThrow(); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); future.resolve([core, plugins, self]); await future.promise; @@ -65,7 +65,7 @@ describe('createStartServicesGetter', () => { const accessor: StartServicesAccessor = async () => await future.promise; const start = createStartServicesGetter(accessor); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); future.resolve([core, plugins, self]); await future.promise; diff --git a/src/plugins/kibana_utils/public/core/create_start_service_getter.ts b/src/plugins/kibana_utils/public/core/create_start_service_getter.ts index 5e385eb5ed473..14e2588a0a9cf 100644 --- a/src/plugins/kibana_utils/public/core/create_start_service_getter.ts +++ b/src/plugins/kibana_utils/public/core/create_start_service_getter.ts @@ -85,7 +85,7 @@ export const createStartServicesGetter = ( self, }; }, - error => { + (error) => { // eslint-disable-next-line no-console console.error('Could not access start services.', error); } diff --git a/src/plugins/kibana_utils/public/errors/errors.test.ts b/src/plugins/kibana_utils/public/errors/errors.test.ts index fa769e71c250e..0c360832d8e5e 100644 --- a/src/plugins/kibana_utils/public/errors/errors.test.ts +++ b/src/plugins/kibana_utils/public/errors/errors.test.ts @@ -23,7 +23,7 @@ import { DuplicateField, SavedObjectNotFound, KbnError } from './errors'; describe('errors', () => { const errors = [new DuplicateField('dupfield'), new SavedObjectNotFound('dashboard', '123')]; - errors.forEach(error => { + errors.forEach((error) => { const className = error.constructor.name; it(`${className} has a message`, () => { expect(error.message).to.not.be.empty(); diff --git a/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.test.ts b/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.test.ts index 9f7523866fdc1..3ea9a823b9de1 100644 --- a/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.test.ts +++ b/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.test.ts @@ -22,19 +22,19 @@ import { fieldWildcardFilter, makeRegEx } from './field_wildcard'; describe('fieldWildcard', () => { const metaFields = ['_id', '_type', '_source']; - describe('makeRegEx', function() { - it('matches * in any position', function() { + describe('makeRegEx', function () { + it('matches * in any position', function () { expect('aaaaaabbbbbbbcccccc').toMatch(makeRegEx('*a*b*c*')); expect('a1234').toMatch(makeRegEx('*1234')); expect('1234a').toMatch(makeRegEx('1234*')); expect('12a34').toMatch(makeRegEx('12a34')); }); - it('properly escapes regexp control characters', function() { + it('properly escapes regexp control characters', function () { expect('account[user_id]').toMatch(makeRegEx('account[*]')); }); - it('properly limits matches without wildcards', function() { + it('properly limits matches without wildcards', function () { expect('username').toMatch(makeRegEx('*name')); expect('username').toMatch(makeRegEx('user*')); expect('username').toMatch(makeRegEx('username')); @@ -44,22 +44,22 @@ describe('fieldWildcard', () => { }); }); - describe('filter', function() { - it('filters nothing when given undefined', function() { + describe('filter', function () { + it('filters nothing when given undefined', function () { const filter = fieldWildcardFilter(); const original = ['foo', 'bar', 'baz', 1234]; - expect(original.filter(val => filter(val))).toEqual(original); + expect(original.filter((val) => filter(val))).toEqual(original); }); - it('filters nothing when given an empty array', function() { + it('filters nothing when given an empty array', function () { const filter = fieldWildcardFilter([], metaFields); const original = ['foo', 'bar', 'baz', 1234]; expect(original.filter(filter)).toEqual(original); }); - it('does not filter metaFields', function() { + it('does not filter metaFields', function () { const filter = fieldWildcardFilter(['_*'], metaFields); const original = ['_id', '_type', '_typefake']; @@ -67,7 +67,7 @@ describe('fieldWildcard', () => { expect(original.filter(filter)).toEqual(['_id', '_type']); }); - it('filters values that match the globs', function() { + it('filters values that match the globs', function () { const filter = fieldWildcardFilter(['f*', '*4'], metaFields); const original = ['foo', 'bar', 'baz', 1234]; @@ -75,7 +75,7 @@ describe('fieldWildcard', () => { expect(original.filter(filter)).toEqual(['bar', 'baz']); }); - it('handles weird values okay', function() { + it('handles weird values okay', function () { const filter = fieldWildcardFilter(['f*', '*4', 'undefined'], metaFields); const original = ['foo', null, 'bar', undefined, {}, [], 'baz', 1234]; diff --git a/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.ts b/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.ts index 5437086ddd6f4..2aa9a255bd5cf 100644 --- a/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.ts +++ b/src/plugins/kibana_utils/public/field_wildcard/field_wildcard.ts @@ -20,10 +20,7 @@ import { escapeRegExp, memoize } from 'lodash'; export const makeRegEx = memoize(function makeRegEx(glob: string) { - const globRegex = glob - .split('*') - .map(escapeRegExp) - .join('.*'); + const globRegex = glob.split('*').map(escapeRegExp).join('.*'); return new RegExp(`^${globRegex}$`); }); @@ -34,7 +31,7 @@ export function fieldWildcardMatcher(globs: string[] = [], metaFields: unknown[] if (metaFields.indexOf(val) !== -1) { return false; } - return globs.some(p => makeRegEx(p).test(`${val}`)); + return globs.some((p) => makeRegEx(p).test(`${val}`)); }; } diff --git a/src/plugins/kibana_utils/public/resize_checker/resize_checker.test.ts b/src/plugins/kibana_utils/public/resize_checker/resize_checker.test.ts index d3013aaf8435d..0e162080ae3ff 100644 --- a/src/plugins/kibana_utils/public/resize_checker/resize_checker.test.ts +++ b/src/plugins/kibana_utils/public/resize_checker/resize_checker.test.ts @@ -50,12 +50,12 @@ class MockElement { } } -(ResizeObserver as any).mockImplementation(function(this: any, callback: any) { - this.observe = function(el: MockElement) { +(ResizeObserver as any).mockImplementation(function (this: any, callback: any) { + this.observe = function (el: MockElement) { el.addEventListener('resize', callback); }; - this.disconnect = function() {}; - this.unobserve = function(el: MockElement) { + this.disconnect = function () {}; + this.unobserve = function (el: MockElement) { el.removeEventListener('resize', callback); }; }); @@ -69,7 +69,7 @@ describe('Resize Checker', () => { expect(checker).toBeInstanceOf(EventEmitter); }); - it('emits a "resize" event', done => { + it('emits a "resize" event', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any); const listener = jest.fn(); @@ -85,7 +85,7 @@ describe('Resize Checker', () => { }); describe('enable/disabled state', () => { - it('should not trigger events while disabled', done => { + it('should not trigger events while disabled', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); @@ -100,7 +100,7 @@ describe('Resize Checker', () => { }, 100); }); - it('should trigger resize events after calling enable', done => { + it('should trigger resize events after calling enable', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); @@ -116,7 +116,7 @@ describe('Resize Checker', () => { }, 100); }); - it('should not trigger the first time after enable when the size does not change', done => { + it('should not trigger the first time after enable when the size does not change', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); @@ -134,7 +134,7 @@ describe('Resize Checker', () => { }); describe('#modifySizeWithoutTriggeringResize()', () => { - it(`does not emit "resize" events caused by the block`, done => { + it(`does not emit "resize" events caused by the block`, (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); @@ -150,7 +150,7 @@ describe('Resize Checker', () => { }, 1000); }); - it('does emit "resize" when modification is made between the block and resize notification', done => { + it('does emit "resize" when modification is made between the block and resize notification', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); @@ -180,7 +180,7 @@ describe('Resize Checker', () => { expect(!(checker as any).observer).toBe(true); }); - it('does not emit future resize events', done => { + it('does not emit future resize events', (done) => { const el = new MockElement(); const checker = new ResizeChecker(el as any, { disabled: true }); const listener = jest.fn(); diff --git a/src/plugins/kibana_utils/public/state_management/url/format.test.ts b/src/plugins/kibana_utils/public/state_management/url/format.test.ts index 728f069840c72..21dd121204bf5 100644 --- a/src/plugins/kibana_utils/public/state_management/url/format.test.ts +++ b/src/plugins/kibana_utils/public/state_management/url/format.test.ts @@ -31,7 +31,7 @@ describe('format', () => { it('should replace hash query', () => { const url = 'http://localhost:5601/oxf/app/kibana#?test=test'; expect( - replaceUrlHashQuery(url, query => ({ + replaceUrlHashQuery(url, (query) => ({ ...query, test1: 'test1', })) diff --git a/src/plugins/kibana_utils/public/state_management/url/hash_unhash_url.ts b/src/plugins/kibana_utils/public/state_management/url/hash_unhash_url.ts index a29f8bb9ac635..ec82bdeadedd5 100644 --- a/src/plugins/kibana_utils/public/state_management/url/hash_unhash_url.ts +++ b/src/plugins/kibana_utils/public/state_management/url/hash_unhash_url.ts @@ -56,5 +56,5 @@ function createQueryReplacer( queryMapper: (q: IParsedUrlQuery, options?: IUrlQueryMapperOptions) => IParsedUrlQuery, options?: IUrlQueryReplacerOptions ) { - return (url: string) => replaceUrlHashQuery(url, query => queryMapper(query, options)); + return (url: string) => replaceUrlHashQuery(url, (query) => queryMapper(query, options)); } diff --git a/src/plugins/kibana_utils/public/state_management/url/kbn_url_storage.ts b/src/plugins/kibana_utils/public/state_management/url/kbn_url_storage.ts index 6d2570b932204..20816c08c550e 100644 --- a/src/plugins/kibana_utils/public/state_management/url/kbn_url_storage.ts +++ b/src/plugins/kibana_utils/public/state_management/url/kbn_url_storage.ts @@ -87,7 +87,7 @@ export function setStateToKbnUrl( { useHash = false }: { useHash: boolean } = { useHash: false }, rawUrl = window.location.href ): string { - return replaceUrlHashQuery(rawUrl, query => { + return replaceUrlHashQuery(rawUrl, (query) => { const encoded = encodeState(state, useHash); return { ...query, diff --git a/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.test.ts b/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.test.ts index b0be822a0d011..e3133fd6d31c2 100644 --- a/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.test.ts +++ b/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.test.ts @@ -26,7 +26,7 @@ import { coreMock } from '../../../../../core/public/mocks'; import { unhashUrl } from './hash_unhash_url'; jest.mock('./hash_unhash_url', () => ({ - unhashUrl: jest.fn(x => x), + unhashUrl: jest.fn((x) => x), })); describe('kbnUrlTracker', () => { @@ -111,7 +111,7 @@ describe('kbnUrlTracker', () => { }); test('unhash all urls that are recorded while app is mounted', () => { - (unhashUrl as jest.Mock).mockImplementation(x => x + '?unhashed'); + (unhashUrl as jest.Mock).mockImplementation((x) => x + '?unhashed'); createTracker(); urlTracker.appMounted(); history.push('#/start/deep/path/2'); diff --git a/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.ts b/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.ts index 9b40aceeb02a2..d9ff3ef36abaf 100644 --- a/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.ts +++ b/src/plugins/kibana_utils/public/state_management/url/kbn_url_tracker.ts @@ -143,7 +143,7 @@ export function createKbnUrlTracker({ } if (unsubscribeGlobalState) { - unsubscribeGlobalState.forEach(sub => sub.unsubscribe()); + unsubscribeGlobalState.forEach((sub) => sub.unsubscribe()); unsubscribeGlobalState = undefined; } } @@ -165,7 +165,7 @@ export function createKbnUrlTracker({ unsubscribe(); const historyInstance = history || (getHistory && getHistory()) || createHashHistory(); // track current hash when within app - unsubscribeURLHistory = historyInstance.listen(location => { + unsubscribeURLHistory = historyInstance.listen((location) => { if (shouldTrackUrlUpdate(location.hash)) { setActiveUrl(location.hash.substr(1)); } @@ -176,7 +176,7 @@ export function createKbnUrlTracker({ unsubscribe(); // propagate state updates when in other apps unsubscribeGlobalState = stateParams.map(({ stateUpdate$, kbnUrlKey }) => - stateUpdate$.subscribe(state => { + stateUpdate$.subscribe((state) => { const updatedUrl = setStateToKbnUrl( kbnUrlKey, state, diff --git a/src/plugins/kibana_utils/public/state_management/utils/diff_object.ts b/src/plugins/kibana_utils/public/state_management/utils/diff_object.ts index 2590e2271f771..65eb8a3cc8fcc 100644 --- a/src/plugins/kibana_utils/public/state_management/utils/diff_object.ts +++ b/src/plugins/kibana_utils/public/state_management/utils/diff_object.ts @@ -30,8 +30,8 @@ export interface IDiffObject { * @param {string} key The keys * @returns {boolean} */ -const filterPrivateAndMethods = function(obj: Record) { - return function(key: string) { +const filterPrivateAndMethods = function (obj: Record) { + return function (key: string) { if (isFunction(obj[key])) return false; if (key.charAt(0) === '$') return false; return key.charAt(0) !== '_'; @@ -56,13 +56,13 @@ export function applyDiff(target: Record, source: Record !isEqual(target[key], source[key])); + diff.changed = filter(sourceKeys, (key) => !isEqual(target[key], source[key])); // Make a list of all the keys that are changing diff.keys = union(diff.changed, diff.removed, diff.added); // Remove all the keys - each(diff.removed, key => { + each(diff.removed, (key) => { delete target[key]; }); diff --git a/src/plugins/kibana_utils/public/state_sync/state_sync.test.ts b/src/plugins/kibana_utils/public/state_sync/state_sync.test.ts index 1a172d76926cc..0450f420784dd 100644 --- a/src/plugins/kibana_utils/public/state_sync/state_sync.test.ts +++ b/src/plugins/kibana_utils/public/state_sync/state_sync.test.ts @@ -184,7 +184,7 @@ describe('state_sync', () => { let history: History; let urlSyncStrategy: IKbnUrlStateStorage; const getCurrentUrl = () => history.createHref(history.location); - const tick = () => new Promise(resolve => setTimeout(resolve)); + const tick = () => new Promise((resolve) => setTimeout(resolve)); beforeEach(() => { container.set(defaultState); diff --git a/src/plugins/kibana_utils/public/state_sync/state_sync.ts b/src/plugins/kibana_utils/public/state_sync/state_sync.ts index ed57723f8f2b7..4c400d47b8e78 100644 --- a/src/plugins/kibana_utils/public/state_sync/state_sync.ts +++ b/src/plugins/kibana_utils/public/state_sync/state_sync.ts @@ -146,7 +146,7 @@ export function syncState< stateStorage.cancel(); } - subscriptions.forEach(s => s.unsubscribe()); + subscriptions.forEach((s) => s.unsubscribe()); subscriptions.splice(0, subscriptions.length); }, start: () => { @@ -175,13 +175,13 @@ export function syncState< * @param stateSyncConfigs - Array of IStateSyncConfig to sync */ export function syncStates(stateSyncConfigs: Array>): ISyncStateRef { - const syncRefs = stateSyncConfigs.map(config => syncState(config)); + const syncRefs = stateSyncConfigs.map((config) => syncState(config)); return { stop: () => { - syncRefs.forEach(s => s.stop()); + syncRefs.forEach((s) => s.stop()); }, start: () => { - syncRefs.forEach(s => s.start()); + syncRefs.forEach((s) => s.start()); }, }; } diff --git a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.test.ts b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.test.ts index 8a9a4ea71ee9a..cc708d14ea8b5 100644 --- a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.test.ts +++ b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.test.ts @@ -82,9 +82,7 @@ describe('KbnUrlStateStorage', () => { expect(urlStateStorage.change$).toBeDefined(); const key = '_s'; const destroy$ = new Subject(); - const result = urlStateStorage.change$!(key) - .pipe(takeUntil(destroy$), toArray()) - .toPromise(); + const result = urlStateStorage.change$!(key).pipe(takeUntil(destroy$), toArray()).toPromise(); history.push(`/#?${key}=(ok:1,test:test)`); history.push(`/?query=test#?${key}=(ok:2,test:test)&some=test`); @@ -119,9 +117,7 @@ describe('KbnUrlStateStorage', () => { expect(urlStateStorage.change$).toBeDefined(); const key = '_s'; const destroy$ = new Subject(); - const result = urlStateStorage.change$!(key) - .pipe(takeUntil(destroy$), toArray()) - .toPromise(); + const result = urlStateStorage.change$!(key).pipe(takeUntil(destroy$), toArray()).toPromise(); history.push(`/#?${key}=(ok:1,test:test)`); history.push(`/?query=test#?${key}=(ok:2,test:test)&some=test`); @@ -193,9 +189,7 @@ describe('KbnUrlStateStorage', () => { expect(urlStateStorage.change$).toBeDefined(); const key = '_s'; const destroy$ = new Subject(); - const result = urlStateStorage.change$!(key) - .pipe(takeUntil(destroy$), toArray()) - .toPromise(); + const result = urlStateStorage.change$!(key).pipe(takeUntil(destroy$), toArray()).toPromise(); history.push(`/#?${key}=(ok:1,test:test)`); history.push(`/?query=test#?${key}=(ok:2,test:test)&some=test`); diff --git a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.ts b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.ts index 082eaa5095ab9..67c1bf26aa251 100644 --- a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.ts +++ b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/create_kbn_url_state_storage.ts @@ -61,17 +61,17 @@ export const createKbnUrlStateStorage = ( ) => { // syncState() utils doesn't wait for this promise return url.updateAsync( - currentUrl => setStateToKbnUrl(key, state, { useHash }, currentUrl), + (currentUrl) => setStateToKbnUrl(key, state, { useHash }, currentUrl), replace ); }, - get: key => { + get: (key) => { // if there is a pending url update, then state will be extracted from that pending url, // otherwise current url will be used to retrieve state from return getStateFromKbnUrl(key, url.getPendingUrl()); }, change$: (key: string) => - new Observable(observer => { + new Observable((observer) => { const unlisten = url.listen(() => { observer.next(); }); diff --git a/src/plugins/kibana_utils/public/storage/__tests__/storage.js b/src/plugins/kibana_utils/public/storage/__tests__/storage.js index 9782fddacbfc3..073ed275b9aac 100644 --- a/src/plugins/kibana_utils/public/storage/__tests__/storage.js +++ b/src/plugins/kibana_utils/public/storage/__tests__/storage.js @@ -27,7 +27,7 @@ let $window; const payload = { first: 'john', last: 'smith' }; function init() { - ngMock.module('kibana/storage', function($provide) { + ngMock.module('kibana/storage', function ($provide) { // mock $window.localStorage for storage $provide.value('$window', { localStorage: { @@ -39,19 +39,19 @@ function init() { }); }); - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { storage = $injector.get('localStorage'); $window = $injector.get('$window'); }); } -describe('StorageService', function() { - beforeEach(function() { +describe('StorageService', function () { + beforeEach(function () { init(); }); - describe('expected API', function() { - it('should have expected methods', function() { + describe('expected API', function () { + it('should have expected methods', function () { expect(storage.get).to.be.a('function'); expect(storage.set).to.be.a('function'); expect(storage.remove).to.be.a('function'); @@ -59,34 +59,34 @@ describe('StorageService', function() { }); }); - describe('call behavior', function() { - it('should call getItem on the store', function() { + describe('call behavior', function () { + it('should call getItem on the store', function () { storage.get('name'); expect($window.localStorage.getItem.callCount).to.equal(1); }); - it('should call setItem on the store', function() { + it('should call setItem on the store', function () { storage.set('name', 'john smith'); expect($window.localStorage.setItem.callCount).to.equal(1); }); - it('should call removeItem on the store', function() { + it('should call removeItem on the store', function () { storage.remove('name'); expect($window.localStorage.removeItem.callCount).to.equal(1); }); - it('should call clear on the store', function() { + it('should call clear on the store', function () { storage.clear(); expect($window.localStorage.clear.callCount).to.equal(1); }); }); - describe('json data', function() { - it('should parse JSON when reading from the store', function() { + describe('json data', function () { + it('should parse JSON when reading from the store', function () { const getItem = $window.localStorage.getItem; getItem.returns(JSON.stringify(payload)); @@ -94,7 +94,7 @@ describe('StorageService', function() { expect(data).to.eql(payload); }); - it('should write JSON string to the store', function() { + it('should write JSON string to the store', function () { const setItem = $window.localStorage.setItem; const key = 'name'; const value = payload; @@ -107,13 +107,13 @@ describe('StorageService', function() { }); }); - describe('expected responses', function() { - it('should return null when not exists', function() { + describe('expected responses', function () { + it('should return null when not exists', function () { const data = storage.get('notexists'); expect(data).to.equal(null); }); - it('should return null when invalid JSON', function() { + it('should return null when invalid JSON', function () { const getItem = $window.localStorage.getItem; getItem.returns('not: json'); diff --git a/src/plugins/kibana_utils/public/storage/hashed_item_store/hashed_item_store.ts b/src/plugins/kibana_utils/public/storage/hashed_item_store/hashed_item_store.ts index 485aa643c4f01..fe18f426f226b 100644 --- a/src/plugins/kibana_utils/public/storage/hashed_item_store/hashed_item_store.ts +++ b/src/plugins/kibana_utils/public/storage/hashed_item_store/hashed_item_store.ts @@ -159,7 +159,7 @@ export class HashedItemStore implements IStorage { } private getIndexedItem(hash: string, indexedItems: IndexedItem[] = this.getIndexedItems()) { - return indexedItems.find(indexedItem => indexedItem.hash === hash); + return indexedItems.find((indexedItem) => indexedItem.hash === hash); } private persistItem(hash: string, item: string): boolean { diff --git a/src/plugins/management/public/components/management_sidebar_nav/management_sidebar_nav.tsx b/src/plugins/management/public/components/management_sidebar_nav/management_sidebar_nav.tsx index c58de6d8b0a81..208f577b76996 100644 --- a/src/plugins/management/public/components/management_sidebar_nav/management_sidebar_nav.tsx +++ b/src/plugins/management/public/components/management_sidebar_nav/management_sidebar_nav.tsx @@ -102,13 +102,13 @@ const legacyAppToNavItem = (app: LegacyApp, selectedId: string) => ({ const sectionVisible = (section: LegacySection | LegacyApp) => !section.disabled && section.visible; const sideNavItems = (sections: ManagementSection[], selectedId: string) => - sections.map(section => ({ + sections.map((section) => ({ items: section.getAppsEnabled().map(managementAppToNavItem(selectedId, section.id)), ...managementSectionToNavSection(section), })); const findOrAddSection = (navItems: NavSection[], legacySection: LegacySection): NavSection => { - const foundSection = navItems.find(sec => sec.id === legacySection.id); + const foundSection = navItems.find((sec) => sec.id === legacySection.id); if (foundSection) { return foundSection; @@ -127,11 +127,11 @@ export const mergeLegacyItems = ( ) => { const filteredLegacySections = legacySections .filter(sectionVisible) - .filter(section => section.visibleItems.length); + .filter((section) => section.visibleItems.length); - filteredLegacySections.forEach(legacySection => { + filteredLegacySections.forEach((legacySection) => { const section = findOrAddSection(navItems, legacySection); - legacySection.visibleItems.forEach(app => { + legacySection.visibleItems.forEach((app) => { section.items.push(legacyAppToNavItem(app, selectedId)); return section.items.sort((a, b) => a.order - b.order); }); diff --git a/src/plugins/management/public/legacy/section.js b/src/plugins/management/public/legacy/section.js index 7d733b7b3173b..5b39f350bf444 100644 --- a/src/plugins/management/public/legacy/section.js +++ b/src/plugins/management/public/legacy/section.js @@ -54,7 +54,7 @@ export class LegacyManagementSection { } get visibleItems() { - return this.items.inOrder.filter(item => { + return this.items.inOrder.filter((item) => { const capabilityManagementSection = this.capabilities.management[this.id]; const itemCapability = capabilityManagementSection ? capabilityManagementSection[item.id] @@ -94,7 +94,7 @@ export class LegacyManagementSection { } this.items.push(item); - listeners.forEach(fn => fn()); + listeners.forEach((fn) => fn()); return item; } @@ -105,8 +105,8 @@ export class LegacyManagementSection { * @param {string} id */ deregister(id) { - this.items.remove(item => item.id === id); - listeners.forEach(fn => fn(this.items)); + this.items.remove((item) => item.id === id); + listeners.forEach((fn) => fn(this.items)); } /** diff --git a/src/plugins/management/public/legacy/section.test.js b/src/plugins/management/public/legacy/section.test.js index 45cc80ef80edd..bf75506a218d5 100644 --- a/src/plugins/management/public/legacy/section.test.js +++ b/src/plugins/management/public/legacy/section.test.js @@ -89,7 +89,7 @@ describe('ManagementSection', () => { expect(section.register('about').parent).toBe(section); }); - it('adds item', function() { + it('adds item', function () { section.register('about', { description: 'test' }); expect(section.items).toHaveLength(1); @@ -203,7 +203,7 @@ describe('ManagementSection', () => { }); it('can be ordered', () => { - const ids = section.items.inOrder.map(i => { + const ids = section.items.inOrder.map((i) => { return i.id; }); expect(ids).toEqual(['one', 'two', 'three']); @@ -259,7 +259,7 @@ describe('ManagementSection', () => { }); it('maintains the order', () => { - const ids = section.visibleItems.map(i => { + const ids = section.visibleItems.map((i) => { return i.id; }); expect(ids).toEqual(['one', 'two', 'three']); @@ -268,7 +268,7 @@ describe('ManagementSection', () => { it('does not include hidden items', () => { section.getSection('two').hide(); - const ids = section.visibleItems.map(i => { + const ids = section.visibleItems.map((i) => { return i.id; }); expect(ids).toEqual(['one', 'three']); @@ -276,7 +276,7 @@ describe('ManagementSection', () => { it('does not include visible items hidden via uiCapabilities', () => { section.register('sampleFeature2', { order: 4, visible: true }); - const ids = section.visibleItems.map(i => { + const ids = section.visibleItems.map((i) => { return i.id; }); expect(ids).toEqual(['one', 'two', 'three']); diff --git a/src/plugins/management/public/legacy/sections_register.js b/src/plugins/management/public/legacy/sections_register.js index 3fa1998c378f6..d77f87e80ea18 100644 --- a/src/plugins/management/public/legacy/sections_register.js +++ b/src/plugins/management/public/legacy/sections_register.js @@ -23,7 +23,7 @@ import { managementSections } from '../management_sections'; export class LegacyManagementAdapter { main = undefined; - init = capabilities => { + init = (capabilities) => { this.main = new LegacyManagementSection( 'management', { diff --git a/src/plugins/management/public/management_app.tsx b/src/plugins/management/public/management_app.tsx index 843bbfde654ee..2954cefa86d5c 100644 --- a/src/plugins/management/public/management_app.tsx +++ b/src/plugins/management/public/management_app.tsx @@ -77,7 +77,7 @@ export class ManagementApp { getSections={getSections} selectedId={id} legacySections={getLegacyManagementSections().items} - onMounted={async element => { + onMounted={async (element) => { appUnmount = await mount({ basePath, element, diff --git a/src/plugins/management/public/management_section.ts b/src/plugins/management/public/management_section.ts index ace8f87bec766..80ef1a108ecd8 100644 --- a/src/plugins/management/public/management_section.ts +++ b/src/plugins/management/public/management_section.ts @@ -72,9 +72,9 @@ export class ManagementSection { return app; } getApp(id: ManagementApp['id']) { - return this.apps.find(app => app.id === id); + return this.apps.find((app) => app.id === id); } getAppsEnabled() { - return this.apps.filter(app => app.enabled).sort((a, b) => a.order - b.order); + return this.apps.filter((app) => app.enabled).sort((a, b) => a.order - b.order); } } diff --git a/src/plugins/management/public/management_service.ts b/src/plugins/management/public/management_service.ts index 85d27a526d402..84939fe095336 100644 --- a/src/plugins/management/public/management_service.ts +++ b/src/plugins/management/public/management_service.ts @@ -53,7 +53,7 @@ export class ManagementService { } private getSection(sectionId: ManagementSectionId) { - return this.sections.find(section => section.id === sectionId); + return this.sections.find((section) => section.id === sectionId); } private getAllSections() { @@ -62,7 +62,7 @@ export class ManagementService { private getSectionsEnabled() { return this.sections - .filter(section => section.getAppsEnabled().length > 0) + .filter((section) => section.getAppsEnabled().length > 0) .sort((a, b) => a.order - b.order); } diff --git a/src/plugins/maps_legacy/public/__tests__/map/kibana_map.js b/src/plugins/maps_legacy/public/__tests__/map/kibana_map.js index 1002a8e9eedc8..ae6d3144335cf 100644 --- a/src/plugins/maps_legacy/public/__tests__/map/kibana_map.js +++ b/src/plugins/maps_legacy/public/__tests__/map/kibana_map.js @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { KibanaMap } from '../../map/kibana_map'; import { KibanaMapLayer } from '../../map/kibana_map_layer'; -describe('kibana_map tests', function() { +describe('kibana_map tests', function () { let domNode; let kibanaMap; @@ -46,8 +46,8 @@ describe('kibana_map tests', function() { document.body.removeChild(domNode); } - describe('KibanaMap - basics', function() { - beforeEach(async function() { + describe('KibanaMap - basics', function () { + beforeEach(async function () { setupDOM('512px', '512px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -57,12 +57,12 @@ describe('kibana_map tests', function() { }); }); - afterEach(function() { + afterEach(function () { kibanaMap.destroy(); teardownDOM(); }); - it('should instantiate at zoom level 2', function() { + it('should instantiate at zoom level 2', function () { const bounds = kibanaMap.getBounds(); expect(bounds.bottom_right.lon).to.equal(90); expect(bounds.top_left.lon).to.equal(-90); @@ -71,7 +71,7 @@ describe('kibana_map tests', function() { expect(kibanaMap.getZoomLevel()).to.equal(2); }); - it('should resize to fit container', function() { + it('should resize to fit container', function () { kibanaMap.setZoomLevel(2); expect(kibanaMap.getCenter().lon).to.equal(0); expect(kibanaMap.getCenter().lat).to.equal(0); @@ -85,14 +85,14 @@ describe('kibana_map tests', function() { }); }); - describe('getBounds', function() { - afterEach(function() { + describe('getBounds', function () { + afterEach(function () { kibanaMap.destroy(); teardownDOM(); }); - describe('extended bounds', function() { - beforeEach(async function() { + describe('extended bounds', function () { + beforeEach(async function () { setupDOM('1600px', '1024px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -102,15 +102,15 @@ describe('kibana_map tests', function() { }); }); - it('should get untrimmed map bounds', function() { + it('should get untrimmed map bounds', function () { const bounds = kibanaMap.getBounds(); expect(bounds.bottom_right.lon.toFixed(2)).to.equal('281.25'); expect(bounds.top_left.lon.toFixed(2)).to.equal('-281.25'); }); }); - describe('no map height (should default to size of 1px for height)', function() { - beforeEach(async function() { + describe('no map height (should default to size of 1px for height)', function () { + beforeEach(async function () { setupDOM('386px', '256px'); const noHeightNode = createDiv('386px', '0px'); domNode.appendChild(noHeightNode); @@ -122,7 +122,7 @@ describe('kibana_map tests', function() { }); }); - it('should calculate map dimensions based on enforcement of single pixel min-width CSS-rule', function() { + it('should calculate map dimensions based on enforcement of single pixel min-width CSS-rule', function () { const bounds = kibanaMap.getBounds(); expect(bounds).to.have.property('bottom_right'); expect(round(bounds.bottom_right.lon, 2)).to.equal(0.27); @@ -137,8 +137,8 @@ describe('kibana_map tests', function() { } }); - describe('no map width (should default to size of 1px for width)', function() { - beforeEach(async function() { + describe('no map width (should default to size of 1px for width)', function () { + beforeEach(async function () { setupDOM('386px', '256px'); const noWidthNode = createDiv('0px', '256px'); domNode.appendChild(noWidthNode); @@ -150,7 +150,7 @@ describe('kibana_map tests', function() { }); }); - it('should calculate map dimensions based on enforcement of single pixel min-width CSS-rule', function() { + it('should calculate map dimensions based on enforcement of single pixel min-width CSS-rule', function () { const bounds = kibanaMap.getBounds(); expect(bounds).to.have.property('bottom_right'); expect(Math.round(bounds.bottom_right.lon)).to.equal(0); @@ -161,8 +161,8 @@ describe('kibana_map tests', function() { }); }); - describe('wrapping', function() { - beforeEach(async function() { + describe('wrapping', function () { + beforeEach(async function () { setupDOM('1600px', '1024px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -172,15 +172,15 @@ describe('kibana_map tests', function() { }); }); - it('coordinates should be corrected to center the -180,180 range', function() { + it('coordinates should be corrected to center the -180,180 range', function () { const bounds = kibanaMap.getBounds(); expect(bounds.bottom_right.lon.toFixed(2)).to.equal('201.09'); expect(bounds.top_left.lon.toFixed(2)).to.equal('-361.41'); }); }); - describe('wrapping - zoomed in', function() { - beforeEach(async function() { + describe('wrapping - zoomed in', function () { + beforeEach(async function () { setupDOM('1600px', '1024px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -190,7 +190,7 @@ describe('kibana_map tests', function() { }); }); - it('coordinates should be corrected to fall within the -180,180 range', function() { + it('coordinates should be corrected to fall within the -180,180 range', function () { const bounds = kibanaMap.getBounds(); expect(bounds.bottom_right.lon.toFixed(2)).to.equal('-75.61'); expect(bounds.top_left.lon.toFixed(2)).to.equal('-84.40'); @@ -198,8 +198,8 @@ describe('kibana_map tests', function() { }); }); - describe('KibanaMap - attributions', function() { - beforeEach(async function() { + describe('KibanaMap - attributions', function () { + beforeEach(async function () { setupDOM('512px', '512px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -209,7 +209,7 @@ describe('kibana_map tests', function() { }); }); - afterEach(function() { + afterEach(function () { kibanaMap.destroy(); teardownDOM(); }); @@ -222,7 +222,7 @@ describe('kibana_map tests', function() { return layer; } - it('should update attributions correctly', function() { + it('should update attributions correctly', function () { kibanaMap.addLayer(makeMockLayer('foo|bar')); expect(domNode.querySelectorAll('.leaflet-control-attribution')[0].innerHTML).to.equal( 'foo, bar' @@ -246,8 +246,8 @@ describe('kibana_map tests', function() { }); }); - describe('KibanaMap - baseLayer', function() { - beforeEach(async function() { + describe('KibanaMap - baseLayer', function () { + beforeEach(async function () { setupDOM('512px', '512px'); kibanaMap = new KibanaMap(domNode, { minZoom: 1, @@ -257,12 +257,12 @@ describe('kibana_map tests', function() { }); }); - afterEach(function() { + afterEach(function () { kibanaMap.destroy(); teardownDOM(); }); - it('TMS', async function() { + it('TMS', async function () { const options = { url: 'https://tiles-stage.elastic.co/v2/default/{z}/{x}/{y}.png?elastic_tile_service_tos=agree&my_app_name=kibana', @@ -271,7 +271,7 @@ describe('kibana_map tests', function() { attribution: '© [Elastic Maps Service](https://www.elastic.co/elastic-maps-service)', }; - return new Promise(function(resolve) { + return new Promise(function (resolve) { kibanaMap.on('baseLayer:loaded', () => { resolve(); }); @@ -282,7 +282,7 @@ describe('kibana_map tests', function() { }); }); - it('WMS - should handle empty settings', async function() { + it('WMS - should handle empty settings', async function () { const invalidOptions = { url: undefined, version: undefined, @@ -303,7 +303,7 @@ describe('kibana_map tests', function() { expect(kibanaMap.getLeafletBaseLayer()).to.eql(null); }); - it('WMS - should clean attribution', async function() { + it('WMS - should clean attribution', async function () { const options = { url: 'https://basemap.nationalmap.gov/arcgis/services/USGSTopo/MapServer/WMSServer', version: '1.1.0', diff --git a/src/plugins/maps_legacy/public/__tests__/map/service_settings.js b/src/plugins/maps_legacy/public/__tests__/map/service_settings.js index 822378163a7eb..72c4323ed0736 100644 --- a/src/plugins/maps_legacy/public/__tests__/map/service_settings.js +++ b/src/plugins/maps_legacy/public/__tests__/map/service_settings.js @@ -28,7 +28,7 @@ import EMS_STYLE_ROAD_MAP_DESATURATED from './ems_mocks/sample_style_desaturated import EMS_STYLE_DARK_MAP from './ems_mocks/sample_style_dark'; import { ORIGIN } from '../../common/constants/origin'; -describe('service_settings (FKA tilemaptest)', function() { +describe('service_settings (FKA tilemaptest)', function () { let serviceSettings; let mapConfig; let tilemapsConfig; @@ -40,7 +40,7 @@ describe('service_settings (FKA tilemaptest)', function() { const emsFileApiUrl2 = 'https://files_override.foobar'; beforeEach( - ngMock.module('kibana', $provide => { + ngMock.module('kibana', ($provide) => { $provide.decorator('mapConfig', () => { return { emsFileApiUrl, @@ -61,9 +61,9 @@ describe('service_settings (FKA tilemaptest)', function() { let tilemapsConfigDeprecatedOriginal; let getManifestStub; beforeEach( - ngMock.inject(function($injector, $rootScope) { + ngMock.inject(function ($injector, $rootScope) { serviceSettings = $injector.get('serviceSettings'); - getManifestStub = serviceSettings.__debugStubManifestCalls(async url => { + getManifestStub = serviceSettings.__debugStubManifestCalls(async (url) => { //simulate network calls if (url.startsWith('https://tiles.foobar')) { if (url.includes('/manifest')) { @@ -90,21 +90,21 @@ describe('service_settings (FKA tilemaptest)', function() { }) ); - afterEach(function() { + afterEach(function () { getManifestStub.removeStub(); mapConfig.emsTileApiUrl = emsTileApiUrlOriginal; mapConfig.emsFileApiUrl = emsFileApiUrlOriginal; tilemapsConfig.deprecated = tilemapsConfigDeprecatedOriginal; }); - describe('TMS', function() { - it('should NOT get url from the config', async function() { + describe('TMS', function () { + it('should NOT get url from the config', async function () { const tmsServices = await serviceSettings.getTMSServices(); const tmsService = tmsServices[0]; expect(typeof tmsService.url === 'undefined').to.equal(true); }); - it('should get url by resolving dynamically', async function() { + it('should get url by resolving dynamically', async function () { const tmsServices = await serviceSettings.getTMSServices(); const tmsService = tmsServices[0]; expect(typeof tmsService.url === 'undefined').to.equal(true); @@ -121,23 +121,21 @@ describe('service_settings (FKA tilemaptest)', function() { expect(urlObject.query).to.have.property('my_app_version'); }); - it('should get options', async function() { + it('should get options', async function () { const tmsServices = await serviceSettings.getTMSServices(); const tmsService = tmsServices[0]; expect(tmsService).to.have.property('minZoom'); expect(tmsService).to.have.property('maxZoom'); - expect(tmsService) - .to.have.property('attribution') - .contain('OpenStreetMap'); + expect(tmsService).to.have.property('attribution').contain('OpenStreetMap'); }); - describe('modify - url', function() { + describe('modify - url', function () { let tilemapServices; async function assertQuery(expected) { const attrs = await serviceSettings.getAttributesForTMSLayer(tilemapServices[0]); const urlObject = url.parse(attrs.url, true); - Object.keys(expected).forEach(key => { + Object.keys(expected).forEach((key) => { expect(urlObject.query).to.have.property(key, expected[key]); }); } @@ -215,7 +213,7 @@ describe('service_settings (FKA tilemaptest)', function() { it('should load appropriate EMS attributes for desaturated and dark theme', async () => { tilemapServices = await serviceSettings.getTMSServices(); - const roadMapService = tilemapServices.find(service => service.id === 'road_map'); + const roadMapService = tilemapServices.find((service) => service.id === 'road_map'); const desaturationFalse = await serviceSettings.getAttributesForTMSLayer( roadMapService, @@ -290,16 +288,16 @@ describe('service_settings (FKA tilemaptest)', function() { }); }); - describe('File layers', function() { - it('should load manifest (all props)', async function() { + describe('File layers', function () { + it('should load manifest (all props)', async function () { serviceSettings.setQueryParams({ foo: 'bar' }); const fileLayers = await serviceSettings.getFileLayers(); expect(fileLayers.length).to.be(18); - const assertions = fileLayers.map(async function(fileLayer) { + const assertions = fileLayers.map(async function (fileLayer) { expect(fileLayer.origin).to.be(ORIGIN.EMS); const fileUrl = await serviceSettings.getUrlForRegionLayer(fileLayer); const urlObject = url.parse(fileUrl, true); - Object.keys({ foo: 'bar', elastic_tile_service_tos: 'agree' }).forEach(key => { + Object.keys({ foo: 'bar', elastic_tile_service_tos: 'agree' }).forEach((key) => { expect(urlObject.query).to.have.property(key); }); }); diff --git a/src/plugins/maps_legacy/public/kibana_services.js b/src/plugins/maps_legacy/public/kibana_services.js index 815c6f9e5651f..e0a6a6e21ab00 100644 --- a/src/plugins/maps_legacy/public/kibana_services.js +++ b/src/plugins/maps_legacy/public/kibana_services.js @@ -18,13 +18,13 @@ */ let toast; -export const setToasts = notificationToast => (toast = notificationToast); +export const setToasts = (notificationToast) => (toast = notificationToast); export const getToasts = () => toast; let uiSettings; -export const setUiSettings = coreUiSettings => (uiSettings = coreUiSettings); +export const setUiSettings = (coreUiSettings) => (uiSettings = coreUiSettings); export const getUiSettings = () => uiSettings; let getInjectedVar; -export const setInjectedVarFunc = getInjectedVarFunc => (getInjectedVar = getInjectedVarFunc); +export const setInjectedVarFunc = (getInjectedVarFunc) => (getInjectedVar = getInjectedVarFunc); export const getInjectedVarFunc = () => getInjectedVar; diff --git a/src/plugins/maps_legacy/public/map/base_maps_visualization.js b/src/plugins/maps_legacy/public/map/base_maps_visualization.js index c4ac671a5187c..2d1a45beb5d87 100644 --- a/src/plugins/maps_legacy/public/map/base_maps_visualization.js +++ b/src/plugins/maps_legacy/public/map/base_maps_visualization.js @@ -142,7 +142,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings) const userConfiguredTmsLayer = tmsServices[0]; const initBasemapLayer = userConfiguredTmsLayer ? userConfiguredTmsLayer - : tmsServices.find(s => s.id === emsTileLayerId.bright); + : tmsServices.find((s) => s.id === emsTileLayerId.bright); if (initBasemapLayer) { this._setTmsLayer(initBasemapLayer); } @@ -245,9 +245,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings) const interval$ = Rx.interval(10).pipe(filter(() => !this._baseLayerDirty)); const timer$ = Rx.timer(maxTimeForBaseLayer); - return Rx.race(interval$, timer$) - .pipe(first()) - .toPromise(); + return Rx.race(interval$, timer$).pipe(first()).toPromise(); } }; } diff --git a/src/plugins/maps_legacy/public/map/convert_to_geojson.js b/src/plugins/maps_legacy/public/map/convert_to_geojson.js index 2186dbb3fc2a3..bca21e4deea97 100644 --- a/src/plugins/maps_legacy/public/map/convert_to_geojson.js +++ b/src/plugins/maps_legacy/public/map/convert_to_geojson.js @@ -36,7 +36,7 @@ export function convertToGeoJson(tabifiedResponse, { geohash, geocentroid, metri const geocentroidColumn = geocentroid ? table.columns[geocentroid.accessor] : null; features = table.rows - .map(row => { + .map((row) => { const geohashValue = row[geohashColumn.id]; if (!geohashValue) return false; const geohashLocation = decodeGeoHash(geohashValue); @@ -92,7 +92,7 @@ export function convertToGeoJson(tabifiedResponse, { geohash, geocentroid, metri }, }; }) - .filter(row => row); + .filter((row) => row); } } else { features = []; diff --git a/src/plugins/maps_legacy/public/map/kibana_map.js b/src/plugins/maps_legacy/public/map/kibana_map.js index 85dafc318db8d..ad5d2c089b875 100644 --- a/src/plugins/maps_legacy/public/map/kibana_map.js +++ b/src/plugins/maps_legacy/public/map/kibana_map.js @@ -33,12 +33,12 @@ function makeFitControl(fitContainer, kibanaMap) { options: { position: 'topleft', }, - initialize: function(fitContainer, kibanaMap) { + initialize: function (fitContainer, kibanaMap) { this._fitContainer = fitContainer; this._kibanaMap = kibanaMap; this._leafletMap = null; }, - onAdd: function(leafletMap) { + onAdd: function (leafletMap) { this._leafletMap = leafletMap; const fitDatBoundsLabel = i18n.translate( 'maps_legacy.kibanaMap.leaflet.fitDataBoundsAriaLabel', @@ -48,14 +48,14 @@ function makeFitControl(fitContainer, kibanaMap) { .html( `` ) - .on('click', e => { + .on('click', (e) => { e.preventDefault(); this._kibanaMap.fitToData(); }); return this._fitContainer; }, - onRemove: function() { + onRemove: function () { $(this._fitContainer).off('click'); }, }); @@ -70,7 +70,7 @@ function makeLegendControl(container, kibanaMap, position) { position: 'topright', }, - initialize: function(container, kibanaMap, position) { + initialize: function (container, kibanaMap, position) { this._legendContainer = container; this._kibanaMap = kibanaMap; this.options.position = position; @@ -81,16 +81,16 @@ function makeLegendControl(container, kibanaMap, position) { const $div = $('
').addClass('visMapLegend'); this._legendContainer.append($div); const layers = this._kibanaMap.getLayers(); - layers.forEach(layer => layer.appendLegendContents($div)); + layers.forEach((layer) => layer.appendLegendContents($div)); }, - onAdd: function() { + onAdd: function () { this._layerUpdateHandle = () => this.updateContents(); this._kibanaMap.on('layers:update', this._layerUpdateHandle); this.updateContents(); return this._legendContainer.get(0); }, - onRemove: function() { + onRemove: function () { this._kibanaMap.removeListener('layers:update', this._layerUpdateHandle); this._legendContainer.empty(); }, @@ -152,19 +152,19 @@ export class KibanaMap extends EventEmitter { this._leafletMap.on('zoomend', () => this._updateExtent()); this._leafletMap.on('dragend', () => this._updateExtent()); - this._leafletMap.on('mousemove', e => - this._layers.forEach(layer => layer.movePointer('mousemove', e)) + this._leafletMap.on('mousemove', (e) => + this._layers.forEach((layer) => layer.movePointer('mousemove', e)) ); - this._leafletMap.on('mouseout', e => - this._layers.forEach(layer => layer.movePointer('mouseout', e)) + this._leafletMap.on('mouseout', (e) => + this._layers.forEach((layer) => layer.movePointer('mouseout', e)) ); - this._leafletMap.on('mousedown', e => - this._layers.forEach(layer => layer.movePointer('mousedown', e)) + this._leafletMap.on('mousedown', (e) => + this._layers.forEach((layer) => layer.movePointer('mousedown', e)) ); - this._leafletMap.on('mouseup', e => - this._layers.forEach(layer => layer.movePointer('mouseup', e)) + this._leafletMap.on('mouseup', (e) => + this._layers.forEach((layer) => layer.movePointer('mouseup', e)) ); - this._leafletMap.on('draw:created', event => { + this._leafletMap.on('draw:created', (event) => { const drawType = event.layerType; if (drawType === 'rectangle') { const bounds = event.layer.getBounds(); @@ -204,7 +204,7 @@ export class KibanaMap extends EventEmitter { } else if (drawType === 'polygon') { const latLongs = event.layer.getLatLngs()[0]; this.emit('drawCreated:polygon', { - points: latLongs.map(leafletLatLng => { + points: latLongs.map((leafletLatLng) => { return { lat: leafletLatLng.lat, lon: leafletLatLng.lng, @@ -226,7 +226,7 @@ export class KibanaMap extends EventEmitter { } addLayer(kibanaLayer) { - const onshowTooltip = event => { + const onshowTooltip = (event) => { if (!this._showTooltip) { return; } @@ -283,14 +283,14 @@ export class KibanaMap extends EventEmitter { this._layers.splice(index, 1); kibanaLayer.removeFromLeafletMap(this._leafletMap); } - this._listeners.forEach(listener => { + this._listeners.forEach((listener) => { if (listener.layer === kibanaLayer) { listener.layer.removeListener(listener.name, listener.handle); } }); //must readd all attributions, because we might have removed dupes - this._layers.forEach(layer => this._addAttributions(layer.getAttributions())); + this._layers.forEach((layer) => this._addAttributions(layer.getAttributions())); if (this._baseLayerSettings) { this._addAttributions(this._baseLayerSettings.options.attribution); } @@ -298,7 +298,7 @@ export class KibanaMap extends EventEmitter { _addAttributions(attribution) { const attributions = getAttributionArray(attribution); - attributions.forEach(attribution => { + attributions.forEach((attribution) => { this._leafletMap.attributionControl.removeAttribution(attribution); //this ensures we do not add duplicates this._leafletMap.attributionControl.addAttribution(attribution); }); @@ -306,7 +306,7 @@ export class KibanaMap extends EventEmitter { _removeAttributions(attribution) { const attributions = getAttributionArray(attribution); - attributions.forEach(attribution => { + attributions.forEach((attribution) => { this._leafletMap.attributionControl.removeAttribution(attribution); //this ensures we do not add duplicates }); } @@ -329,7 +329,7 @@ export class KibanaMap extends EventEmitter { } this._leafletMap.remove(); this._containerNode.innerHTML = ''; - this._listeners.forEach(listener => + this._listeners.forEach((listener) => listener.layer.removeListener(listener.name, listener.handle) ); } @@ -490,7 +490,7 @@ export class KibanaMap extends EventEmitter { this._updateLegend(); } - _addMaxZoomMessage = layer => { + _addMaxZoomMessage = (layer) => { const zoomWarningMsg = createZoomWarningMsg( getToasts(), this.getZoomLevel, @@ -609,13 +609,13 @@ export class KibanaMap extends EventEmitter { } const boundsArray = await Promise.all( - this._layers.map(async layer => { + this._layers.map(async (layer) => { return await layer.getBounds(); }) ); let bounds = null; - boundsArray.forEach(async b => { + boundsArray.forEach(async (b) => { if (bounds) { bounds.extend(b); } else { @@ -655,7 +655,7 @@ export class KibanaMap extends EventEmitter { } _updateExtent() { - this._layers.forEach(layer => layer.updateExtent()); + this._layers.forEach((layer) => layer.updateExtent()); } _updateDesaturation() { diff --git a/src/plugins/maps_legacy/public/map/map_messages.js b/src/plugins/maps_legacy/public/map/map_messages.js index 7422fa71280fb..3c7dca0ba9b4e 100644 --- a/src/plugins/maps_legacy/public/map/map_messages.js +++ b/src/plugins/maps_legacy/public/map/map_messages.js @@ -22,9 +22,9 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiSpacer, EuiButtonEmpty } from '@elastic/eui'; import { toMountPoint } from '../../../kibana_react/public'; -export const createZoomWarningMsg = (function() { +export const createZoomWarningMsg = (function () { let disableZoomMsg = false; - const setZoomMsg = boolDisableMsg => (disableZoomMsg = boolDisableMsg); + const setZoomMsg = (boolDisableMsg) => (disableZoomMsg = boolDisableMsg); class ZoomWarning extends React.Component { constructor(props) { diff --git a/src/plugins/maps_legacy/public/map/service_settings.js b/src/plugins/maps_legacy/public/map/service_settings.js index 437b78a3c3472..7c2b841e4adf3 100644 --- a/src/plugins/maps_legacy/public/map/service_settings.js +++ b/src/plugins/maps_legacy/public/map/service_settings.js @@ -42,7 +42,7 @@ export class ServiceSettings { tileApiUrl: this._mapConfig.emsTileApiUrl, landingPageUrl: this._mapConfig.emsLandingPageUrl, // Wrap to avoid errors passing window fetch - fetchFunction: function(...args) { + fetchFunction: function (...args) { return fetch(...args); }, }); @@ -97,7 +97,7 @@ export class ServiceSettings { } const fileLayers = await this._emsClient.getFileLayers(); - return fileLayers.map(fileLayer => { + return fileLayers.map((fileLayer) => { //backfill to older settings const format = fileLayer.getDefaultFormatType(); const meta = fileLayer.getDefaultFormatMeta(); @@ -133,8 +133,8 @@ export class ServiceSettings { const servicesFromManifest = await this._emsClient.getTMSServices(); const strippedServiceFromManifest = await Promise.all( servicesFromManifest - .filter(tmsService => tmsService.getId() === this._mapConfig.emsTileLayerId.bright) - .map(async tmsService => { + .filter((tmsService) => tmsService.getId() === this._mapConfig.emsTileLayerId.bright) + .map(async (tmsService) => { //shim for compatibility return { origin: tmsService.getOrigin(), @@ -163,7 +163,7 @@ export class ServiceSettings { async getEMSHotLink(fileLayerConfig) { const fileLayers = await this._emsClient.getFileLayers(); - const layer = fileLayers.find(fileLayer => { + const layer = fileLayers.find((fileLayer) => { const hasIdByName = fileLayer.hasId(fileLayerConfig.name); //legacy const hasIdById = fileLayer.hasId(fileLayerConfig.id); return hasIdByName || hasIdById; @@ -184,7 +184,7 @@ export class ServiceSettings { serviceId = emsTileLayerId.bright; } } - const tmsService = tmsServices.find(service => { + const tmsService = tmsServices.find((service) => { return service.getId() === serviceId; }); return { @@ -218,7 +218,7 @@ export class ServiceSettings { async _getFileUrlFromEMS(fileLayerConfig) { const fileLayers = await this._emsClient.getFileLayers(); - const layer = fileLayers.find(fileLayer => { + const layer = fileLayers.find((fileLayer) => { const hasIdByName = fileLayer.hasId(fileLayerConfig.name); //legacy const hasIdById = fileLayer.hasId(fileLayerConfig.id); return hasIdByName || hasIdById; diff --git a/src/plugins/navigation/public/top_nav_menu/create_top_nav_menu.tsx b/src/plugins/navigation/public/top_nav_menu/create_top_nav_menu.tsx index 79201a9da88c5..e8292f38c2ecb 100644 --- a/src/plugins/navigation/public/top_nav_menu/create_top_nav_menu.tsx +++ b/src/plugins/navigation/public/top_nav_menu/create_top_nav_menu.tsx @@ -30,7 +30,7 @@ export function createTopNav( ) { return (props: TopNavMenuProps) => { const relevantConfig = extraConfig.filter( - dataItem => dataItem.appName === undefined || dataItem.appName === props.appName + (dataItem) => dataItem.appName === undefined || dataItem.appName === props.appName ); const config = (props.config || []).concat(relevantConfig); diff --git a/src/plugins/newsfeed/public/components/newsfeed_header_nav_button.tsx b/src/plugins/newsfeed/public/components/newsfeed_header_nav_button.tsx index fd938e9071074..888b807b5296f 100644 --- a/src/plugins/newsfeed/public/components/newsfeed_header_nav_button.tsx +++ b/src/plugins/newsfeed/public/components/newsfeed_header_nav_button.tsx @@ -48,7 +48,7 @@ export const NewsfeedNavButton = ({ apiFetchResult }: Props) => { setNewsFetchResult(fetchResult); } - const subscription = apiFetchResult.subscribe(res => handleStatusChange(res)); + const subscription = apiFetchResult.subscribe((res) => handleStatusChange(res)); return () => subscription.unsubscribe(); }, [apiFetchResult]); diff --git a/src/plugins/newsfeed/public/lib/api.test.ts b/src/plugins/newsfeed/public/lib/api.test.ts index 5db578f1bd4e9..be4274e8bc054 100644 --- a/src/plugins/newsfeed/public/lib/api.test.ts +++ b/src/plugins/newsfeed/public/lib/api.test.ts @@ -481,9 +481,9 @@ describe('getApi', () => { } as unknown) as HttpSetup; }); - it('creates a result', done => { + it('creates a result', (done) => { mockHttpGet.mockImplementationOnce(() => Promise.resolve({ items: [] })); - getApi(httpMock, configMock, '6.8.2').subscribe(result => { + getApi(httpMock, configMock, '6.8.2').subscribe((result) => { expect(result).toMatchInlineSnapshot(` Object { "error": null, @@ -496,7 +496,7 @@ describe('getApi', () => { }); }); - it('hasNew is true when the service returns hashes not in the cache', done => { + it('hasNew is true when the service returns hashes not in the cache', (done) => { const mockApiItems: ApiItem[] = [ { title: { @@ -528,7 +528,7 @@ describe('getApi', () => { mockHttpGet.mockImplementationOnce(getHttpMockWithItems(mockApiItems)); - getApi(httpMock, configMock, '6.8.2').subscribe(result => { + getApi(httpMock, configMock, '6.8.2').subscribe((result) => { expect(result).toMatchInlineSnapshot(` Object { "error": null, @@ -552,7 +552,7 @@ describe('getApi', () => { }); }); - it('hasNew is false when service returns hashes that are all stored', done => { + it('hasNew is false when service returns hashes that are all stored', (done) => { localStorageGet.throws('Wrong key passed!'); localStorageGet.withArgs(NEWSFEED_HASH_SET_STORAGE_KEY).returns('happyness'); const mockApiItems: ApiItem[] = [ @@ -568,7 +568,7 @@ describe('getApi', () => { }, ]; mockHttpGet.mockImplementationOnce(getHttpMockWithItems(mockApiItems)); - getApi(httpMock, configMock, '6.8.2').subscribe(result => { + getApi(httpMock, configMock, '6.8.2').subscribe((result) => { expect(result).toMatchInlineSnapshot(` Object { "error": null, @@ -592,10 +592,10 @@ describe('getApi', () => { }); }); - it('forwards an error', done => { + it('forwards an error', (done) => { mockHttpGet.mockImplementationOnce((arg1, arg2) => Promise.reject('sorry, try again later!')); - getApi(httpMock, configMock, '6.8.2').subscribe(result => { + getApi(httpMock, configMock, '6.8.2').subscribe((result) => { expect(result).toMatchInlineSnapshot(` Object { "error": "sorry, try again later!", @@ -622,7 +622,7 @@ describe('getApi', () => { }, ]; - it("retries until fetch doesn't error", done => { + it("retries until fetch doesn't error", (done) => { configMock.mainInterval = moment.duration(10); // fast retry for testing mockHttpGet .mockImplementationOnce(() => Promise.reject('Sorry, try again later!')) @@ -632,7 +632,7 @@ describe('getApi', () => { getApi(httpMock, configMock, '6.8.2') .pipe(take(4), toArray()) - .subscribe(result => { + .subscribe((result) => { expect(result).toMatchInlineSnapshot(` Array [ Object { @@ -676,7 +676,7 @@ describe('getApi', () => { }); }); - it("doesn't retry if fetch succeeds", done => { + it("doesn't retry if fetch succeeds", (done) => { configMock.mainInterval = moment.duration(10); // fast retry for testing mockHttpGet.mockImplementation(getHttpMockWithItems(successItems)); diff --git a/src/plugins/newsfeed/public/lib/api.ts b/src/plugins/newsfeed/public/lib/api.ts index 2924f3d340662..ac38e064d2686 100644 --- a/src/plugins/newsfeed/public/lib/api.ts +++ b/src/plugins/newsfeed/public/lib/api.ts @@ -70,7 +70,7 @@ export class NewsfeedApiDriver { old = stored.split(','); } - const newHashes = items.map(i => i.hash); + const newHashes = items.map((i) => i.hash); const updatedHashes = [...new Set(old.concat(newHashes))]; localStorage.setItem(NEWSFEED_HASH_SET_STORAGE_KEY, updatedHashes.join(',')); @@ -178,7 +178,7 @@ export function getApi( filter(() => driver.shouldFetch()), mergeMap(() => driver.fetchNewsfeedItems(http, config.service).pipe( - catchError(err => { + catchError((err) => { window.console.error(err); return Rx.of({ error: err, diff --git a/src/plugins/newsfeed/public/plugin.tsx b/src/plugins/newsfeed/public/plugin.tsx index e61070ab184f3..1a1915ccbed3e 100644 --- a/src/plugins/newsfeed/public/plugin.tsx +++ b/src/plugins/newsfeed/public/plugin.tsx @@ -55,7 +55,7 @@ export class NewsfeedPublicPlugin implements Plugin { const api$ = this.fetchNewsfeed(core); core.chrome.navControls.registerRight({ order: 1000, - mount: target => this.mount(api$, target), + mount: (target) => this.mount(api$, target), }); return {}; diff --git a/src/plugins/region_map/public/__tests__/region_map_visualization.js b/src/plugins/region_map/public/__tests__/region_map_visualization.js index cefef98fae814..3dcfc7c2fc6fa 100644 --- a/src/plugins/region_map/public/__tests__/region_map_visualization.js +++ b/src/plugins/region_map/public/__tests__/region_map_visualization.js @@ -60,7 +60,7 @@ import { getBaseMapsVis } from '../../../maps_legacy/public'; const THRESHOLD = 0.45; const PIXEL_DIFF = 96; -describe('RegionMapsVisualizationTests', function() { +describe('RegionMapsVisualizationTests', function () { let domNode; let RegionMapsVisualization; let vis; @@ -118,7 +118,7 @@ describe('RegionMapsVisualizationTests', function() { }, }, }; - setInjectedVarFunc(injectedVar => { + setInjectedVarFunc((injectedVar) => { switch (injectedVar) { case 'version': return '123'; @@ -154,16 +154,16 @@ describe('RegionMapsVisualizationTests', function() { regionMapVisType = new BaseVisType(createRegionMapTypeDefinition(dependencies)); RegionMapsVisualization = createRegionMapVisualization(dependencies); - ChoroplethLayer.prototype._makeJsonAjaxCall = async function() { + ChoroplethLayer.prototype._makeJsonAjaxCall = async function () { //simulate network call - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => { resolve(worldJson); }, 10); }); }; - getManifestStub = serviceSettings.__debugStubManifestCalls(async url => { + getManifestStub = serviceSettings.__debugStubManifestCalls(async (url) => { //simulate network calls if (url.startsWith('https://foobar')) { return EMS_CATALOGUE; @@ -184,13 +184,13 @@ describe('RegionMapsVisualizationTests', function() { }) ); - afterEach(function() { + afterEach(function () { ChoroplethLayer.prototype._makeJsonAjaxCall = _makeJsonAjaxCallOld; getManifestStub.removeStub(); }); - describe('RegionMapVisualization - basics', function() { - beforeEach(async function() { + describe('RegionMapVisualization - basics', function () { + beforeEach(async function () { setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -228,12 +228,12 @@ describe('RegionMapsVisualizationTests', function() { }; }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('should instantiate at zoom level 2 (may fail in dev env)', async function() { + it('should instantiate at zoom level 2 (may fail in dev env)', async function () { const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); await regionMapsVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -247,7 +247,7 @@ describe('RegionMapsVisualizationTests', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should update after resetting join field', async function() { + it('should update after resetting join field', async function () { const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); await regionMapsVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -273,7 +273,7 @@ describe('RegionMapsVisualizationTests', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should resize (may fail in dev env)', async function() { + it('should resize (may fail in dev env)', async function () { const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); await regionMapsVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -310,7 +310,7 @@ describe('RegionMapsVisualizationTests', function() { expect(mismatchedPixelsAfterSecondResize).to.be.lessThan(PIXEL_DIFF); }); - it('should redo data (may fail in dev env)', async function() { + it('should redo data (may fail in dev env)', async function () { const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); await regionMapsVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -354,7 +354,7 @@ describe('RegionMapsVisualizationTests', function() { expect(mismatchedPixelsAfterDataChangeAndResize).to.be.lessThan(PIXEL_DIFF); }); - it('should redo data and color ramp (may fail in dev env)', async function() { + it('should redo data and color ramp (may fail in dev env)', async function () { const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); await regionMapsVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -380,7 +380,7 @@ describe('RegionMapsVisualizationTests', function() { expect(mismatchedPixelsAfterDataAndColorChange).to.be.lessThan(PIXEL_DIFF); }); - it('should zoom and center elsewhere', async function() { + it('should zoom and center elsewhere', async function () { vis.params.mapZoom = 4; vis.params.mapCenter = [36, -85]; const regionMapsVisualization = new RegionMapsVisualization(domNode, vis); diff --git a/src/plugins/region_map/public/choropleth_layer.js b/src/plugins/region_map/public/choropleth_layer.js index ddaf2db257fba..30fa8b544cdec 100644 --- a/src/plugins/region_map/public/choropleth_layer.js +++ b/src/plugins/region_map/public/choropleth_layer.js @@ -116,7 +116,7 @@ export default class ChoroplethLayer extends KibanaMapLayer { this._loaded = false; this._error = false; this._isJoinValid = false; - this._whenDataLoaded = new Promise(async resolve => { + this._whenDataLoaded = new Promise(async (resolve) => { try { const data = await this._makeJsonAjaxCall(); let featureCollection; @@ -221,7 +221,7 @@ CORS configuration of the server permits requests from the Kibana application on if (!this._showAllShapes) { const featureCollection = { type: 'FeatureCollection', - features: this._sortedFeatures.filter(feature => feature.__kbnJoinedMetric), + features: this._sortedFeatures.filter((feature) => feature.__kbnJoinedMetric), }; this._leafletLayer.addData(featureCollection); } @@ -234,10 +234,7 @@ CORS configuration of the server permits requests from the Kibana application on const { min, max } = getMinMax(this._metrics); this._legendColors = colorUtil.getLegendColors(this._colorRamp); const quantizeDomain = min !== max ? [min, max] : d3.scale.quantize().domain(); - this._legendQuantizer = d3.scale - .quantize() - .domain(quantizeDomain) - .range(this._legendColors); + this._legendQuantizer = d3.scale.quantize().domain(quantizeDomain).range(this._legendColors); } this._boundsOfData = styler.getLeafletBounds(); this.emit('styleChanged', { @@ -250,11 +247,11 @@ CORS configuration of the server permits requests from the Kibana application on } setTooltipFormatter(tooltipFormatter, fieldFormatter, fieldName, metricLabel) { - this._tooltipFormatter = geojsonFeature => { + this._tooltipFormatter = (geojsonFeature) => { if (!this._metrics) { return ''; } - const match = this._metrics.find(bucket => { + const match = this._metrics.find((bucket) => { return ( compareLexicographically(bucket.term, geojsonFeature.properties[this._joinField]) === 0 ); @@ -374,15 +371,13 @@ CORS configuration of the server permits requests from the Kibana application on } const titleText = this._metricTitle; - const $title = $('
') - .addClass('visMapLegend__title') - .text(titleText); + const $title = $('
').addClass('visMapLegend__title').text(titleText); jqueryDiv.append($title); - this._legendColors.forEach(color => { + this._legendColors.forEach((color) => { const labelText = this._legendQuantizer .invertExtent(color) - .map(val => { + .map((val) => { return this._valueFormatter.convert(val); }) .join(' – '); @@ -432,7 +427,7 @@ CORS configuration of the server permits requests from the Kibana application on // eslint-disable-next-line no-undef const boundsOfAllFeatures = new L.LatLngBounds(); return { - leafletStyleFunction: geojsonFeature => { + leafletStyleFunction: (geojsonFeature) => { const match = geojsonFeature.__kbnJoinedMetric; if (!match) { return emptyStyle(); @@ -455,15 +450,15 @@ CORS configuration of the server permits requests from the Kibana application on */ getMismatches: () => { const mismatches = this._metrics.slice(); - this._sortedFeatures.forEach(feature => { + this._sortedFeatures.forEach((feature) => { const index = mismatches.indexOf(feature.__kbnJoinedMetric); if (index >= 0) { mismatches.splice(index, 1); } }); - return mismatches.map(b => b.term); + return mismatches.map((b) => b.term); }, - getLeafletBounds: function() { + getLeafletBounds: function () { return boundsOfAllFeatures.isValid() ? boundsOfAllFeatures : null; }, }; @@ -479,10 +474,7 @@ function compareLexicographically(termA, termB) { function makeColorDarker(color) { const amount = 1.3; //magic number, carry over from earlier - return d3 - .hcl(color) - .darker(amount) - .toString(); + return d3.hcl(color).darker(amount).toString(); } function getMinMax(data) { diff --git a/src/plugins/region_map/public/components/region_map_options.tsx b/src/plugins/region_map/public/components/region_map_options.tsx index 9a6987b981539..be3d7fe86ab3f 100644 --- a/src/plugins/region_map/public/components/region_map_options.tsx +++ b/src/plugins/region_map/public/components/region_map_options.tsx @@ -78,7 +78,7 @@ function RegionMapOptions(props: RegionMapOptionsProps) { if (stateParams.selectedLayer) { setValue( paramName, - stateParams.selectedLayer.fields.find(f => f.name === value) + stateParams.selectedLayer.fields.find((f) => f.name === value) ); } }, diff --git a/src/plugins/region_map/public/region_map_type.js b/src/plugins/region_map/public/region_map_type.js index d29360a9589ab..def95950e6151 100644 --- a/src/plugins/region_map/public/region_map_type.js +++ b/src/plugins/region_map/public/region_map_type.js @@ -54,7 +54,7 @@ provided base maps, or add your own. Darker colors represent higher values.', }, visualization, editorConfig: { - optionsTemplate: props => , + optionsTemplate: (props) => , collections: { colorSchemas: truncatedColorSchemas, vectorLayers: [], @@ -96,7 +96,7 @@ provided base maps, or add your own. Darker colors represent higher values.', }, ]), }, - setup: async vis => { + setup: async (vis) => { const tmsLayers = await serviceSettings.getTMSServices(); vis.type.editorConfig.collections.tmsLayers = tmsLayers; if (!vis.params.wms.selectedTmsLayer && tmsLayers.length) { @@ -113,11 +113,11 @@ provided base maps, or add your own. Darker colors represent higher values.', const newLayers = layers .map(mapToLayerWithId.bind(null, ORIGIN.EMS)) .filter( - layer => !vectorLayers.some(vectorLayer => vectorLayer.layerId === layer.layerId) + (layer) => !vectorLayers.some((vectorLayer) => vectorLayer.layerId === layer.layerId) ); // backfill v1 manifest for now - newLayers.forEach(layer => { + newLayers.forEach((layer) => { if (layer.format === 'geojson') { layer.format = { type: 'geojson', diff --git a/src/plugins/region_map/public/region_map_visualization.js b/src/plugins/region_map/public/region_map_visualization.js index ed6a3ed2c10c8..a95547b1c34cf 100644 --- a/src/plugins/region_map/public/region_map_visualization.js +++ b/src/plugins/region_map/public/region_map_visualization.js @@ -52,7 +52,7 @@ export function createRegionMapVisualization({ if (!this._hasColumns() || !table.rows.length) { results = []; } else { - results = table.rows.map(row => { + results = table.rows.map((row) => { const term = row[termColumn.id]; const value = row[valueColumn.id]; return { term: term, value: value }; @@ -161,9 +161,9 @@ export function createRegionMapVisualization({ ); } - this._choroplethLayer.on('select', event => { + this._choroplethLayer.on('select', (event) => { const { rows, columns } = this._chartData; - const rowIndex = rows.findIndex(row => row[columns[0].id] === event); + const rowIndex = rows.findIndex((row) => row[columns[0].id] === event); this._vis.API.events.filter({ table: this._chartData, column: 0, @@ -172,7 +172,7 @@ export function createRegionMapVisualization({ }); }); - this._choroplethLayer.on('styleChanged', event => { + this._choroplethLayer.on('styleChanged', (event) => { const shouldShowWarning = this._params.isDisplayWarning && uiSettings.get('visualization:regionmap:showWarnings'); if (event.mismatches.length > 0 && shouldShowWarning) { diff --git a/src/plugins/saved_objects/public/finder/saved_object_finder.test.tsx b/src/plugins/saved_objects/public/finder/saved_object_finder.test.tsx index 90212fbe83c10..8a644a718c9d3 100644 --- a/src/plugins/saved_objects/public/finder/saved_object_finder.test.tsx +++ b/src/plugins/saved_objects/public/finder/saved_object_finder.test.tsx @@ -21,7 +21,7 @@ jest.mock('lodash', () => ({ debounce: (fn: any) => fn, })); -const nextTick = () => new Promise(res => process.nextTick(res)); +const nextTick = () => new Promise((res) => process.nextTick(res)); import { EuiEmptyPrompt, @@ -130,10 +130,7 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - wrapper - .find(EuiListGroupItem) - .first() - .simulate('click'); + wrapper.find(EuiListGroupItem).first().simulate('click'); expect(chooseStub.calledWith('1', 'search', `${doc.attributes.title} (Search)`, doc)).toEqual( true ); @@ -469,12 +466,7 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - expect( - wrapper - .find(EuiEmptyPrompt) - .first() - .prop('body') - ).toEqual(noItemsMessage); + expect(wrapper.find(EuiEmptyPrompt).first().prop('body')).toEqual(noItemsMessage); }); describe('pagination', () => { @@ -504,12 +496,7 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - expect( - wrapper - .find(EuiTablePagination) - .first() - .prop('itemsPerPage') - ).toEqual(15); + expect(wrapper.find(EuiTablePagination).first().prop('itemsPerPage')).toEqual(15); expect(wrapper.find(EuiListGroup).children().length).toBe(15); }); @@ -531,10 +518,7 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - wrapper - .find(EuiTablePagination) - .first() - .prop('onChangeItemsPerPage')!(5); + wrapper.find(EuiTablePagination).first().prop('onChangeItemsPerPage')!(5); expect(wrapper.find(EuiListGroup).children().length).toBe(5); }); @@ -556,17 +540,8 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - wrapper - .find(EuiTablePagination) - .first() - .prop('onChangePage')!(1); - expect( - wrapper - .find(EuiListGroup) - .children() - .first() - .key() - ).toBe('15'); + wrapper.find(EuiTablePagination).first().prop('onChangePage')!(1); + expect(wrapper.find(EuiListGroup).children().first().key()).toBe('15'); }); it('should show an ordinary pagination for fixed page sizes', async () => { @@ -587,12 +562,7 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - expect( - wrapper - .find(EuiPagination) - .first() - .prop('pageCount') - ).toEqual(2); + expect(wrapper.find(EuiPagination).first().prop('pageCount')).toEqual(2); expect(wrapper.find(EuiListGroup).children().length).toBe(33); }); @@ -614,17 +584,8 @@ describe('SavedObjectsFinder', () => { wrapper.instance().componentDidMount!(); await nextTick(); - wrapper - .find(EuiPagination) - .first() - .prop('onPageClick')!(1); - expect( - wrapper - .find(EuiListGroup) - .children() - .first() - .key() - ).toBe('33'); + wrapper.find(EuiPagination).first().prop('onPageClick')!(1); + expect(wrapper.find(EuiListGroup).children().first().key()).toBe('33'); }); }); diff --git a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx index 5b5242579c718..9ef4f2fbe7c55 100644 --- a/src/plugins/saved_objects/public/finder/saved_object_finder.tsx +++ b/src/plugins/saved_objects/public/finder/saved_object_finder.tsx @@ -130,7 +130,7 @@ class SavedObjectFinderUi extends React.Component< const metaDataMap = this.getSavedObjectMetaDataMap(); const fields = Object.values(metaDataMap) - .map(metaData => metaData.includeFields || []) + .map((metaData) => metaData.includeFields || []) .reduce((allFields, currentFields) => allFields.concat(currentFields), ['title']); const perPage = this.props.uiSettings.get(LISTING_LIMIT_SETTING); @@ -144,7 +144,7 @@ class SavedObjectFinderUi extends React.Component< defaultSearchOperator: 'AND', }); - resp.savedObjects = resp.savedObjects.filter(savedObject => { + resp.savedObjects = resp.savedObjects.filter((savedObject) => { const metaData = metaDataMap[savedObject.type]; if (metaData.showSavedObject) { return metaData.showSavedObject(savedObject); @@ -163,7 +163,7 @@ class SavedObjectFinderUi extends React.Component< this.setState({ isFetchingItems: false, page: 0, - items: resp.savedObjects.map(savedObject => { + items: resp.savedObjects.map((savedObject) => { const { attributes: { title }, id, @@ -227,7 +227,7 @@ class SavedObjectFinderUi extends React.Component< (this.state.filteredTypes.length === 0 ? this.state.items.length : this.state.items.filter( - item => + (item) => this.state.filteredTypes.length === 0 || this.state.filteredTypes.includes(item.type) ).length) / this.state.perPage ); @@ -259,7 +259,7 @@ class SavedObjectFinderUi extends React.Component< const lastIndex = startIndex + this.state.perPage; return items .filter( - item => + (item) => this.state.filteredTypes.length === 0 || this.state.filteredTypes.includes(item.type) ) .slice(startIndex, lastIndex); @@ -276,10 +276,10 @@ class SavedObjectFinderUi extends React.Component< private getAvailableSavedObjectMetaData() { const typesInItems = new Set(); - this.state.items.forEach(item => { + this.state.items.forEach((item) => { typesInItems.add(item.type); }); - return this.props.savedObjectMetaData.filter(metaData => typesInItems.has(metaData.type)); + return this.props.savedObjectMetaData.filter((metaData) => typesInItems.has(metaData.type)); } private getSortOptions() { @@ -351,7 +351,7 @@ class SavedObjectFinderUi extends React.Component< })} fullWidth value={this.state.query} - onChange={e => { + onChange={(e) => { this.setState( { query: e.target.value, @@ -422,7 +422,7 @@ class SavedObjectFinderUi extends React.Component< > ( + items={this.props.savedObjectMetaData.map((metaData) => ( { this.setState(({ filteredTypes }) => ({ filteredTypes: filteredTypes.includes(metaData.type) - ? filteredTypes.filter(t => t !== metaData.type) + ? filteredTypes.filter((t) => t !== metaData.type) : [...filteredTypes, metaData.type], page: 0, })); @@ -466,9 +466,9 @@ class SavedObjectFinderUi extends React.Component< )} {items.length > 0 ? ( - {items.map(item => { + {items.map((item) => { const currentSavedObjectMetaData = savedObjectMetaData.find( - metaData => metaData.type === item.type + (metaData) => metaData.type === item.type )!; const fullName = currentSavedObjectMetaData.getTooltipForSavedObject ? currentSavedObjectMetaData.getTooltipForSavedObject(item.savedObject) @@ -505,7 +505,7 @@ class SavedObjectFinderUi extends React.Component< { + onPageClick={(page) => { this.setState({ page, }); @@ -515,12 +515,12 @@ class SavedObjectFinderUi extends React.Component< { + onChangePage={(page) => { this.setState({ page, }); }} - onChangeItemsPerPage={perPage => { + onChangeItemsPerPage={(perPage) => { this.setState({ perPage, }); diff --git a/src/plugins/saved_objects/public/save_modal/saved_object_save_modal_origin.tsx b/src/plugins/saved_objects/public/save_modal/saved_object_save_modal_origin.tsx index 734ebb1095d84..63863b0826f11 100644 --- a/src/plugins/saved_objects/public/save_modal/saved_object_save_modal_origin.tsx +++ b/src/plugins/saved_objects/public/save_modal/saved_object_save_modal_origin.tsx @@ -71,7 +71,7 @@ export function SavedObjectSaveModalOrigin(props: OriginSaveModalProps) { { + onChange={(event) => { setReturnToOriginMode(event.target.checked); }} label={ diff --git a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts index 0f1c08930db5e..4fb900baa4434 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/find_object_by_title.ts @@ -49,5 +49,7 @@ export async function findObjectByTitle( searchFields: ['title'], fields: ['title'], }); - return response.savedObjects.find(obj => obj.get('title').toLowerCase() === title.toLowerCase()); + return response.savedObjects.find( + (obj) => obj.get('title').toLowerCase() === title.toLowerCase() + ); } diff --git a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts index 66587a5d068c9..53abe55ef0ea7 100644 --- a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts +++ b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts @@ -122,13 +122,17 @@ describe('Saved Object', () => { it('when false does not request overwrite', () => { stubESResponse(getMockedDocResponse('myId')); - return createInitializedSavedObject({ type: 'dashboard', id: 'myId' }).then(savedObject => { - stubSavedObjectsClientCreate({ id: 'myId' } as SimpleSavedObject); - - return savedObject.save({ confirmOverwrite: false }).then(() => { - expect(startMock.overlays.openModal).not.toHaveBeenCalled(); - }); - }); + return createInitializedSavedObject({ type: 'dashboard', id: 'myId' }).then( + (savedObject) => { + stubSavedObjectsClientCreate({ id: 'myId' } as SimpleSavedObject< + SavedObjectAttributes + >); + + return savedObject.save({ confirmOverwrite: false }).then(() => { + expect(startMock.overlays.openModal).not.toHaveBeenCalled(); + }); + } + ); }); }); @@ -136,17 +140,19 @@ describe('Saved Object', () => { it('as true creates a copy on save success', () => { stubESResponse(getMockedDocResponse('myId')); - return createInitializedSavedObject({ type: 'dashboard', id: 'myId' }).then(savedObject => { - stubSavedObjectsClientCreate({ - type: 'dashboard', - id: 'newUniqueId', - } as SimpleSavedObject); - savedObject.copyOnSave = true; + return createInitializedSavedObject({ type: 'dashboard', id: 'myId' }).then( + (savedObject) => { + stubSavedObjectsClientCreate({ + type: 'dashboard', + id: 'newUniqueId', + } as SimpleSavedObject); + savedObject.copyOnSave = true; - return savedObject.save(saveOptionsMock).then(id => { - expect(id).toBe('newUniqueId'); - }); - }); + return savedObject.save(saveOptionsMock).then((id) => { + expect(id).toBe('newUniqueId'); + }); + } + ); }); it('as true does not create a copy when save fails', () => { @@ -154,7 +160,7 @@ describe('Saved Object', () => { stubESResponse(getMockedDocResponse(originalId)); return createInitializedSavedObject({ type: 'dashboard', id: originalId }).then( - savedObject => { + (savedObject) => { stubSavedObjectsClientCreate('simulated error', false); savedObject.copyOnSave = true; @@ -174,14 +180,14 @@ describe('Saved Object', () => { const myId = 'myId'; stubESResponse(getMockedDocResponse(myId)); - return createInitializedSavedObject({ type: 'dashboard', id: myId }).then(savedObject => { + return createInitializedSavedObject({ type: 'dashboard', id: myId }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.id).toBe(myId); return Bluebird.resolve({ id: myId }); }); savedObject.copyOnSave = false; - return savedObject.save(saveOptionsMock).then(id => { + return savedObject.save(saveOptionsMock).then((id) => { expect(id).toBe(myId); }); }); @@ -189,7 +195,7 @@ describe('Saved Object', () => { }); it('returns id from server on success', () => { - return createInitializedSavedObject({ type: 'dashboard' }).then(savedObject => { + return createInitializedSavedObject({ type: 'dashboard' }).then((savedObject) => { stubESResponse(getMockedDocResponse('myId')); stubSavedObjectsClientCreate({ type: 'dashboard', @@ -197,7 +203,7 @@ describe('Saved Object', () => { _version: 'foo', } as SimpleSavedObject); - return savedObject.save(saveOptionsMock).then(id => { + return savedObject.save(saveOptionsMock).then((id) => { expect(id).toBe('myId'); }); }); @@ -208,7 +214,7 @@ describe('Saved Object', () => { const id = 'id'; stubESResponse(getMockedDocResponse(id)); - return createInitializedSavedObject({ type: 'dashboard', id }).then(savedObject => { + return createInitializedSavedObject({ type: 'dashboard', id }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.isSaving).toBe(true); return Bluebird.resolve({ @@ -227,7 +233,7 @@ describe('Saved Object', () => { it('on failure', () => { stubESResponse(getMockedDocResponse('id')); - return createInitializedSavedObject({ type: 'dashboard' }).then(savedObject => { + return createInitializedSavedObject({ type: 'dashboard' }).then((savedObject) => { savedObjectsClientStub.create = jest.fn().mockImplementation(() => { expect(savedObject.isSaving).toBe(true); return Bluebird.reject(''); @@ -257,7 +263,7 @@ describe('Saved Object', () => { return { attributes, references }; }; return createInitializedSavedObject({ type: 'dashboard', extractReferences }).then( - savedObject => { + (savedObject) => { stubSavedObjectsClientCreate({ id, _version: 'foo', @@ -281,7 +287,7 @@ describe('Saved Object', () => { const id = '123'; stubESResponse(getMockedDocResponse(id)); return createInitializedSavedObject({ type: 'dashboard', searchSource: true }).then( - savedObject => { + (savedObject) => { stubSavedObjectsClientCreate({ id, _version: '2', @@ -322,7 +328,7 @@ describe('Saved Object', () => { const id = '123'; stubESResponse(getMockedDocResponse(id)); return createInitializedSavedObject({ type: 'dashboard', searchSource: true }).then( - savedObject => { + (savedObject) => { stubSavedObjectsClientCreate({ id, _version: '2', @@ -361,7 +367,7 @@ describe('Saved Object', () => { const id = '123'; stubESResponse(getMockedDocResponse(id)); return createInitializedSavedObject({ type: 'dashboard', searchSource: true }).then( - savedObject => { + (savedObject) => { stubSavedObjectsClientCreate({ id, _version: '2', @@ -406,7 +412,7 @@ describe('Saved Object', () => { describe('applyESResp', () => { it('throws error if not found', () => { - return createInitializedSavedObject({ type: 'dashboard' }).then(savedObject => { + return createInitializedSavedObject({ type: 'dashboard' }).then((savedObject) => { const response = { _source: {} }; try { savedObject.applyESResp(response); @@ -701,7 +707,7 @@ describe('Saved Object', () => { }); describe('type', () => { - it('that is not specified throws an error', done => { + it('that is not specified throws an error', (done) => { const config = {}; const savedObject = new SavedObjectClass(config); @@ -738,7 +744,7 @@ describe('Saved Object', () => { } function expectDefaultApplied(config: SavedObjectConfig) { - return createInitializedSavedObject(config).then(savedObject => { + return createInitializedSavedObject(config).then((savedObject) => { expect(savedObject.defaults).toBe(config.defaults); }); } @@ -783,7 +789,7 @@ describe('Saved Object', () => { stubESResponse(mockDocResponse); - return createInitializedSavedObject(config).then(savedObject => { + return createInitializedSavedObject(config).then((savedObject) => { expect(!!savedObject._source).toBe(true); expect(savedObject.defaults).toBe(config.defaults); expect(savedObject._source.overwriteMe).toBe(serverValue); diff --git a/src/plugins/saved_objects/public/saved_object/saved_object_loader.ts b/src/plugins/saved_objects/public/saved_object/saved_object_loader.ts index e83f5c0b6bafb..53ef1f3f04ad9 100644 --- a/src/plugins/saved_objects/public/saved_object/saved_object_loader.ts +++ b/src/plugins/saved_objects/public/saved_object/saved_object_loader.ts @@ -69,7 +69,7 @@ export class SavedObjectLoader { async delete(ids: string | string[]) { const idsUsed = !Array.isArray(ids) ? [ids] : ids; - const deletions = idsUsed.map(id => { + const deletions = idsUsed.map((id) => { // @ts-ignore const savedObject = new this.Class(id); return savedObject.delete(); @@ -83,11 +83,11 @@ export class SavedObjectLoader { coreNavLinks .getAll() .filter( - link => + (link) => link.linkToLastSubUrl && - idsUsed.find(deletedId => link.url && link.url.includes(deletedId)) !== undefined + idsUsed.find((deletedId) => link.url && link.url.includes(deletedId)) !== undefined ) - .forEach(link => coreNavLinks.update(link.id, { url: link.baseUrl })); + .forEach((link) => coreNavLinks.update(link.id, { url: link.baseUrl })); } /** @@ -133,19 +133,19 @@ export class SavedObjectLoader { defaultSearchOperator: 'AND', fields, } as SavedObjectsFindOptions) - .then(resp => { + .then((resp) => { return { total: resp.total, - hits: resp.savedObjects.map(savedObject => this.mapSavedObjectApiHits(savedObject)), + hits: resp.savedObjects.map((savedObject) => this.mapSavedObjectApiHits(savedObject)), }; }); } find(search: string = '', size: number = 100) { - return this.findAll(search, size).then(resp => { + return this.findAll(search, size).then((resp) => { return { total: resp.total, - hits: resp.hits.filter(savedObject => !savedObject.error), + hits: resp.hits.filter((savedObject) => !savedObject.error), }; }); } diff --git a/src/plugins/saved_objects_management/public/lib/create_field_list.ts b/src/plugins/saved_objects_management/public/lib/create_field_list.ts index d66d0b0a28844..5f424751dd58e 100644 --- a/src/plugins/saved_objects_management/public/lib/create_field_list.ts +++ b/src/plugins/saved_objects_management/public/lib/create_field_list.ts @@ -89,7 +89,7 @@ const createFields = (key: string, value: any, parents: string[] = []): ObjectFi return [field]; }; -const addFieldsFromClass = function( +const addFieldsFromClass = function ( Class: { mapping: Record; searchSource: any }, fields: ObjectField[] ) { diff --git a/src/plugins/saved_objects_management/public/lib/extract_export_details.ts b/src/plugins/saved_objects_management/public/lib/extract_export_details.ts index fdd72aece06bc..bde2b8d1d3daa 100644 --- a/src/plugins/saved_objects_management/public/lib/extract_export_details.ts +++ b/src/plugins/saved_objects_management/public/lib/extract_export_details.ts @@ -22,15 +22,15 @@ export async function extractExportDetails( ): Promise { const reader = new FileReader(); const content = await new Promise((resolve, reject) => { - reader.addEventListener('loadend', e => { + reader.addEventListener('loadend', (e) => { resolve((e as any).target.result); }); - reader.addEventListener('error', e => { + reader.addEventListener('error', (e) => { reject(e); }); reader.readAsText(blob, 'utf-8'); }); - const lines = content.split('\n').filter(l => l.length > 0); + const lines = content.split('\n').filter((l) => l.length > 0); const maybeDetails = JSON.parse(lines[lines.length - 1]); if (isExportDetails(maybeDetails)) { return maybeDetails; diff --git a/src/plugins/saved_objects_management/public/lib/import_legacy_file.ts b/src/plugins/saved_objects_management/public/lib/import_legacy_file.ts index 0d86866fa3c1b..17214c9309924 100644 --- a/src/plugins/saved_objects_management/public/lib/import_legacy_file.ts +++ b/src/plugins/saved_objects_management/public/lib/import_legacy_file.ts @@ -20,7 +20,7 @@ export async function importLegacyFile(file: File) { return new Promise((resolve, reject) => { const fr = new FileReader(); - fr.onload = event => { + fr.onload = (event) => { const result = event.target!.result as string; try { resolve(JSON.parse(result)); diff --git a/src/plugins/saved_objects_management/public/lib/process_import_response.ts b/src/plugins/saved_objects_management/public/lib/process_import_response.ts index cfb2eb29e7885..4725000aa9d55 100644 --- a/src/plugins/saved_objects_management/public/lib/process_import_response.ts +++ b/src/plugins/saved_objects_management/public/lib/process_import_response.ts @@ -60,7 +60,7 @@ export function processImportResponse( continue; } // Currently only supports resolving references on index patterns - const indexPatternRefs = error.references.filter(ref => ref.type === 'index-pattern'); + const indexPatternRefs = error.references.filter((ref) => ref.type === 'index-pattern'); for (const missingReference of indexPatternRefs) { const conflict = unmatchedReferences.get( `${missingReference.type}:${missingReference.id}` @@ -81,7 +81,7 @@ export function processImportResponse( // returned errors of type missing_references. status: unmatchedReferences.size === 0 && - !failedImports.some(issue => issue.error.type === 'conflict') + !failedImports.some((issue) => issue.error.type === 'conflict') ? 'success' : 'idle', importCount: response.successCount, diff --git a/src/plugins/saved_objects_management/public/lib/resolve_import_errors.ts b/src/plugins/saved_objects_management/public/lib/resolve_import_errors.ts index 0aea7114bad1c..ea29cc4884d00 100644 --- a/src/plugins/saved_objects_management/public/lib/resolve_import_errors.ts +++ b/src/plugins/saved_objects_management/public/lib/resolve_import_errors.ts @@ -65,7 +65,7 @@ function mapImportFailureToRetryObject({ if (failure.error.type === 'missing_references') { const objReplaceReferences = replaceReferencesCache.get(`${failure.obj.type}:${failure.obj.id}`) || []; - const indexPatternRefs = failure.error.references.filter(obj => obj.type === 'index-pattern'); + const indexPatternRefs = failure.error.references.filter((obj) => obj.type === 'index-pattern'); for (const reference of indexPatternRefs) { for (const unmatchedReference of unmatchedReferences) { const hasNewValue = !!unmatchedReference.newIndexPatternId; @@ -133,7 +133,9 @@ export async function resolveImportErrors({ // Loop until all issues are resolved while ( - importFailures.some(failure => ['conflict', 'missing_references'].includes(failure.error.type)) + importFailures.some((failure) => + ['conflict', 'missing_references'].includes(failure.error.type) + ) ) { // Ask for overwrites if (!isOverwriteAllChecked) { @@ -149,12 +151,14 @@ export async function resolveImportErrors({ } // Build retries array - const retries = importFailures.map(callMapImportFailure).filter(obj => !!obj) as RetryObject[]; + const retries = importFailures + .map(callMapImportFailure) + .filter((obj) => !!obj) as RetryObject[]; for (const { error, obj } of importFailures) { if (error.type !== 'missing_references') { continue; } - if (!retries.some(retryObj => retryObj.type === obj.type && retryObj.id === obj.id)) { + if (!retries.some((retryObj) => retryObj.type === obj.type && retryObj.id === obj.id)) { continue; } for (const { type, id } of error.blocking || []) { diff --git a/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.ts b/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.ts index 8da8a5b1cebbc..952e9628d2846 100644 --- a/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.ts +++ b/src/plugins/saved_objects_management/public/lib/resolve_saved_objects.ts @@ -31,7 +31,7 @@ import { type SavedObjectsRawDoc = Record; async function getSavedObject(doc: SavedObjectsRawDoc, services: SavedObjectLoader[]) { - const service = services.find(s => s.type === doc._type); + const service = services.find((s) => s.type === doc._type); if (!service) { return; } @@ -160,7 +160,7 @@ function groupByType(docs: SavedObjectsRawDoc[]): Record(list: T[], op: (item: T) => R) { - return await Promise.all(list.map(item => op(item))); + return await Promise.all(list.map((item) => op(item))); } export async function resolveIndexPatternConflicts( @@ -233,7 +233,7 @@ export async function resolveIndexPatternConflicts( export async function saveObjects(objs: SavedObject[], overwriteAll: boolean) { let importCount = 0; - await awaitEachItemInParallel(objs, async obj => { + await awaitEachItemInParallel(objs, async (obj) => { if (await saveObject(obj, overwriteAll)) { importCount++; } @@ -252,7 +252,7 @@ export async function resolveSavedSearches( overwriteAll: boolean ) { let importCount = 0; - await awaitEachItemInParallel(savedSearches, async searchDoc => { + await awaitEachItemInParallel(savedSearches, async (searchDoc) => { const obj = await getSavedObject(searchDoc, services); if (!obj) { // Just ignore? @@ -279,7 +279,7 @@ export async function resolveSavedObjects( let importedObjectCount = 0; const failedImports: any[] = []; // Start with the index patterns since everything is dependent on them - await awaitEachItemInParallel(docTypes.indexPatterns, async indexPatternDoc => { + await awaitEachItemInParallel(docTypes.indexPatterns, async (indexPatternDoc) => { try { const importedIndexPatternId = await importIndexPattern( indexPatternDoc, @@ -310,7 +310,7 @@ export async function resolveSavedObjects( // likely that these saved objects will work once resaved so keep them around to resave them. const conflictedSavedObjectsLinkedToSavedSearches: any[] = []; - await awaitEachItemInParallel(docTypes.searches, async searchDoc => { + await awaitEachItemInParallel(docTypes.searches, async (searchDoc) => { const obj = await getSavedObject(searchDoc, services); try { @@ -330,7 +330,7 @@ export async function resolveSavedObjects( } }); - await awaitEachItemInParallel(docTypes.other, async otherDoc => { + await awaitEachItemInParallel(docTypes.other, async (otherDoc) => { const obj = await getSavedObject(otherDoc, services); try { diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/field.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/components/field.tsx index afed6b492dc91..fd7967f4128c3 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/field.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/field.tsx @@ -92,7 +92,7 @@ export class Field extends PureComponent { name={name} id={this.fieldId} value={currentValue} - onChange={e => this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled} data-test-subj={`savedObjects-editField-${name}`} /> @@ -110,7 +110,7 @@ export class Field extends PureComponent { ) } checked={!!currentValue} - onChange={e => this.onFieldChange(e.target.checked)} + onChange={(e) => this.onFieldChange(e.target.checked)} disabled={disabled} data-test-subj={`savedObjects-editField-${name}`} /> @@ -148,7 +148,7 @@ export class Field extends PureComponent { id={this.fieldId} name={name} value={currentValue} - onChange={e => this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled} data-test-subj={`savedObjects-editField-${name}`} /> diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx index 878399f86421e..d273ffb4c1052 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx @@ -75,7 +75,7 @@ export class Form extends Component { const isValid = this.isFormValid(); return ( - {fields.map(field => ( + {fields.map((field) => ( { isFormValid() { const { fieldStates } = this.state; - return !Object.values(fieldStates).some(state => state.invalid === true); + return !Object.values(fieldStates).some((state) => state.invalid === true); } onCancel = () => { @@ -161,7 +161,7 @@ export class Form extends Component { }); const source = cloneDeep(object.attributes as any); - fields.forEach(field => { + fields.forEach((field) => { let value = fieldStates[field.name]?.value ?? field.value; if (field.type === 'array' && typeof value === 'string') { diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/saved_object_view.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/saved_object_view.tsx index f714970a5cac3..83644e6404c81 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/saved_object_view.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/saved_object_view.tsx @@ -67,7 +67,7 @@ export class SavedObjectEdition extends Component< componentDidMount() { const { id, savedObjectsClient } = this.props; const { type } = this.state; - savedObjectsClient.get(type, id).then(object => { + savedObjectsClient.get(type, id).then((object) => { this.setState({ object, }); diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.test.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.test.tsx index c915a8a2be8f8..e3bb53f9e48df 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.test.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.test.tsx @@ -78,7 +78,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -89,7 +89,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -102,7 +102,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -130,7 +130,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -184,7 +184,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -219,7 +219,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -239,7 +239,7 @@ describe('Flyout', () => { .find('EuiButton[data-test-subj="importSavedObjectsConfirmBtn"]') .simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(resolveImportErrorsMock).toMatchSnapshot(); }); @@ -247,7 +247,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -278,7 +278,7 @@ describe('Flyout', () => { .find('EuiButton[data-test-subj="importSavedObjectsConfirmBtn"]') .simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(component.state('failedImports')).toEqual([ { @@ -422,7 +422,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -432,9 +432,9 @@ describe('Flyout', () => { expect(importLegacyFileMock).toHaveBeenCalledWith(legacyMockFile); // Remove the last element from data since it should be filtered out expect(resolveSavedObjectsMock).toHaveBeenCalledWith( - mockData.slice(0, 2).map(doc => ({ ...doc, _migrationVersion: {} })), + mockData.slice(0, 2).map((doc) => ({ ...doc, _migrationVersion: {} })), true, - defaultProps.serviceRegistry.all().map(s => s.service), + defaultProps.serviceRegistry.all().map((s) => s.service), defaultProps.indexPatterns, defaultProps.overlays.openConfirm ); @@ -477,7 +477,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -497,7 +497,7 @@ describe('Flyout', () => { .find('EuiButton[data-test-subj="importSavedObjectsConfirmBtn"]') .simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(resolveIndexPatternConflictsMock).toHaveBeenCalledWith( component.instance().resolutions, mockConflictedIndexPatterns, @@ -513,7 +513,7 @@ describe('Flyout', () => { ); expect(resolveSavedSearchesMock).toHaveBeenCalledWith( mockConflictedSearchDocs, - defaultProps.serviceRegistry.all().map(s => s.service), + defaultProps.serviceRegistry.all().map((s) => s.service), defaultProps.indexPatterns, true ); @@ -523,7 +523,7 @@ describe('Flyout', () => { const component = shallowRender(defaultProps); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -542,7 +542,7 @@ describe('Flyout', () => { .find('EuiButton[data-test-subj="importSavedObjectsConfirmBtn"]') .simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(component.state('error')).toEqual('foobar'); expect(component.find('EuiFlyoutBody EuiCallOut')).toMatchSnapshot(); diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.tsx index fbcfeafe291a3..6e7397d1058bf 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/flyout.tsx @@ -137,7 +137,7 @@ export class Flyout extends Component { }; changeOverwriteAll = () => { - this.setState(state => ({ + this.setState((state) => ({ isOverwriteAllChecked: !state.isOverwriteAllChecked, })); }; @@ -196,7 +196,7 @@ export class Flyout extends Component { getConflictResolutions = async (objects: any[]) => { const resolutions: Record = {}; for (const { type, id, title } of objects) { - const overwrite = await new Promise(resolve => { + const overwrite = await new Promise((resolve) => { this.setState({ conflictingRecord: { id, @@ -277,8 +277,8 @@ export class Flyout extends Component { } contents = contents - .filter(content => allowedTypes.includes(content._type)) - .map(doc => ({ + .filter((content) => allowedTypes.includes(content._type)) + .map((doc) => ({ ...doc, // The server assumes that documents with no migrationVersion are up to date. // That assumption enables Kibana and other API consumers to not have to build @@ -297,7 +297,7 @@ export class Flyout extends Component { } = await resolveSavedObjects( contents, isOverwriteAllChecked, - serviceRegistry.all().map(e => e.service), + serviceRegistry.all().map((e) => e.service), indexPatterns, overlays.openConfirm ); @@ -417,7 +417,7 @@ export class Flyout extends Component { }); importCount += await resolveSavedSearches( conflictedSearchDocs!, - serviceRegistry.all().map(e => e.service), + serviceRegistry.all().map((e) => e.service), indexPatterns, isOverwriteAllChecked ); @@ -446,9 +446,9 @@ export class Flyout extends Component { onIndexChanged = (id: string, e: any) => { const value = e.target.value; - this.setState(state => { + this.setState((state) => { const conflictIndex = state.unmatchedReferences?.findIndex( - conflict => conflict.existingIndexPatternId === id + (conflict) => conflict.existingIndexPatternId === id ); if (conflictIndex === undefined || conflictIndex === -1) { return state; @@ -529,7 +529,7 @@ export class Flyout extends Component { ), render: (id: string) => { const options = this.state.indexPatterns!.map( - indexPattern => + (indexPattern) => ({ text: indexPattern.title, value: indexPattern.id, @@ -545,7 +545,7 @@ export class Flyout extends Component { return ( this.onIndexChanged(id, e)} + onChange={(e) => this.onIndexChanged(id, e)} options={options} /> ); @@ -646,7 +646,7 @@ export class Flyout extends Component { {failedImports .map(({ error, obj }) => { if (error.type === 'missing_references') { - return error.references.map(reference => { + return error.references.map((reference) => { return i18n.translate( 'savedObjectsManagement.objectsTable.flyout.importFailedMissingReference', { diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.test.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.test.tsx index b3372ccb6fda5..5ee70e73c873b 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.test.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.test.tsx @@ -90,7 +90,7 @@ describe('Relationships', () => { expect(component.find('EuiLoadingKibana').length).toBe(1); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -157,7 +157,7 @@ describe('Relationships', () => { expect(component.find('EuiLoadingKibana').length).toBe(1); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -224,7 +224,7 @@ describe('Relationships', () => { expect(component.find('EuiLoadingKibana').length).toBe(1); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -291,7 +291,7 @@ describe('Relationships', () => { expect(component.find('EuiLoadingKibana').length).toBe(1); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -328,7 +328,7 @@ describe('Relationships', () => { const component = shallowWithI18nProvider(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.tsx index d9e39f31d181a..cc654f9717bd6 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/relationships.tsx @@ -235,7 +235,7 @@ export class Relationships extends Component [ + relationships.map((relationship) => [ relationship.type, { value: relationship.type, diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/components/table.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/components/table.tsx index 5b574e4b3d331..51e7525d0e00a 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/components/table.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/components/table.tsx @@ -111,13 +111,13 @@ export class Table extends PureComponent { }; toggleExportPopoverVisibility = () => { - this.setState(state => ({ + this.setState((state) => ({ isExportPopoverOpen: !state.isExportPopoverOpen, })); }; toggleIsIncludeReferencesDeepChecked = () => { - this.setState(state => ({ + this.setState((state) => ({ isIncludeReferencesDeepChecked: !state.isIncludeReferencesDeepChecked, })); }; @@ -241,8 +241,8 @@ export class Table extends PureComponent { ), type: 'icon', icon: 'inspect', - onClick: object => goInspectObject(object), - available: object => !!object.meta.editUrl, + onClick: (object) => goInspectObject(object), + available: (object) => !!object.meta.editUrl, 'data-test-subj': 'savedObjectsTableAction-inspect', }, { @@ -259,10 +259,10 @@ export class Table extends PureComponent { ), type: 'icon', icon: 'kqlSelector', - onClick: object => onShowRelationships(object), + onClick: (object) => onShowRelationships(object), 'data-test-subj': 'savedObjectsTableAction-relationships', }, - ...actionRegistry.getAll().map(action => { + ...actionRegistry.getAll().map((action) => { return { ...action.euiAction, 'data-test-subj': `savedObjectsTableAction-${action.id}`, @@ -390,7 +390,7 @@ export class Table extends PureComponent { pagination={pagination} selection={selection} onChange={onTableChange} - rowProps={item => ({ + rowProps={(item) => ({ 'data-test-subj': `savedObjectsTableRow row-${item.id}`, })} /> diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.test.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.test.tsx index fc01e558f5020..b46bc8dd1b4ee 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.test.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.test.tsx @@ -209,7 +209,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender({ perPageConfig: 15 }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -223,7 +223,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender({ perPageConfig: 15 }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -237,7 +237,7 @@ describe('SavedObjectsTable', () => { { id: '3', type: 'dashboard' }, ] as SavedObjectWithMetadata[]; - const mockSavedObjects = mockSelectedSavedObjects.map(obj => ({ + const mockSavedObjects = mockSelectedSavedObjects.map((obj) => ({ _id: obj.id, _source: {}, })); @@ -252,7 +252,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender({ savedObjectsClient: mockSavedObjectsClient }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -273,7 +273,7 @@ describe('SavedObjectsTable', () => { { id: '3', type: 'dashboard' }, ] as SavedObjectWithMetadata[]; - const mockSavedObjects = mockSelectedSavedObjects.map(obj => ({ + const mockSavedObjects = mockSelectedSavedObjects.map((obj) => ({ _id: obj.id, _source: {}, })); @@ -294,7 +294,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender({ savedObjectsClient: mockSavedObjectsClient }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -316,7 +316,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -330,7 +330,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -360,7 +360,7 @@ describe('SavedObjectsTable', () => { }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -388,7 +388,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -402,7 +402,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -418,7 +418,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -431,7 +431,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -470,7 +470,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -494,7 +494,7 @@ describe('SavedObjectsTable', () => { ] as SavedObjectWithMetadata[]; // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -512,7 +512,7 @@ describe('SavedObjectsTable', () => { { id: '3', type: 'dashboard' }, ] as SavedObjectWithMetadata[]; - const mockSavedObjects = mockSelectedSavedObjects.map(obj => ({ + const mockSavedObjects = mockSelectedSavedObjects.map((obj) => ({ id: obj.id, type: obj.type, source: {}, @@ -529,7 +529,7 @@ describe('SavedObjectsTable', () => { const component = shallowRender({ savedObjectsClient: mockSavedObjectsClient }); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx index 0ed6a49275f67..d9b856a79b496 100644 --- a/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx +++ b/src/plugins/saved_objects_management/public/management_section/objects_table/saved_objects_table.tsx @@ -163,7 +163,9 @@ export class SavedObjectsTable extends Component !visibleTypes || visibleTypes.includes(type)); + const filteredTypes = allowedTypes.filter( + (type) => !visibleTypes || visibleTypes.includes(type) + ); // These are the saved objects visible in the table. const filteredSavedObjectCounts = await getSavedObjectCounts( @@ -175,7 +177,7 @@ export class SavedObjectsTable extends Component = {}; - Object.keys(filteredSavedObjectCounts).forEach(id => { + Object.keys(filteredSavedObjectCounts).forEach((id) => { // Add this type as a bulk-export option. exportAllOptions.push({ id, @@ -190,7 +192,7 @@ export class SavedObjectsTable extends Component ({ + this.setState((state) => ({ ...state, savedObjectCounts, exportAllOptions, @@ -218,7 +220,7 @@ export class SavedObjectsTable extends Component !visibleTypes || visibleTypes.includes(type)), + type: allowedTypes.filter((type) => !visibleTypes || visibleTypes.includes(type)), }; if (findOptions.type.length > 1) { findOptions.sortField = 'type'; @@ -312,7 +314,7 @@ export class SavedObjectsTable extends Component { const { selectedSavedObjects } = this.state; const { notifications, http } = this.props; - const objectsToExport = selectedSavedObjects.map(obj => ({ id: obj.id, type: obj.type })); + const objectsToExport = selectedSavedObjects.map((obj) => ({ id: obj.id, type: obj.type })); let blob; try { @@ -418,13 +420,13 @@ export class SavedObjectsTable extends Component object.type === 'index-pattern'); + const indexPatterns = selectedSavedObjects.filter((object) => object.type === 'index-pattern'); if (indexPatterns.length) { await this.props.indexPatterns.clearCache(); } const objects = await savedObjectsClient.bulkGet(selectedSavedObjects); - const deletes = objects.savedObjects.map(object => + const deletes = objects.savedObjects.map((object) => savedObjectsClient.delete(object.type, object.id) ); await Promise.all(deletes); @@ -592,7 +594,7 @@ export class SavedObjectsTable extends Component { - this.setState(state => ({ + this.setState((state) => ({ isIncludeReferencesDeepChecked: !state.isIncludeReferencesDeepChecked, })); }; @@ -641,7 +643,7 @@ export class SavedObjectsTable extends Component { + onChange={(optionId) => { const newExportAllSelectedOptions = { ...exportAllSelectedOptions, ...{ @@ -713,7 +715,7 @@ export class SavedObjectsTable extends Component ({ + const filterOptions = allowedTypes.map((type) => ({ value: type, name: type, view: `${type} (${savedObjectCounts[type] || 0})`, diff --git a/src/plugins/saved_objects_management/public/management_section/saved_objects_table_page.tsx b/src/plugins/saved_objects_management/public/management_section/saved_objects_table_page.tsx index 7660d17f91c5b..4e8418d7406b5 100644 --- a/src/plugins/saved_objects_management/public/management_section/saved_objects_table_page.tsx +++ b/src/plugins/saved_objects_management/public/management_section/saved_objects_table_page.tsx @@ -70,7 +70,7 @@ const SavedObjectsTablePage = ({ notifications={coreStart.notifications} applications={coreStart.application} perPageConfig={itemsPerPage} - goInspectObject={savedObject => { + goInspectObject={(savedObject) => { const { editUrl } = savedObject.meta; if (editUrl) { // previously, kbnUrl.change(object.meta.editUrl); was used. @@ -80,7 +80,7 @@ const SavedObjectsTablePage = ({ window.location.hash = editUrl; } }} - canGoInApp={savedObject => { + canGoInApp={(savedObject) => { const { inAppUrl } = savedObject.meta; return inAppUrl ? get(capabilities, inAppUrl.uiCapabilitiesPath) : false; }} diff --git a/src/plugins/saved_objects_management/public/plugin.ts b/src/plugins/saved_objects_management/public/plugin.ts index b0c6b1952a2a5..1d765c70edb97 100644 --- a/src/plugins/saved_objects_management/public/plugin.ts +++ b/src/plugins/saved_objects_management/public/plugin.ts @@ -94,7 +94,7 @@ export class SavedObjectsManagementPlugin defaultMessage: 'Saved Objects', }), order: 1, - mount: async mountParams => { + mount: async (mountParams) => { const { mountManagementSection } = await import('./management_section'); return mountManagementSection({ core, diff --git a/src/plugins/saved_objects_management/public/services/action_service.ts b/src/plugins/saved_objects_management/public/services/action_service.ts index 2b0b4cf5431e5..b5d8cbd2652e5 100644 --- a/src/plugins/saved_objects_management/public/services/action_service.ts +++ b/src/plugins/saved_objects_management/public/services/action_service.ts @@ -42,7 +42,7 @@ export class SavedObjectsManagementActionService { setup(): SavedObjectsManagementActionServiceSetup { return { - register: action => { + register: (action) => { if (this.actions.has(action.id)) { throw new Error(`Saved Objects Management Action with id '${action.id}' already exists`); } @@ -53,7 +53,7 @@ export class SavedObjectsManagementActionService { start(): SavedObjectsManagementActionServiceStart { return { - has: actionId => this.actions.has(actionId), + has: (actionId) => this.actions.has(actionId), getAll: () => [...this.actions.values()], }; } diff --git a/src/plugins/saved_objects_management/public/services/types.ts b/src/plugins/saved_objects_management/public/services/types.ts index 92b0ea638b9bb..c2f807f63b1b9 100644 --- a/src/plugins/saved_objects_management/public/services/types.ts +++ b/src/plugins/saved_objects_management/public/services/types.ts @@ -58,6 +58,6 @@ export abstract class SavedObjectsManagementAction { protected finish() { this.record = null; - this.callbacks.forEach(callback => callback()); + this.callbacks.forEach((callback) => callback()); } } diff --git a/src/plugins/saved_objects_management/server/lib/find_all.test.ts b/src/plugins/saved_objects_management/server/lib/find_all.test.ts index 98e669c093178..2515d11f6d4bb 100644 --- a/src/plugins/saved_objects_management/server/lib/find_all.test.ts +++ b/src/plugins/saved_objects_management/server/lib/find_all.test.ts @@ -90,6 +90,6 @@ describe('findAll', () => { page: 3, }); - expect(results).toEqual(times(6, num => createObj(num + 1))); + expect(results).toEqual(times(6, (num) => createObj(num + 1))); }); }); diff --git a/src/plugins/saved_objects_management/server/lib/find_relationships.test.ts b/src/plugins/saved_objects_management/server/lib/find_relationships.test.ts index 18846eeebdfb7..2c8997c9af21a 100644 --- a/src/plugins/saved_objects_management/server/lib/find_relationships.test.ts +++ b/src/plugins/saved_objects_management/server/lib/find_relationships.test.ts @@ -99,7 +99,7 @@ describe('findRelationships', () => { expect(savedObjectsClient.bulkGet).toHaveBeenCalledTimes(1); expect(savedObjectsClient.bulkGet).toHaveBeenCalledWith( - references.map(ref => ({ + references.map((ref) => ({ id: ref.id, type: ref.type, })) diff --git a/src/plugins/saved_objects_management/server/lib/find_relationships.ts b/src/plugins/saved_objects_management/server/lib/find_relationships.ts index cca8831afd16c..46a270a33cbaf 100644 --- a/src/plugins/saved_objects_management/server/lib/find_relationships.ts +++ b/src/plugins/saved_objects_management/server/lib/find_relationships.ts @@ -41,7 +41,7 @@ export async function findRelationships({ // Use a map to avoid duplicates, it does happen but have a different "name" in the reference const referencedToBulkGetOpts = new Map( - references.map(ref => [`${ref.type}:${ref.id}`, { id: ref.id, type: ref.type }]) + references.map((ref) => [`${ref.type}:${ref.id}`, { id: ref.id, type: ref.type }]) ); const [childReferencesResponse, parentReferencesResponse] = await Promise.all([ @@ -56,10 +56,10 @@ export async function findRelationships({ ]); return childReferencesResponse.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) .map( - obj => + (obj) => ({ ...obj, relationship: 'child', @@ -67,10 +67,10 @@ export async function findRelationships({ ) .concat( parentReferencesResponse.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) .map( - obj => + (obj) => ({ ...obj, relationship: 'parent', diff --git a/src/plugins/saved_objects_management/server/routes/find.ts b/src/plugins/saved_objects_management/server/routes/find.ts index a74c92ba6161f..0d88e6ec3f3b5 100644 --- a/src/plugins/saved_objects_management/server/routes/find.ts +++ b/src/plugins/saved_objects_management/server/routes/find.ts @@ -58,12 +58,12 @@ export const registerFindRoute = ( const includedFields = Array.isArray(req.query.fields) ? req.query.fields : [req.query.fields]; - const importAndExportableTypes = searchTypes.filter(type => + const importAndExportableTypes = searchTypes.filter((type) => managementService.isImportAndExportable(type) ); const searchFields = new Set(); - importAndExportableTypes.forEach(type => { + importAndExportableTypes.forEach((type) => { const searchField = managementService.getDefaultSearchField(type); if (searchField) { searchFields.add(searchField); @@ -77,8 +77,8 @@ export const registerFindRoute = ( }); const enhancedSavedObjects = findResponse.saved_objects - .map(so => injectMetaAttributes(so, managementService)) - .map(obj => { + .map((so) => injectMetaAttributes(so, managementService)) + .map((obj) => { const result = { ...obj, attributes: {} as Record }; for (const field of includedFields) { result.attributes[field] = obj.attributes[field]; diff --git a/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts b/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts index ab5bec6678946..2d15dde48a4e9 100644 --- a/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts +++ b/src/plugins/saved_objects_management/server/routes/get_allowed_types.ts @@ -28,7 +28,7 @@ export const registerGetAllowedTypesRoute = (router: IRouter) => { async (context, req, res) => { const allowedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(type => type.name); + .map((type) => type.name); return res.ok({ body: { diff --git a/src/plugins/saved_objects_management/server/routes/scroll_export.ts b/src/plugins/saved_objects_management/server/routes/scroll_export.ts index cda2770234911..88a0064ccdc72 100644 --- a/src/plugins/saved_objects_management/server/routes/scroll_export.ts +++ b/src/plugins/saved_objects_management/server/routes/scroll_export.ts @@ -39,7 +39,7 @@ export const registerScrollForExportRoute = (router: IRouter) => { }); return res.ok({ - body: objects.map(hit => { + body: objects.map((hit) => { return { _id: hit.id, _source: hit.attributes, diff --git a/src/plugins/share/public/components/share_context_menu.tsx b/src/plugins/share/public/components/share_context_menu.tsx index 1669791da23c2..c12e9dabd1938 100644 --- a/src/plugins/share/public/components/share_context_menu.tsx +++ b/src/plugins/share/public/components/share_context_menu.tsx @@ -151,7 +151,7 @@ export class ShareContextMenu extends Component { } return -1; }) - .map(menuItem => { + .map((menuItem) => { menuItem['data-test-subj'] = `sharePanel-${menuItem.name.replace(' ', '')}`; delete menuItem.sortOrder; return menuItem; diff --git a/src/plugins/share/public/components/url_panel_content.tsx b/src/plugins/share/public/components/url_panel_content.tsx index 804b606696a83..2ece2052c4b95 100644 --- a/src/plugins/share/public/components/url_panel_content.tsx +++ b/src/plugins/share/public/components/url_panel_content.tsx @@ -336,9 +336,7 @@ export class UrlPanelContent extends Component { defaultMessage="Can't share as saved object until the {objectType} has been saved." values={{ objectType: this.props.objectType }} /> - ) : ( - undefined - ); + ) : undefined; return ( - Array.from(this.shareMenuProviders.values()).flatMap(shareActionProvider => + Array.from(this.shareMenuProviders.values()).flatMap((shareActionProvider) => shareActionProvider.getShareMenuItems(context) ), }; diff --git a/src/plugins/share/public/services/short_url_redirect_app.test.ts b/src/plugins/share/public/services/short_url_redirect_app.test.ts index 206e637451ec0..a6b0fd2d6177e 100644 --- a/src/plugins/share/public/services/short_url_redirect_app.test.ts +++ b/src/plugins/share/public/services/short_url_redirect_app.test.ts @@ -21,7 +21,7 @@ import { createShortUrlRedirectApp } from './short_url_redirect_app'; import { coreMock } from '../../../../core/public/mocks'; import { hashUrl } from '../../../kibana_utils/public'; -jest.mock('../../../kibana_utils/public', () => ({ hashUrl: jest.fn(x => `${x}/hashed`) })); +jest.mock('../../../kibana_utils/public', () => ({ hashUrl: jest.fn((x) => `${x}/hashed`) })); describe('short_url_redirect_app', () => { beforeEach(() => { diff --git a/src/plugins/share/server/routes/get.ts b/src/plugins/share/server/routes/get.ts index d6b191341dbe1..ff13a63d8efd3 100644 --- a/src/plugins/share/server/routes/get.ts +++ b/src/plugins/share/server/routes/get.ts @@ -40,7 +40,7 @@ export const createGetterRoute = ({ params: schema.object({ urlId: schema.string() }), }, }, - router.handleLegacyErrors(async function(context, request, response) { + router.handleLegacyErrors(async function (context, request, response) { const url = await shortUrlLookup.getUrl(request.params.urlId, { savedObjects: context.core.savedObjects.client, }); diff --git a/src/plugins/share/server/routes/goto.ts b/src/plugins/share/server/routes/goto.ts index 0dbddd6552c36..193f2acb87c95 100644 --- a/src/plugins/share/server/routes/goto.ts +++ b/src/plugins/share/server/routes/goto.ts @@ -41,7 +41,7 @@ export const createGotoRoute = ({ params: schema.object({ urlId: schema.string() }), }, }, - router.handleLegacyErrors(async function(context, request, response) { + router.handleLegacyErrors(async function (context, request, response) { const url = await shortUrlLookup.getUrl(request.params.urlId, { savedObjects: context.core.savedObjects.client, }); @@ -52,7 +52,7 @@ export const createGotoRoute = ({ if (!stateStoreInSessionStorage) { const basePath = http.basePath.get(request); - const prependedUrl = modifyUrl(url, parts => { + const prependedUrl = modifyUrl(url, (parts) => { if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) { parts.pathname = `${basePath}${parts.pathname}`; } diff --git a/src/plugins/share/server/routes/lib/short_url_assert_valid.test.ts b/src/plugins/share/server/routes/lib/short_url_assert_valid.test.ts index f83073e6aefe9..02a5e123b6481 100644 --- a/src/plugins/share/server/routes/lib/short_url_assert_valid.test.ts +++ b/src/plugins/share/server/routes/lib/short_url_assert_valid.test.ts @@ -55,7 +55,7 @@ describe('shortUrlAssertValid()', () => { '/app/some?with=query#and-a-hash', ]; - valid.forEach(url => { + valid.forEach((url) => { it(`allows ${url}`, () => { shortUrlAssertValid(url); }); diff --git a/src/plugins/share/server/routes/lib/short_url_lookup.ts b/src/plugins/share/server/routes/lib/short_url_lookup.ts index 65fa33a940fac..a858b7c54ac4f 100644 --- a/src/plugins/share/server/routes/lib/short_url_lookup.ts +++ b/src/plugins/share/server/routes/lib/short_url_lookup.ts @@ -53,10 +53,7 @@ export function shortUrlLookupProvider({ logger }: { logger: Logger }): ShortUrl return { async generateUrlId(url, { savedObjects }) { - const id = crypto - .createHash('md5') - .update(url) - .digest('hex'); + const id = crypto.createHash('md5').update(url).digest('hex'); const { isConflictError } = savedObjects.errors; try { diff --git a/src/plugins/share/server/routes/shorten_url.ts b/src/plugins/share/server/routes/shorten_url.ts index 41570f8a5f453..959826f323dce 100644 --- a/src/plugins/share/server/routes/shorten_url.ts +++ b/src/plugins/share/server/routes/shorten_url.ts @@ -38,7 +38,7 @@ export const createShortenUrlRoute = ({ body: schema.object({ url: schema.string() }), }, }, - router.handleLegacyErrors(async function(context, request, response) { + router.handleLegacyErrors(async function (context, request, response) { shortUrlAssertValid(request.body.url); const urlId = await shortUrlLookup.generateUrlId(request.body.url, { savedObjects: context.core.savedObjects.client, diff --git a/src/plugins/share/server/saved_objects/kibana_app_migration.ts b/src/plugins/share/server/saved_objects/kibana_app_migration.ts index 526d25deb3cd2..413b48d7fa6de 100644 --- a/src/plugins/share/server/saved_objects/kibana_app_migration.ts +++ b/src/plugins/share/server/saved_objects/kibana_app_migration.ts @@ -26,7 +26,7 @@ import { SavedObjectMigrationFn } from 'kibana/server'; * without loading the page again. * @param doc */ -export const migrateLegacyKibanaAppShortUrls: SavedObjectMigrationFn = doc => ({ +export const migrateLegacyKibanaAppShortUrls: SavedObjectMigrationFn = (doc) => ({ ...doc, attributes: { ...doc.attributes, diff --git a/src/plugins/telemetry/common/telemetry_config/get_telemetry_opt_in.test.ts b/src/plugins/telemetry/common/telemetry_config/get_telemetry_opt_in.test.ts index da44abd35517c..abf6aec6e2661 100644 --- a/src/plugins/telemetry/common/telemetry_config/get_telemetry_opt_in.test.ts +++ b/src/plugins/telemetry/common/telemetry_config/get_telemetry_opt_in.test.ts @@ -83,22 +83,22 @@ describe('getTelemetryOptIn', () => { { lastVersionChecked: 'beta', currentKibanaVersion: '8.0.0', result: null }, { lastVersionChecked: 'beta', currentKibanaVersion: 'beta', result: false }, { lastVersionChecked: 'BETA', currentKibanaVersion: 'beta', result: null }, - ].map(el => ({ ...el, enabled: false })); + ].map((el) => ({ ...el, enabled: false })); // build a table of tests with version checks, with results for enabled true/null/undefined - const EnabledTrueVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map(el => ({ + const EnabledTrueVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map((el) => ({ ...el, enabled: true, result: true, })); - const EnabledNullVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map(el => ({ + const EnabledNullVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map((el) => ({ ...el, enabled: null, result: null, })); - const EnabledUndefinedVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map(el => ({ + const EnabledUndefinedVersionChecks: VersionCheckTable = EnabledFalseVersionChecks.map((el) => ({ ...el, enabled: undefined, result: null, diff --git a/src/plugins/telemetry/public/components/opt_in_banner.test.tsx b/src/plugins/telemetry/public/components/opt_in_banner.test.tsx index 0dc76d65f8879..097c17862c668 100644 --- a/src/plugins/telemetry/public/components/opt_in_banner.test.tsx +++ b/src/plugins/telemetry/public/components/opt_in_banner.test.tsx @@ -30,7 +30,7 @@ describe('OptInDetailsComponent', () => { const onClick = jest.fn(); const component = shallowWithIntl(); - const enableButton = component.findWhere(n => { + const enableButton = component.findWhere((n) => { const props = n.props(); return n.type() === EuiButton && props['data-test-subj'] === 'enable'; }); @@ -48,7 +48,7 @@ describe('OptInDetailsComponent', () => { const onClick = jest.fn(); const component = shallowWithIntl(); - const disableButton = component.findWhere(n => { + const disableButton = component.findWhere((n) => { const props = n.props(); return n.type() === EuiButton && props['data-test-subj'] === 'disable'; }); diff --git a/src/plugins/telemetry/public/components/opted_in_notice_banner.test.tsx b/src/plugins/telemetry/public/components/opted_in_notice_banner.test.tsx index f004f20a4a1c4..f4e0287cab93f 100644 --- a/src/plugins/telemetry/public/components/opted_in_notice_banner.test.tsx +++ b/src/plugins/telemetry/public/components/opted_in_notice_banner.test.tsx @@ -30,7 +30,7 @@ describe('OptInDetailsComponent', () => { const onLinkClick = jest.fn(); const component = shallowWithIntl(); - const button = component.findWhere(n => n.type() === EuiButton); + const button = component.findWhere((n) => n.type() === EuiButton); if (!button) { throw new Error(`Couldn't find any buttons in opt-in notice`); diff --git a/src/plugins/telemetry/public/mocks.ts b/src/plugins/telemetry/public/mocks.ts index fd88f520205f5..9ec4a3ae86cc7 100644 --- a/src/plugins/telemetry/public/mocks.ts +++ b/src/plugins/telemetry/public/mocks.ts @@ -59,7 +59,7 @@ export function mockTelemetryService({ }); const originalReportOptInStatus = telemetryService['reportOptInStatus']; - telemetryService['reportOptInStatus'] = jest.fn().mockImplementation(optInPayload => { + telemetryService['reportOptInStatus'] = jest.fn().mockImplementation((optInPayload) => { return originalReportOptInStatus(optInPayload); // Actually calling the original method }); diff --git a/src/plugins/telemetry/public/services/telemetry_sender.ts b/src/plugins/telemetry/public/services/telemetry_sender.ts index fec2db0506eb7..b28482c14482e 100644 --- a/src/plugins/telemetry/public/services/telemetry_sender.ts +++ b/src/plugins/telemetry/public/services/telemetry_sender.ts @@ -73,7 +73,7 @@ export class TelemetrySender { const clusters: string[] = [].concat(telemetryData); await Promise.all( clusters.map( - async cluster => + async (cluster) => await fetch(telemetryUrl, { method: 'POST', headers: { diff --git a/src/plugins/telemetry/server/collectors/usage/ensure_deep_object.ts b/src/plugins/telemetry/server/collectors/usage/ensure_deep_object.ts index 3b7a9355da746..be44ccd8b5816 100644 --- a/src/plugins/telemetry/server/collectors/usage/ensure_deep_object.ts +++ b/src/plugins/telemetry/server/collectors/usage/ensure_deep_object.ts @@ -39,7 +39,7 @@ export function ensureDeepObject(obj: any): any { } if (Array.isArray(obj)) { - return obj.map(item => ensureDeepObject(item)); + return obj.map((item) => ensureDeepObject(item)); } return Object.keys(obj).reduce((fullObject, propertyKey) => { diff --git a/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.test.ts b/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.test.ts index 9dc19f34f7ebe..662385a6af546 100644 --- a/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.test.ts +++ b/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.test.ts @@ -69,7 +69,7 @@ describe('telemetry_usage_collector', () => { // delete temp files afterAll(() => { - allFiles.forEach(path => { + allFiles.forEach((path) => { try { unlinkSync(path); } catch (err) { @@ -81,7 +81,7 @@ describe('telemetry_usage_collector', () => { describe('isFileReadable', () => { test('returns `undefined` no file is readable', async () => { expect(isFileReadable('')).toBe(false); - invalidFiles.forEach(path => { + invalidFiles.forEach((path) => { expect(isFileReadable(path)).toBe(false); }); }); diff --git a/src/plugins/telemetry/server/fetcher.ts b/src/plugins/telemetry/server/fetcher.ts index be85824855ff3..39a2b5854e62c 100644 --- a/src/plugins/telemetry/server/fetcher.ts +++ b/src/plugins/telemetry/server/fetcher.ts @@ -178,9 +178,7 @@ export class FetcherTask { private async fetchTelemetry() { return await this.telemetryCollectionManager!.getStats({ unencrypted: false, - start: moment() - .subtract(20, 'minutes') - .toISOString(), + start: moment().subtract(20, 'minutes').toISOString(), end: moment().toISOString(), }); } diff --git a/src/plugins/telemetry/server/plugin.ts b/src/plugins/telemetry/server/plugin.ts index 05fcb385429c5..8ae63682413e5 100644 --- a/src/plugins/telemetry/server/plugin.ts +++ b/src/plugins/telemetry/server/plugin.ts @@ -93,7 +93,7 @@ export class TelemetryPlugin implements Plugin { telemetryCollectionManager, }); - this.registerMappings(opts => savedObjects.registerType(opts)); + this.registerMappings((opts) => savedObjects.registerType(opts)); this.registerUsageCollectors(usageCollection); } diff --git a/src/plugins/telemetry/server/routes/telemetry_opt_in.ts b/src/plugins/telemetry/server/routes/telemetry_opt_in.ts index 4ed5dbf251275..7dd15f73029e7 100644 --- a/src/plugins/telemetry/server/routes/telemetry_opt_in.ts +++ b/src/plugins/telemetry/server/routes/telemetry_opt_in.ts @@ -83,9 +83,7 @@ export function registerTelemetryOptInRoutes({ } const statsGetterConfig: StatsGetterConfig = { - start: moment() - .subtract(20, 'minutes') - .toISOString(), + start: moment().subtract(20, 'minutes').toISOString(), end: moment().toISOString(), unencrypted: false, }; diff --git a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts index 3263c6d49523c..4bb26ea3abc76 100644 --- a/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts +++ b/src/plugins/telemetry/server/routes/telemetry_opt_in_stats.ts @@ -70,9 +70,7 @@ export function registerTelemetryOptInStatsRoutes( const unencrypted = req.body.unencrypted; const statsGetterConfig: StatsGetterConfig = { - start: moment() - .subtract(20, 'minutes') - .toISOString(), + start: moment().subtract(20, 'minutes').toISOString(), end: moment().toISOString(), unencrypted, request: req, diff --git a/src/plugins/telemetry/server/routes/telemetry_usage_stats.ts b/src/plugins/telemetry/server/routes/telemetry_usage_stats.ts index 15d4c0ca2fa55..d47a2a0780efe 100644 --- a/src/plugins/telemetry/server/routes/telemetry_usage_stats.ts +++ b/src/plugins/telemetry/server/routes/telemetry_usage_stats.ts @@ -26,7 +26,7 @@ import { StatsGetterConfig, } from 'src/plugins/telemetry_collection_manager/server'; -const validate: TypeOptions['validate'] = value => { +const validate: TypeOptions['validate'] = (value) => { if (!moment(value).isValid()) { return `${value} is not a valid date`; } diff --git a/src/plugins/telemetry/server/telemetry_collection/__tests__/get_local_stats.js b/src/plugins/telemetry/server/telemetry_collection/__tests__/get_local_stats.js index ac3c5307adcf6..29076537e9ae8 100644 --- a/src/plugins/telemetry/server/telemetry_collection/__tests__/get_local_stats.js +++ b/src/plugins/telemetry/server/telemetry_collection/__tests__/get_local_stats.js @@ -28,7 +28,7 @@ import { getLocalStats, handleLocalStats } from '../get_local_stats'; const mockUsageCollection = (kibanaUsage = {}) => ({ bulkFetch: () => kibanaUsage, - toObject: data => data, + toObject: (data) => data, }); const getMockServer = (getCluster = sinon.stub()) => ({ diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_license.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_license.ts index ad0666c7ad153..0ba6fcc154d8b 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_license.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_license.ts @@ -43,7 +43,7 @@ function fetchLicense(callCluster: APICaller, local: boolean) { */ async function getLicenseFromLocalOrMaster(callCluster: APICaller) { // Fetching the local license is cheaper than getting it from the master and good enough - const { license } = await fetchLicense(callCluster, true).catch(async err => { + const { license } = await fetchLicense(callCluster, true).catch(async (err) => { if (cachedLicense) { try { // Fallback to the master node's license info diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts index 19d5c2970361c..b77d01c5b431f 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts @@ -66,7 +66,7 @@ export const getLocalStats: StatsGetter<{}, TelemetryLocalStats> = async ( const { callCluster, usageCollection } = config; return await Promise.all( - clustersDetails.map(async clustersDetail => { + clustersDetails.map(async (clustersDetail) => { const [clusterInfo, clusterStats, kibana] = await Promise.all([ getClusterInfo(callCluster), // cluster info getClusterStats(callCluster), // cluster stats (not to be confused with cluster _state_) diff --git a/src/plugins/telemetry_collection_manager/server/plugin.ts b/src/plugins/telemetry_collection_manager/server/plugin.ts index 0b57fae83c0fb..c3db0ca39e6ac 100644 --- a/src/plugins/telemetry_collection_manager/server/plugin.ts +++ b/src/plugins/telemetry_collection_manager/server/plugin.ts @@ -240,7 +240,7 @@ export class TelemetryCollectionManagerPlugin collection.licenseGetter(clustersDetails, statsCollectionConfig, context), ]); - return stats.map(stat => { + return stats.map((stat) => { const license = licenses[stat.cluster_uuid]; return { ...(license ? { license } : {}), diff --git a/src/plugins/telemetry_management_section/public/components/telemetry_management_section.tsx b/src/plugins/telemetry_management_section/public/components/telemetry_management_section.tsx index 7982a958f5aba..db104e9c7baab 100644 --- a/src/plugins/telemetry_management_section/public/components/telemetry_management_section.tsx +++ b/src/plugins/telemetry_management_section/public/components/telemetry_management_section.tsx @@ -71,7 +71,7 @@ export class TelemetryManagementSection extends Component { const searchTerm = (query.text || '').toLowerCase(); const searchTermMatches = this.props.telemetryService.getCanChangeOptInStatus() && - SEARCH_TERMS.some(term => term.indexOf(searchTerm) >= 0); + SEARCH_TERMS.some((term) => term.indexOf(searchTerm) >= 0); if (searchTermMatches !== this.state.queryMatches) { this.setState( diff --git a/src/plugins/testbed/server/index.ts b/src/plugins/testbed/server/index.ts index 96d5612508a96..31f5d433c66ab 100644 --- a/src/plugins/testbed/server/index.ts +++ b/src/plugins/testbed/server/index.ts @@ -79,7 +79,7 @@ class Plugin { return { data$: this.initializerContext.config.create().pipe( - map(configValue => { + map((configValue) => { this.log.debug(`I've got value from my config: ${configValue.secret}`); return `Some exposed data derived from config: ${configValue.secret}`; }) diff --git a/src/plugins/tile_map/public/__tests__/coordinate_maps_visualization.js b/src/plugins/tile_map/public/__tests__/coordinate_maps_visualization.js index 303ce67be7102..11c8fb9c00ef1 100644 --- a/src/plugins/tile_map/public/__tests__/coordinate_maps_visualization.js +++ b/src/plugins/tile_map/public/__tests__/coordinate_maps_visualization.js @@ -78,7 +78,7 @@ mockRawData(); const THRESHOLD = 0.45; const PIXEL_DIFF = 64; -describe('CoordinateMapsVisualizationTest', function() { +describe('CoordinateMapsVisualizationTest', function () { let domNode; let CoordinateMapsVisualization; let vis; @@ -105,7 +105,7 @@ describe('CoordinateMapsVisualizationTest', function() { }, }, }; - setInjectedVarFunc(injectedVar => { + setInjectedVarFunc((injectedVar) => { switch (injectedVar) { case 'version': return '123'; @@ -139,7 +139,7 @@ describe('CoordinateMapsVisualizationTest', function() { CoordinateMapsVisualization = createTileMapVisualization(dependencies); - getManifestStub = serviceSettings.__debugStubManifestCalls(async url => { + getManifestStub = serviceSettings.__debugStubManifestCalls(async (url) => { //simulate network calls if (url.startsWith('https://foobar')) { return EMS_CATALOGUE; @@ -164,8 +164,8 @@ describe('CoordinateMapsVisualizationTest', function() { getManifestStub.removeStub(); }); - describe('CoordinateMapsVisualization - basics', function() { - beforeEach(async function() { + describe('CoordinateMapsVisualization - basics', function () { + beforeEach(async function () { setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -192,15 +192,15 @@ describe('CoordinateMapsVisualizationTest', function() { }, }; const mockAggs = { - byType: type => { - return mockAggs.aggs.find(agg => agg.type.type === type); + byType: (type) => { + return mockAggs.aggs.find((agg) => agg.type.type === type); }, aggs: [ { type: { type: 'metrics', }, - fieldFormatter: x => { + fieldFormatter: (x) => { return x; }, makeLabel: () => { @@ -215,18 +215,18 @@ describe('CoordinateMapsVisualizationTest', function() { }, ], }; - vis.getAggConfig = function() { + vis.getAggConfig = function () { return mockAggs; }; vis.aggs = mockAggs; }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('should initialize OK (may fail in dev env)', async function() { + it('should initialize OK (may fail in dev env)', async function () { const coordinateMapVisualization = new CoordinateMapsVisualization(domNode, vis); await coordinateMapVisualization.render(dummyESResponse, vis.params, { resize: false, @@ -241,7 +241,7 @@ describe('CoordinateMapsVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should toggle to Heatmap OK', async function() { + it('should toggle to Heatmap OK', async function () { const coordinateMapVisualization = new CoordinateMapsVisualization(domNode, vis); await coordinateMapVisualization.render(dummyESResponse, vis.params, { resize: false, @@ -265,7 +265,7 @@ describe('CoordinateMapsVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should toggle back&forth OK between mapTypes (may fail in dev env)', async function() { + it('should toggle back&forth OK between mapTypes (may fail in dev env)', async function () { const coordinateMapVisualization = new CoordinateMapsVisualization(domNode, vis); await coordinateMapVisualization.render(dummyESResponse, vis.params, { resize: false, @@ -298,7 +298,7 @@ describe('CoordinateMapsVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should toggle to different color schema ok (may fail in dev env)', async function() { + it('should toggle to different color schema ok (may fail in dev env)', async function () { const coordinateMapVisualization = new CoordinateMapsVisualization(domNode, vis); await coordinateMapVisualization.render(dummyESResponse, vis.params, { resize: false, @@ -322,7 +322,7 @@ describe('CoordinateMapsVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('should toggle to different color schema and maptypes ok', async function() { + it('should toggle to different color schema and maptypes ok', async function () { const coordinateMapVisualization = new CoordinateMapsVisualization(domNode, vis); await coordinateMapVisualization.render(dummyESResponse, vis.params, { resize: false, diff --git a/src/plugins/tile_map/public/__tests__/geohash_layer.js b/src/plugins/tile_map/public/__tests__/geohash_layer.js index a288e78ef00c1..000a0e16dd16b 100644 --- a/src/plugins/tile_map/public/__tests__/geohash_layer.js +++ b/src/plugins/tile_map/public/__tests__/geohash_layer.js @@ -27,7 +27,7 @@ import GeoHashSampleData from './dummy_es_response.json'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { KibanaMap } from '../../../maps_legacy/public/map/kibana_map'; -describe('geohash_layer', function() { +describe('geohash_layer', function () { let domNode; let expectCanvas; let kibanaMap; @@ -53,8 +53,8 @@ describe('geohash_layer', function() { document.body.removeChild(expectCanvas); } - describe('GeohashGridLayer', function() { - beforeEach(async function() { + describe('GeohashGridLayer', function () { + beforeEach(async function () { setupDOM(); imageComparator = new ImageComparator(); kibanaMap = new KibanaMap(domNode, { @@ -68,7 +68,7 @@ describe('geohash_layer', function() { }); }); - afterEach(function() { + afterEach(function () { // return; kibanaMap.destroy(); teardownDOM(); @@ -95,8 +95,8 @@ describe('geohash_layer', function() { // }, // expected: heatmapPng // } - ].forEach(function(test) { - it(`${test.options.mapType} (may fail in dev env)`, async function() { + ].forEach(function (test) { + it(`${test.options.mapType} (may fail in dev env)`, async function () { const geohashGridOptions = test.options; const geohashLayer = new GeohashLayer( GeoHashSampleData.featureCollection, @@ -116,7 +116,7 @@ describe('geohash_layer', function() { }); }); - it('should not throw when fitting on empty-data layer', function() { + it('should not throw when fitting on empty-data layer', function () { const geohashLayer = new GeohashLayer( { type: 'FeatureCollection', @@ -134,7 +134,7 @@ describe('geohash_layer', function() { }).to.not.throwException(); }); - it('should not throw when resizing to 0 on heatmap', function() { + it('should not throw when resizing to 0 on heatmap', function () { const geohashGridOptions = { mapType: 'Heatmap', heatmap: { diff --git a/src/plugins/tile_map/public/css_filters.js b/src/plugins/tile_map/public/css_filters.js index 63d6a358059b3..b41ea6955663b 100644 --- a/src/plugins/tile_map/public/css_filters.js +++ b/src/plugins/tile_map/public/css_filters.js @@ -22,20 +22,18 @@ import _ from 'lodash'; /** * just a place to put feature detection checks */ -export const supportsCssFilters = (function() { +export const supportsCssFilters = (function () { const e = document.createElement('img'); const rules = ['webkitFilter', 'mozFilter', 'msFilter', 'filter']; const test = 'grayscale(1)'; - rules.forEach(function(rule) { + rules.forEach(function (rule) { e.style[rule] = test; }); document.body.appendChild(e); const styles = window.getComputedStyle(e); - const can = _(styles) - .pick(rules) - .includes(test); + const can = _(styles).pick(rules).includes(test); document.body.removeChild(e); return can; diff --git a/src/plugins/tile_map/public/geohash_layer.js b/src/plugins/tile_map/public/geohash_layer.js index dbe64871265b1..ca2f49a1f31e0 100644 --- a/src/plugins/tile_map/public/geohash_layer.js +++ b/src/plugins/tile_map/public/geohash_layer.js @@ -109,8 +109,8 @@ export class GeohashLayer extends KibanaMapLayer { ); } - this._geohashMarkers.on('showTooltip', event => this.emit('showTooltip', event)); - this._geohashMarkers.on('hideTooltip', event => this.emit('hideTooltip', event)); + this._geohashMarkers.on('showTooltip', (event) => this.emit('showTooltip', event)); + this._geohashMarkers.on('hideTooltip', (event) => this.emit('hideTooltip', event)); this._leafletLayer = this._geohashMarkers.getLeafletLayer(); } diff --git a/src/plugins/tile_map/public/markers/geohash_grid.js b/src/plugins/tile_map/public/markers/geohash_grid.js index 0150f6d2c54c9..46e7987c601f5 100644 --- a/src/plugins/tile_map/public/markers/geohash_grid.js +++ b/src/plugins/tile_map/public/markers/geohash_grid.js @@ -22,7 +22,7 @@ import { L } from '../../../maps_legacy/public'; export class GeohashGridMarkers extends ScaledCirclesMarkers { getMarkerFunction() { - return function(feature) { + return function (feature) { const geohashRect = feature.properties.geohash_meta.rectangle; // get bounds from northEast[3] and southWest[1] // corners in geohash rectangle diff --git a/src/plugins/tile_map/public/markers/heatmap.js b/src/plugins/tile_map/public/markers/heatmap.js index ed9dbccbfbcde..f2d014797bce0 100644 --- a/src/plugins/tile_map/public/markers/heatmap.js +++ b/src/plugins/tile_map/public/markers/heatmap.js @@ -39,10 +39,10 @@ export class HeatmapMarkers extends EventEmitter { this._zoom = zoom; this._disableTooltips = false; this._getLatLng = _.memoize( - function(feature) { + function (feature) { return L.latLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0]); }, - function(feature) { + function (feature) { // turn coords into a string for the memoize cache return [feature.geometry.coordinates[1], feature.geometry.coordinates[0]].join(','); } @@ -74,7 +74,7 @@ export class HeatmapMarkers extends EventEmitter { } _addTooltips() { - const mouseMoveLocation = e => { + const mouseMoveLocation = (e) => { if (!this._geojsonFeatureCollection.features.length || this._disableTooltips) { this.emit('hideTooltip'); return; @@ -118,7 +118,7 @@ export class HeatmapMarkers extends EventEmitter { _.reduce( this._geojsonFeatureCollection.features, - function(distance, feature) { + function (distance, feature) { const featureLatLng = self._getLatLng(feature); const dist = latLng.distanceTo(featureLatLng); @@ -171,11 +171,7 @@ export class HeatmapMarkers extends EventEmitter { showTip = true; } - d3.scale - .pow() - .exponent(0.2) - .domain([1, 18]) - .range([1500000, 50]); + d3.scale.pow().exponent(0.2).domain([1, 18]).range([1500000, 50]); return showTip; } } @@ -188,7 +184,7 @@ export class HeatmapMarkers extends EventEmitter { * @return {Array} */ function dataToHeatArray(featureCollection, max) { - return featureCollection.features.map(feature => { + return featureCollection.features.map((feature) => { const lat = feature.geometry.coordinates[1]; const lng = feature.geometry.coordinates[0]; // show bucket value normalized to max value diff --git a/src/plugins/tile_map/public/markers/scaled_circles.js b/src/plugins/tile_map/public/markers/scaled_circles.js index 028d3de515ae7..cb111107f6fe3 100644 --- a/src/plugins/tile_map/public/markers/scaled_circles.js +++ b/src/plugins/tile_map/public/markers/scaled_circles.js @@ -42,12 +42,12 @@ export class ScaledCirclesMarkers extends EventEmitter { this._valueFormatter = options.valueFormatter || - (x => { + ((x) => { x; }); this._tooltipFormatter = options.tooltipFormatter || - (x => { + ((x) => { x; }); this._label = options.label; @@ -67,7 +67,7 @@ export class ScaledCirclesMarkers extends EventEmitter { }; // Filter leafletlayer on client when results are not filtered on the server if (!options.isFilteredByCollar) { - layerOptions.filter = feature => { + layerOptions.filter = (feature) => { const bucketRectBounds = feature.properties.geohash_meta.rectangle; return kibanaMap.isInside(bucketRectBounds); }; @@ -87,10 +87,7 @@ export class ScaledCirclesMarkers extends EventEmitter { const quantizeDomain = min !== max ? [min, max] : d3.scale.quantize().domain(); this._legendColors = this.getLegendColors(); - this._legendQuantizer = d3.scale - .quantize() - .domain(quantizeDomain) - .range(this._legendColors); + this._legendQuantizer = d3.scale.quantize().domain(quantizeDomain).range(this._legendColors); return makeStyleFunction(this._legendColors, quantizeDomain); } @@ -110,12 +107,10 @@ export class ScaledCirclesMarkers extends EventEmitter { } const titleText = this.getLabel(); - const $title = $('
') - .addClass('visMapLegend__title') - .text(titleText); + const $title = $('
').addClass('visMapLegend__title').text(titleText); jqueryDiv.append($title); - this._legendColors.forEach(color => { + this._legendColors.forEach((color) => { const labelText = this._legendQuantizer .invertExtent(color) .map(this._valueFormatter) @@ -145,7 +140,7 @@ export class ScaledCirclesMarkers extends EventEmitter { */ _bindPopup(feature, layer) { const popup = layer.on({ - mouseover: e => { + mouseover: (e) => { const layer = e.target; // bring layer to front if not older browser if (!L.Browser.ie && !L.Browser.opera) { @@ -205,7 +200,7 @@ export class ScaledCirclesMarkers extends EventEmitter { const precisionBiasNumerator = 200; const precision = _.max( - this._featureCollection.features.map(feature => { + this._featureCollection.features.map((feature) => { return String(feature.properties.geohash).length; }) ); @@ -230,18 +225,12 @@ export class ScaledCirclesMarkers extends EventEmitter { function makeColorDarker(color) { const amount = 1.3; //magic number, carry over from earlier - return d3 - .hcl(color) - .darker(amount) - .toString(); + return d3.hcl(color).darker(amount).toString(); } function makeStyleFunction(legendColors, quantizeDomain) { - const legendQuantizer = d3.scale - .quantize() - .domain(quantizeDomain) - .range(legendColors); - return feature => { + const legendQuantizer = d3.scale.quantize().domain(quantizeDomain).range(legendColors); + return (feature) => { const value = _.get(feature, 'properties.value'); const color = legendQuantizer(value); return { diff --git a/src/plugins/tile_map/public/tile_map_type.js b/src/plugins/tile_map/public/tile_map_type.js index aa0160f3f5a9d..f76da26022a77 100644 --- a/src/plugins/tile_map/public/tile_map_type.js +++ b/src/plugins/tile_map/public/tile_map_type.js @@ -113,7 +113,7 @@ export function createTileMapTypeDefinition(dependencies) { ], tmsLayers: [], }, - optionsTemplate: props => , + optionsTemplate: (props) => , schemas: new Schemas([ { group: 'metrics', @@ -138,7 +138,7 @@ export function createTileMapTypeDefinition(dependencies) { }, ]), }, - setup: async vis => { + setup: async (vis) => { let tmsLayers; try { diff --git a/src/plugins/tile_map/public/tile_map_visualization.js b/src/plugins/tile_map/public/tile_map_visualization.js index f96c7291b34cf..1f4e5f09a9aa4 100644 --- a/src/plugins/tile_map/public/tile_map_visualization.js +++ b/src/plugins/tile_map/public/tile_map_visualization.js @@ -23,7 +23,7 @@ import { getFormatService, getQueryService } from './services'; import { scaleBounds, geoContains, mapTooltipProvider } from '../../maps_legacy/public'; import { tooltipFormatter } from './tooltip_formatter'; -export const createTileMapVisualization = dependencies => { +export const createTileMapVisualization = (dependencies) => { const { getZoomPrecision, getPrecision, BaseMapsVisualization } = dependencies; return class CoordinateMapsVisualization extends BaseMapsVisualization { @@ -67,7 +67,7 @@ export const createTileMapVisualization = dependencies => { let precisionChange = false; const uiState = this.vis.getUiState(); - uiState.on('change', prop => { + uiState.on('change', (prop) => { if (prop === 'mapZoom' || prop === 'mapCenter') { this.updateGeohashAgg(); } @@ -98,11 +98,11 @@ export const createTileMapVisualization = dependencies => { }); this._kibanaMap.addDrawControl(); - this._kibanaMap.on('drawCreated:rectangle', event => { + this._kibanaMap.on('drawCreated:rectangle', (event) => { const geohashAgg = this._getGeoHashAgg(); this.addSpatialFilter(geohashAgg, 'geo_bounding_box', event.bounds); }); - this._kibanaMap.on('drawCreated:polygon', event => { + this._kibanaMap.on('drawCreated:polygon', (event) => { const geohashAgg = this._getGeoHashAgg(); this.addSpatialFilter(geohashAgg, 'geo_polygon', { points: event.points }); }); diff --git a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx index 0c19d20ed1bda..74e9ef96b575b 100644 --- a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx +++ b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx @@ -106,7 +106,7 @@ async function convertPanelActionToContextMenuItem({ 'data-test-subj': `embeddablePanelAction-${action.id}`, }; - menuPanelItem.onClick = event => { + menuPanelItem.onClick = (event) => { if (event.currentTarget instanceof HTMLAnchorElement) { // from react-router's if ( diff --git a/src/plugins/ui_actions/public/service/ui_actions_service.ts b/src/plugins/ui_actions/public/service/ui_actions_service.ts index 9a08aeabb00f3..760897f0287d8 100644 --- a/src/plugins/ui_actions/public/service/ui_actions_service.ts +++ b/src/plugins/ui_actions/public/service/ui_actions_service.ts @@ -108,7 +108,7 @@ export class UiActionsService { const actionIds = this.triggerToActions.get(triggerId); - if (!actionIds!.find(id => id === actionId)) { + if (!actionIds!.find((id) => id === actionId)) { this.triggerToActions.set(triggerId, [...actionIds!, actionId]); } }; @@ -126,7 +126,7 @@ export class UiActionsService { this.triggerToActions.set( triggerId, - actionIds!.filter(id => id !== actionId) + actionIds!.filter((id) => id !== actionId) ); }; @@ -165,7 +165,7 @@ export class UiActionsService { const actionIds = this.triggerToActions.get(triggerId); const actions = actionIds! - .map(actionId => this.actions.get(actionId) as ActionInternal) + .map((actionId) => this.actions.get(actionId) as ActionInternal) .filter(Boolean); return actions as Array>>; @@ -176,7 +176,7 @@ export class UiActionsService { context: TriggerContextMapping[T] ): Promise>> => { const actions = this.getTriggerActions!(triggerId); - const isCompatibles = await Promise.all(actions.map(action => action.isCompatible(context))); + const isCompatibles = await Promise.all(actions.map((action) => action.isCompatible(context))); return actions.reduce( (acc: Array>, action, i) => isCompatibles[i] ? [...acc, action] : acc, diff --git a/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts b/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts index ade21ee4b7d91..983c6796eeb09 100644 --- a/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts +++ b/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts @@ -42,7 +42,7 @@ function createTestAction( type: type as ActionType, id: type, isCompatible: (context: C) => Promise.resolve(checkCompatibility(context)), - execute: context => executeFn(context), + execute: (context) => executeFn(context), }); } diff --git a/src/plugins/usage_collection/public/plugin.ts b/src/plugins/usage_collection/public/plugin.ts index e89e24e25c627..cf2f6af1507c0 100644 --- a/src/plugins/usage_collection/public/plugin.ts +++ b/src/plugins/usage_collection/public/plugin.ts @@ -83,7 +83,7 @@ export class UsageCollectionPlugin implements Plugin { reportUiStats: this.reporter.reportUiStats, METRIC_TYPE, __LEGACY: { - appChanged: appId => this.legacyAppId$.next(appId), + appChanged: (appId) => this.legacyAppId$.next(appId), }, }; } diff --git a/src/plugins/usage_collection/public/services/application_usage.ts b/src/plugins/usage_collection/public/services/application_usage.ts index 15aaabc70ed0d..f63c30ad6cd37 100644 --- a/src/plugins/usage_collection/public/services/application_usage.ts +++ b/src/plugins/usage_collection/public/services/application_usage.ts @@ -32,8 +32,8 @@ export function reportApplicationUsage( ) { currentAppId$ .pipe( - filter(appId => typeof appId === 'string' && !DO_NOT_REPORT.includes(appId)), + filter((appId) => typeof appId === 'string' && !DO_NOT_REPORT.includes(appId)), distinctUntilChanged() ) - .subscribe(appId => appId && reporter.reportApplicationUsage(appId)); + .subscribe((appId) => appId && reporter.reportApplicationUsage(appId)); } diff --git a/src/plugins/usage_collection/server/collector/collector_set.test.ts b/src/plugins/usage_collection/server/collector/collector_set.test.ts index c85880c34d72b..ced5206cee318 100644 --- a/src/plugins/usage_collection/server/collector/collector_set.test.ts +++ b/src/plugins/usage_collection/server/collector/collector_set.test.ts @@ -144,7 +144,7 @@ describe('CollectorSet', () => { new Collector(logger, { type: 'MY_TEST_COLLECTOR', fetch: () => ({ test: 1 }), - formatForBulkUpload: result => ({ + formatForBulkUpload: (result) => ({ type: 'MY_TEST_COLLECTOR', payload: { test: result.test * 2 }, }), diff --git a/src/plugins/usage_collection/server/collector/collector_set.ts b/src/plugins/usage_collection/server/collector/collector_set.ts index 64a48025be248..66673bd7902a2 100644 --- a/src/plugins/usage_collection/server/collector/collector_set.ts +++ b/src/plugins/usage_collection/server/collector/collector_set.ts @@ -64,7 +64,7 @@ export class CollectorSet { }; public getCollectorByType = (type: string) => { - return this.collectors.find(c => c.type === type); + return this.collectors.find((c) => c.type === type); }; public isUsageCollector = (x: UsageCollector | any): x is UsageCollector => { @@ -140,7 +140,7 @@ export class CollectorSet { }; public bulkFetchUsage = async (callCluster: APICaller) => { - const usageCollectors = this.getFilteredCollectorSet(c => c instanceof UsageCollector); + const usageCollectors = this.getFilteredCollectorSet((c) => c instanceof UsageCollector); return await this.bulkFetch(callCluster, usageCollectors.collectors); }; diff --git a/src/plugins/vis_default_editor/public/agg_filters/agg_type_field_filters.ts b/src/plugins/vis_default_editor/public/agg_filters/agg_type_field_filters.ts index 15df2f0acccd1..6254108db7997 100644 --- a/src/plugins/vis_default_editor/public/agg_filters/agg_type_field_filters.ts +++ b/src/plugins/vis_default_editor/public/agg_filters/agg_type_field_filters.ts @@ -41,8 +41,8 @@ const filters: AggTypeFieldFilter[] = [ ]; export function filterAggTypeFields(fields: IndexPatternField[], aggConfig: IAggConfig) { - const allowedAggTypeFields = fields.filter(field => { - const isAggTypeFieldAllowed = filters.every(filter => filter(field, aggConfig)); + const allowedAggTypeFields = fields.filter((field) => { + const isAggTypeFieldAllowed = filters.every((filter) => filter(field, aggConfig)); return isAggTypeFieldAllowed; }); return allowedAggTypeFields; diff --git a/src/plugins/vis_default_editor/public/agg_filters/agg_type_filters.ts b/src/plugins/vis_default_editor/public/agg_filters/agg_type_filters.ts index 2cf1acba4d228..87f6798bc35d0 100644 --- a/src/plugins/vis_default_editor/public/agg_filters/agg_type_filters.ts +++ b/src/plugins/vis_default_editor/public/agg_filters/agg_type_filters.ts @@ -65,8 +65,8 @@ export function filterAggTypes( aggConfig: IAggConfig, aggFilter: string[] ) { - const allowedAggTypes = aggTypes.filter(aggType => { - const isAggTypeAllowed = filters.every(filter => + const allowedAggTypes = aggTypes.filter((aggType) => { + const isAggTypeAllowed = filters.every((filter) => filter(aggType, indexPattern, aggConfig, aggFilter) ); return isAggTypeAllowed; diff --git a/src/plugins/vis_default_editor/public/components/agg.test.tsx b/src/plugins/vis_default_editor/public/components/agg.test.tsx index feb5b3caa023b..db107fa589083 100644 --- a/src/plugins/vis_default_editor/public/components/agg.test.tsx +++ b/src/plugins/vis_default_editor/public/components/agg.test.tsx @@ -99,10 +99,7 @@ describe('DefaultEditorAgg component', () => { const comp = mount(); act(() => { - comp - .find(DefaultEditorAggParams) - .props() - .setValidity(false); + comp.find(DefaultEditorAggParams).props().setValidity(false); }); comp.update(); expect(setAggsState).toBeCalledWith({ @@ -124,10 +121,7 @@ describe('DefaultEditorAgg component', () => { const comp = mount(); act(() => { - comp - .find(DefaultEditorAggParams) - .props() - .setValidity(true); + comp.find(DefaultEditorAggParams).props().setValidity(true); }); comp.update(); expect(setAggsState).toBeCalledWith({ @@ -160,10 +154,7 @@ describe('DefaultEditorAgg component', () => { const comp = mount(); act(() => { - comp - .find(DefaultEditorAggParams) - .props() - .setValidity(false); + comp.find(DefaultEditorAggParams).props().setValidity(false); }); expect(setAggsState).toBeCalledWith({ diff --git a/src/plugins/vis_default_editor/public/components/agg.tsx b/src/plugins/vis_default_editor/public/components/agg.tsx index c7e3e609490f9..76c8e0dc0cb9e 100644 --- a/src/plugins/vis_default_editor/public/components/agg.tsx +++ b/src/plugins/vis_default_editor/public/components/agg.tsx @@ -225,7 +225,7 @@ function DefaultEditorAgg({ } return (
- {actionIcons.map(icon => { + {actionIcons.map((icon) => { if (icon.id === 'dragHandle') { return ( { - const count = group.filter(agg => agg.schema === schema.name).length; + const count = group.filter((agg) => agg.schema === schema.name).length; return count >= schema.max; }; @@ -105,7 +105,7 @@ function DefaultEditorAggAdd({ )} ( + items={schemas.map((schema) => ( s.name); + const schemaNames = schemas.map((s) => s.name); const group: IAggConfig[] = useMemo( () => state.data.aggs!.aggs.filter( @@ -100,7 +100,7 @@ function DefaultEditorAggGroup({ }) : undefined; - const isGroupValid = !bucketsError && Object.values(aggsState).every(item => item.valid); + const isGroupValid = !bucketsError && Object.values(aggsState).every((item) => item.valid); const isAllAggsTouched = isInvalidAggsTouched(aggsState); const isMetricAggregationDisabled = useMemo( () => groupName === AggGroupNames.Metrics && getEnabledMetricAggsCount(group) === 1, @@ -165,7 +165,7 @@ function DefaultEditorAggGroup({ draggableId={`agg_group_dnd_${groupName}_${agg.id}`} customDragHandle={true} > - {provided => ( + {(provided) => ( !agg.valid); + const invalidAggs = Object.values(aggsState).filter((agg) => !agg.valid); if (isEmpty(invalidAggs)) { return false; } - return invalidAggs.every(agg => agg.touched); + return invalidAggs.every((agg) => agg.touched); } export { isAggRemovable, calcAggIsTooLow, isInvalidAggsTouched, getEnabledMetricAggsCount }; diff --git a/src/plugins/vis_default_editor/public/components/agg_params.tsx b/src/plugins/vis_default_editor/public/components/agg_params.tsx index d36c2d0e7625b..78398d8359e9e 100644 --- a/src/plugins/vis_default_editor/public/components/agg_params.tsx +++ b/src/plugins/vis_default_editor/public/components/agg_params.tsx @@ -132,7 +132,7 @@ function DefaultEditorAggParams({ !!error || isInvalidParamsTouched(agg.type, aggType, paramsState); const onAggSelect = useCallback( - value => { + (value) => { if (agg.type !== value) { onAggTypeChange(agg.id, value); // reset touched and valid of params @@ -147,7 +147,7 @@ function DefaultEditorAggParams({ useEffect(() => { Object.entries(editorConfig).forEach(([param, paramConfig]) => { - const paramOptions = agg.type.params.find(paramOption => paramOption.name === param); + const paramOptions = agg.type.params.find((paramOption) => paramOption.name === param); const hasFixedValue = paramConfig.hasOwnProperty(FIXED_VALUE_PROP); const hasDefault = paramConfig.hasOwnProperty(DEFAULT_PROP); @@ -210,7 +210,7 @@ function DefaultEditorAggParams({ onChangeAggType={onChangeAggType} /> - {params.basic.map(param => { + {params.basic.map((param) => { const model = paramsState[param.aggParam.name] || { touched: false, valid: true, @@ -240,7 +240,7 @@ function DefaultEditorAggParams({ })} > - {params.advanced.map(param => { + {params.advanced.map((param) => { const model = paramsState[param.aggParam.name] || { touched: false, valid: true, diff --git a/src/plugins/vis_default_editor/public/components/agg_params_helper.ts b/src/plugins/vis_default_editor/public/components/agg_params_helper.ts index 9977f1e5e71fc..45abbf8d2b2dd 100644 --- a/src/plugins/vis_default_editor/public/components/agg_params_helper.ts +++ b/src/plugins/vis_default_editor/public/components/agg_params_helper.ts @@ -89,7 +89,7 @@ function getAggParamsToRender({ if (agg.type.name === 'top_hits' && param.name === 'field') { const allowStrings = _.get(schema, `aggSettings[${agg.type.name}].allowStrings`, false); if (!allowStrings) { - availableFields = availableFields.filter(field => field.type === 'number'); + availableFields = availableFields.filter((field) => field.type === 'number'); } } fields = filterAggTypeFields(availableFields, agg); @@ -163,13 +163,13 @@ function isInvalidParamsTouched( return aggTypeState.touched; } - const invalidParams = Object.values(aggParams).filter(param => !param.valid); + const invalidParams = Object.values(aggParams).filter((param) => !param.valid); if (isEmpty(invalidParams)) { return false; } - return invalidParams.every(param => param.touched); + return invalidParams.every((param) => param.touched); } function buildAggDescription(agg: IAggConfig) { diff --git a/src/plugins/vis_default_editor/public/components/agg_select.tsx b/src/plugins/vis_default_editor/public/components/agg_select.tsx index 6cb76b18e24a6..8d03940a92d34 100644 --- a/src/plugins/vis_default_editor/public/components/agg_select.tsx +++ b/src/plugins/vis_default_editor/public/components/agg_select.tsx @@ -111,14 +111,14 @@ function DefaultEditorAggSelect({ }, [setValue] ); - const onSearchChange = useCallback(searchValue => setIsDirty(Boolean(searchValue)), []); + const onSearchChange = useCallback((searchValue) => setIsDirty(Boolean(searchValue)), []); const setTouched = useCallback( () => onChangeAggType({ type: AGG_TYPE_ACTION_KEYS.TOUCHED, payload: true }), [onChangeAggType] ); const setValidity = useCallback( - valid => onChangeAggType({ type: AGG_TYPE_ACTION_KEYS.VALID, payload: valid }), + (valid) => onChangeAggType({ type: AGG_TYPE_ACTION_KEYS.VALID, payload: valid }), [onChangeAggType] ); diff --git a/src/plugins/vis_default_editor/public/components/controls/auto_precision.tsx b/src/plugins/vis_default_editor/public/components/controls/auto_precision.tsx index e49a12333bdca..11b249e1873a8 100644 --- a/src/plugins/vis_default_editor/public/components/controls/auto_precision.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/auto_precision.tsx @@ -34,7 +34,7 @@ function AutoPrecisionParamEditor({ value = false, setValue }: AggParamEditorPro compressed={true} label={label} checked={value} - onChange={ev => setValue(ev.target.checked)} + onChange={(ev) => setValue(ev.target.checked)} /> ); diff --git a/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx index b874459a8e7d3..8fe5cdb47a53d 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/from_to_list.tsx @@ -90,7 +90,7 @@ function FromToList({ showValidation, onBlur, ...rest }: FromToListProps) { compressed isInvalid={showValidation ? item.from.isInvalid : false} placeholder="*" - onChange={ev => { + onChange={(ev) => { onChangeValue(index, ev.target.value, 'from'); }} value={item.from.value} @@ -109,7 +109,7 @@ function FromToList({ showValidation, onBlur, ...rest }: FromToListProps) { compressed isInvalid={showValidation ? item.to.isInvalid : false} placeholder="*" - onChange={ev => { + onChange={(ev) => { onChangeValue(index, ev.target.value, 'to'); }} value={item.to.value} diff --git a/src/plugins/vis_default_editor/public/components/controls/components/input_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/input_list.tsx index 639b69cd3d33c..a0bc0d78a2889 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/input_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/input_list.tsx @@ -96,7 +96,7 @@ function InputList({ config, list, onChange, setValidity }: InputListProps) { const { defaultValue, getModelValue, modelNames, onChangeFn, validateClass } = config; const [models, setModels] = useState(() => list.map( - item => + (item) => ({ id: generateId(), ...getModelValue(item), @@ -133,7 +133,7 @@ function InputList({ config, list, onChange, setValidity }: InputListProps) { [models, updateValues, validateClass] ); const onDelete = useCallback( - (id: string) => updateValues(models.filter(model => model.id !== id)), + (id: string) => updateValues(models.filter((model) => model.id !== id)), [models, updateValues] ); const onAdd = useCallback( @@ -178,7 +178,7 @@ function InputList({ config, list, onChange, setValidity }: InputListProps) { ) { setModels( list.map( - item => + (item) => ({ id: generateId(), ...getModelValue(item), diff --git a/src/plugins/vis_default_editor/public/components/controls/components/mask_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/mask_list.tsx index 560213fc08ff0..98f92387e0038 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/mask_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/mask_list.tsx @@ -86,7 +86,7 @@ function MaskList({ showValidation, onBlur, ...rest }: MaskListProps) { fullWidth isInvalid={showValidation ? mask.isInvalid : false} placeholder="*" - onChange={ev => { + onChange={(ev) => { onChangeValue(index, ev.target.value, 'mask'); }} value={mask.value} diff --git a/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.test.tsx b/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.test.tsx index f547f1dee6a39..82d4b9142fb76 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.test.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.test.tsx @@ -139,12 +139,7 @@ describe('NumberList', () => { defaultProps.numberArray = [1]; const comp = shallow(); - expect( - comp - .find(NumberRow) - .first() - .prop('disableDelete') - ).toEqual(true); + expect(comp.find(NumberRow).first().prop('disableDelete')).toEqual(true); }); test('should change value', () => { @@ -157,10 +152,7 @@ describe('NumberList', () => { test('should call setTouched', () => { const comp = shallow(); - comp - .find(NumberRow) - .first() - .prop('onBlur')(); + comp.find(NumberRow).first().prop('onBlur')(); expect(defaultProps.setTouched).toBeCalled(); }); diff --git a/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.tsx index b4683e47979ce..aac4c9fe528bd 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/number_list/number_list.tsx @@ -63,7 +63,7 @@ function NumberList({ // set up validity for each model useEffect(() => { - setModels(state => + setModels((state) => getValidatedModels( numberArray, state, @@ -97,7 +97,7 @@ function NumberList({ const parsedValue = parse(value); onUpdate( - models.map(model => { + models.map((model) => { if (model.id === id) { return { id, @@ -120,7 +120,7 @@ function NumberList({ const onDelete = useCallback( (id: string) => { - const newArray = models.filter(model => model.id !== id); + const newArray = models.filter((model) => model.id !== id); onUpdate(newArray); }, [models, onUpdate] diff --git a/src/plugins/vis_default_editor/public/components/controls/components/number_list/range.test.ts b/src/plugins/vis_default_editor/public/components/controls/components/number_list/range.test.ts index a19034d3c8e92..c50ac929dc7bd 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/number_list/range.test.ts +++ b/src/plugins/vis_default_editor/public/components/controls/components/number_list/range.test.ts @@ -26,19 +26,19 @@ describe('Range parsing utility', () => { parseRange(''); }).toThrowError(TypeError); - expect(function() { + expect(function () { parseRange('p10202'); }).toThrowError(TypeError); - expect(function() { + expect(function () { parseRange('{0,100}'); }).toThrowError(TypeError); - expect(function() { + expect(function () { parseRange('[0,100'); }).toThrowError(TypeError); - expect(function() { + expect(function () { parseRange(')0,100('); }).toThrowError(TypeError); }); diff --git a/src/plugins/vis_default_editor/public/components/controls/components/number_list/utils.ts b/src/plugins/vis_default_editor/public/components/controls/components/number_list/utils.ts index 5cb594ade8dba..6eaef3050029a 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/number_list/utils.ts +++ b/src/plugins/vis_default_editor/public/components/controls/components/number_list/utils.ts @@ -121,7 +121,7 @@ function getNextModel(list: NumberRowModel[], range: NumberListRange): NumberRow function getInitModelList(list: Array): NumberRowModel[] { return list.length - ? list.map(num => ({ + ? list.map((num) => ({ value: (num === undefined ? EMPTY_STRING : num) as NumberRowModel['value'], id: generateId(), isInvalid: false, diff --git a/src/plugins/vis_default_editor/public/components/controls/components/simple_number_list.tsx b/src/plugins/vis_default_editor/public/components/controls/components/simple_number_list.tsx index becf8e47ef573..079fa95d362ac 100644 --- a/src/plugins/vis_default_editor/public/components/controls/components/simple_number_list.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/components/simple_number_list.tsx @@ -47,7 +47,7 @@ function SimpleNumberList({ !value.every((numberValue, index) => numberValue === numbers[index].value)) ) { setNumbers( - value.map(numberValue => ({ + value.map((numberValue) => ({ id: generateId(), value: numberValue, isInvalid: false, @@ -67,7 +67,7 @@ function SimpleNumberList({ const onChangeValue = useCallback( (numberField: { id: string; value: string }) => { onUpdate( - numbers.map(number => + numbers.map((number) => number.id === numberField.id ? { id: numberField.id, @@ -95,7 +95,7 @@ function SimpleNumberList({ }, [numbers, onUpdate]); const onDelete = useCallback( - (id: string) => onUpdate(numbers.filter(number => number.id !== id)), + (id: string) => onUpdate(numbers.filter((number) => number.id !== id)), [numbers, onUpdate] ); diff --git a/src/plugins/vis_default_editor/public/components/controls/date_ranges.test.tsx b/src/plugins/vis_default_editor/public/components/controls/date_ranges.test.tsx index b844fdfb82256..5c95d72bcd282 100644 --- a/src/plugins/vis_default_editor/public/components/controls/date_ranges.test.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/date_ranges.test.tsx @@ -65,7 +65,7 @@ describe('DateRangesParamEditor component', () => { expect(setValue).toHaveBeenCalledWith([{}]); }); - it('should validate range values with date math', function() { + it('should validate range values with date math', function () { const component = mountWithIntl(); // should allow empty values diff --git a/src/plugins/vis_default_editor/public/components/controls/date_ranges.tsx b/src/plugins/vis_default_editor/public/components/controls/date_ranges.tsx index 57f4c7d04019b..d3cf87c9ef14a 100644 --- a/src/plugins/vis_default_editor/public/components/controls/date_ranges.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/date_ranges.tsx @@ -68,7 +68,9 @@ function DateRangesParamEditor({ setValidity, }: AggParamEditorProps) { const { services } = useKibana(); - const [ranges, setRanges] = useState(() => value.map(range => ({ ...range, id: generateId() }))); + const [ranges, setRanges] = useState(() => + value.map((range) => ({ ...range, id: generateId() })) + ); const hasInvalidRange = value.some( ({ from, to }) => (!from && !to) || !validateDateMath(from) || !validateDateMath(to) ); @@ -76,7 +78,7 @@ function DateRangesParamEditor({ const updateRanges = useCallback( (rangeValues: DateRangeValuesModel[]) => { // do not set internal id parameter into saved object - setValue(rangeValues.map(range => omit(range, 'id'))); + setValue(rangeValues.map((range) => omit(range, 'id'))); setRanges(rangeValues); }, [setValue] @@ -100,7 +102,7 @@ function DateRangesParamEditor({ value.length !== ranges.length || value.some((range, index) => !isEqual(range, omit(ranges[index], 'id'))) ) { - setRanges(value.map(range => ({ ...range, id: generateId() }))); + setRanges(value.map((range) => ({ ...range, id: generateId() }))); } }, [ranges, value]); @@ -108,10 +110,10 @@ function DateRangesParamEditor({ setValidity(!hasInvalidRange); }, [hasInvalidRange, setValidity]); - const onRemoveRange = (id: string) => updateRanges(ranges.filter(range => range.id !== id)); + const onRemoveRange = (id: string) => updateRanges(ranges.filter((range) => range.id !== id)); const onChangeRange = (id: string, key: string, newValue: string) => updateRanges( - ranges.map(range => + ranges.map((range) => range.id === id ? { ...range, @@ -162,7 +164,7 @@ function DateRangesParamEditor({ isInvalid={areBothEmpty || !validateDateMath(from)} placeholder={FROM_PLACEHOLDER} value={from || ''} - onChange={ev => onChangeRange(id, 'from', ev.target.value)} + onChange={(ev) => onChangeRange(id, 'from', ev.target.value)} data-test-subj={`visEditorDateRange${index}__from`} /> @@ -184,7 +186,7 @@ function DateRangesParamEditor({ isInvalid={areBothEmpty || !validateDateMath(to)} placeholder={TO_PLACEHOLDER} value={to || ''} - onChange={ev => onChangeRange(id, 'to', ev.target.value)} + onChange={(ev) => onChangeRange(id, 'to', ev.target.value)} /> diff --git a/src/plugins/vis_default_editor/public/components/controls/extended_bounds.tsx b/src/plugins/vis_default_editor/public/components/controls/extended_bounds.tsx index 14652f435cf5b..11df63c9a3fa1 100644 --- a/src/plugins/vis_default_editor/public/components/controls/extended_bounds.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/extended_bounds.tsx @@ -78,7 +78,7 @@ function ExtendedBoundsParamEditor({ handleChange(ev, 'min')} + onChange={(ev) => handleChange(ev, 'min')} onBlur={setTouched} fullWidth={true} isInvalid={showValidation ? !isValid : false} @@ -90,7 +90,7 @@ function ExtendedBoundsParamEditor({ handleChange(ev, 'max')} + onChange={(ev) => handleChange(ev, 'max')} onBlur={setTouched} fullWidth={true} isInvalid={showValidation ? !isValid : false} diff --git a/src/plugins/vis_default_editor/public/components/controls/field.tsx b/src/plugins/vis_default_editor/public/components/controls/field.tsx index 42086004a12dc..24d94c2b18feb 100644 --- a/src/plugins/vis_default_editor/public/components/controls/field.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/field.tsx @@ -100,7 +100,7 @@ function FieldParamEditor({ } }); - const onSearchChange = useCallback(searchValue => setIsDirty(Boolean(searchValue)), []); + const onSearchChange = useCallback((searchValue) => setIsDirty(Boolean(searchValue)), []); return ( onChangeValue(id, value, ev.target.value)} + onChange={(ev) => onChangeValue(id, value, ev.target.value)} fullWidth={true} compressed /> diff --git a/src/plugins/vis_default_editor/public/components/controls/filters.tsx b/src/plugins/vis_default_editor/public/components/controls/filters.tsx index d4e698f655c5e..7a655b935a45e 100644 --- a/src/plugins/vis_default_editor/public/components/controls/filters.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/filters.tsx @@ -38,12 +38,12 @@ interface FilterValue { function FiltersParamEditor({ agg, value = [], setValue }: AggParamEditorProps) { const [filters, setFilters] = useState(() => - value.map(filter => ({ ...filter, id: generateId() })) + value.map((filter) => ({ ...filter, id: generateId() })) ); useMount(() => { // set parsed values into model after initialization - setValue(filters.map(filter => omit({ ...filter, input: filter.input }, 'id'))); + setValue(filters.map((filter) => omit({ ...filter, input: filter.input }, 'id'))); }); useEffect(() => { @@ -52,13 +52,13 @@ function FiltersParamEditor({ agg, value = [], setValue }: AggParamEditorProps !isEqual(filter, omit(filters[index], 'id'))) ) { - setFilters(value.map(filter => ({ ...filter, id: generateId() }))); + setFilters(value.map((filter) => ({ ...filter, id: generateId() }))); } }, [filters, value]); const updateFilters = (updatedFilters: FilterValue[]) => { // do not set internal id parameter into saved object - setValue(updatedFilters.map(filter => omit(filter, 'id'))); + setValue(updatedFilters.map((filter) => omit(filter, 'id'))); setFilters(updatedFilters); }; @@ -73,10 +73,11 @@ function FiltersParamEditor({ agg, value = [], setValue }: AggParamEditorProps updateFilters(filters.filter(filter => filter.id !== id)); + const onRemoveFilter = (id: string) => + updateFilters(filters.filter((filter) => filter.id !== id)); const onChangeValue = (id: string, query: Query, label: string) => updateFilters( - filters.map(filter => + filters.map((filter) => filter.id === id ? { ...filter, diff --git a/src/plugins/vis_default_editor/public/components/controls/include_exclude.tsx b/src/plugins/vis_default_editor/public/components/controls/include_exclude.tsx index f60f6ce7ce249..7941cecdae31f 100644 --- a/src/plugins/vis_default_editor/public/components/controls/include_exclude.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/include_exclude.tsx @@ -33,11 +33,11 @@ export function IncludeExcludeParamEditor(props: AggParamEditorProps parseFloat(item)) - .filter(number => Number.isFinite(number)); + .map((item) => parseFloat(item)) + .filter((number) => Number.isFinite(number)); setValue(numberArray.length ? numberArray : ['']); } else if (!isAggOfNumberType && Array.isArray(value) && value !== undefined) { - setValue(value.filter(item => item !== '').join('|')); + setValue(value.filter((item) => item !== '').join('|')); } }, [isAggOfNumberType, setValue, value]); diff --git a/src/plugins/vis_default_editor/public/components/controls/metric_agg.tsx b/src/plugins/vis_default_editor/public/components/controls/metric_agg.tsx index 41e638b8d85fe..7215ef3dcc7b7 100644 --- a/src/plugins/vis_default_editor/public/components/controls/metric_agg.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/metric_agg.tsx @@ -46,11 +46,11 @@ function MetricAggParamEditor({ useFallbackMetric(setValue, aggFilter, metricAggs, value); const filteredMetrics = useMemo( - () => metricAggs.filter(respAgg => respAgg.type.name !== agg.type.name), + () => metricAggs.filter((respAgg) => respAgg.type.name !== agg.type.name), [metricAggs, agg.type.name] ); const options = useAvailableOptions(aggFilter, filteredMetrics, DEFAULT_OPTIONS); - const onChange = useCallback(ev => setValue(ev.target.value), [setValue]); + const onChange = useCallback((ev) => setValue(ev.target.value), [setValue]); return ( diff --git a/src/plugins/vis_default_editor/public/components/controls/order.tsx b/src/plugins/vis_default_editor/public/components/controls/order.tsx index 3c0224564300a..9f7c39eb65dc0 100644 --- a/src/plugins/vis_default_editor/public/components/controls/order.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/order.tsx @@ -52,7 +52,7 @@ function OrderParamEditor({ + onChange={(ev) => setValue(aggParam.options.find((opt: OptionedValueProp) => opt.value === ev.target.value)) } fullWidth={true} diff --git a/src/plugins/vis_default_editor/public/components/controls/order_by.tsx b/src/plugins/vis_default_editor/public/components/controls/order_by.tsx index 47b12f4340d42..30a72818fe8a1 100644 --- a/src/plugins/vis_default_editor/public/components/controls/order_by.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/order_by.tsx @@ -81,7 +81,7 @@ function OrderByParamEditor({ setValue(ev.target.value)} + onChange={(ev) => setValue(ev.target.value)} fullWidth={true} compressed isInvalid={showValidation && !isValid} diff --git a/src/plugins/vis_default_editor/public/components/controls/ranges.tsx b/src/plugins/vis_default_editor/public/components/controls/ranges.tsx index 5c6438b400408..e5f5b53a3d879 100644 --- a/src/plugins/vis_default_editor/public/components/controls/ranges.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/ranges.tsx @@ -75,11 +75,13 @@ function RangesParamEditor({ setValidity, validateRange, }: RangesParamEditorProps) { - const [ranges, setRanges] = useState(() => value.map(range => ({ ...range, id: generateId() }))); + const [ranges, setRanges] = useState(() => + value.map((range) => ({ ...range, id: generateId() })) + ); const updateRanges = useCallback( (rangeValues: RangeValuesModel[]) => { // do not set internal id parameter into saved object - setValue(rangeValues.map(range => omit(range, 'id'))); + setValue(rangeValues.map((range) => omit(range, 'id'))); setRanges(rangeValues); if (setTouched) { @@ -95,10 +97,10 @@ function RangesParamEditor({ : updateRanges([...ranges, { id: generateId() }]), [addRangeValues, ranges, updateRanges] ); - const onRemoveRange = (id: string) => updateRanges(ranges.filter(range => range.id !== id)); + const onRemoveRange = (id: string) => updateRanges(ranges.filter((range) => range.id !== id)); const onChangeRange = (id: string, key: string, newValue: string) => updateRanges( - ranges.map(range => + ranges.map((range) => range.id === id ? { ...range, @@ -121,7 +123,7 @@ function RangesParamEditor({ value.length !== ranges.length || value.some((range, index) => !isEqual(range, omit(ranges[index], 'id'))) ) { - setRanges(value.map(range => ({ ...range, id: generateId() }))); + setRanges(value.map((range) => ({ ...range, id: generateId() }))); } }, [ranges, value]); @@ -197,7 +199,7 @@ function RangesParamEditor({ data-test-subj={`${dataTestSubj}${index}__from`} value={isEmpty(from) ? '' : from} placeholder={hidePlaceholders ? undefined : FROM_PLACEHOLDER} - onChange={ev => onChangeRange(id, 'from', ev.target.value)} + onChange={(ev) => onChangeRange(id, 'from', ev.target.value)} fullWidth={true} compressed={true} isInvalid={!isFromValid} @@ -219,7 +221,7 @@ function RangesParamEditor({ data-test-subj={`${dataTestSubj}${index}__to`} value={isEmpty(to) ? '' : to} placeholder={hidePlaceholders ? undefined : TO_PLACEHOLDER} - onChange={ev => onChangeRange(id, 'to', ev.target.value)} + onChange={(ev) => onChangeRange(id, 'to', ev.target.value)} fullWidth={true} compressed={true} isInvalid={!isToValid} diff --git a/src/plugins/vis_default_editor/public/components/controls/rows_or_columns.tsx b/src/plugins/vis_default_editor/public/components/controls/rows_or_columns.tsx index 83a341e045b5c..4e06e8d0af71f 100644 --- a/src/plugins/vis_default_editor/public/components/controls/rows_or_columns.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/rows_or_columns.tsx @@ -48,7 +48,7 @@ function RowsOrColumnsControl({ editorStateParams, setStateParamValue }: AggCont }, ]; const onChange = useCallback( - optionId => setStateParamValue(PARAMS.NAME, optionId === PARAMS.ROWS), + (optionId) => setStateParamValue(PARAMS.NAME, optionId === PARAMS.ROWS), [setStateParamValue] ); diff --git a/src/plugins/vis_default_editor/public/components/controls/size.tsx b/src/plugins/vis_default_editor/public/components/controls/size.tsx index 9f55eb9212dee..159607cbdbd57 100644 --- a/src/plugins/vis_default_editor/public/components/controls/size.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/size.tsx @@ -59,7 +59,7 @@ function SizeParamEditor({ > setValue(ev.target.value === '' ? '' : parseFloat(ev.target.value))} + onChange={(ev) => setValue(ev.target.value === '' ? '' : parseFloat(ev.target.value))} fullWidth={true} compressed isInvalid={showValidation ? !isValid : false} diff --git a/src/plugins/vis_default_editor/public/components/controls/string.tsx b/src/plugins/vis_default_editor/public/components/controls/string.tsx index 67120d85406f9..a2bde27f669eb 100644 --- a/src/plugins/vis_default_editor/public/components/controls/string.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/string.tsx @@ -37,7 +37,7 @@ function StringParamEditor({ setValidity(isValid); }, [isValid, setValidity]); - const onChange = useCallback(ev => setValue(ev.target.value), [setValue]); + const onChange = useCallback((ev) => setValue(ev.target.value), [setValue]); return ( setValue(ev.target.checked)} + onChange={(ev) => setValue(ev.target.checked)} /> diff --git a/src/plugins/vis_default_editor/public/components/controls/top_aggregate.tsx b/src/plugins/vis_default_editor/public/components/controls/top_aggregate.tsx index 66abb88b97d29..1ef3f1b49ae0a 100644 --- a/src/plugins/vis_default_editor/public/components/controls/top_aggregate.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/top_aggregate.tsx @@ -91,7 +91,7 @@ export function TopAggregateParamEditor({ } if (value) { - if (aggParam.options.find(opt => opt.value === value.value)) { + if (aggParam.options.find((opt) => opt.value === value.value)) { return; } @@ -99,7 +99,7 @@ export function TopAggregateParamEditor({ } if (filteredOptions.length === 1) { - setValue(aggParam.options.find(opt => opt.value === filteredOptions[0].value)); + setValue(aggParam.options.find((opt) => opt.value === filteredOptions[0].value)); } }, [aggParam.options, fieldType, filteredOptions, setValue, value]); @@ -107,7 +107,7 @@ export function TopAggregateParamEditor({ if (event.target.value === emptyValue.value) { setValue(); } else { - setValue(aggParam.options.find(opt => opt.value === event.target.value)); + setValue(aggParam.options.find((opt) => opt.value === event.target.value)); } }; diff --git a/src/plugins/vis_default_editor/public/components/controls/use_geocentroid.tsx b/src/plugins/vis_default_editor/public/components/controls/use_geocentroid.tsx index ce22794a7aef8..02c3480928263 100644 --- a/src/plugins/vis_default_editor/public/components/controls/use_geocentroid.tsx +++ b/src/plugins/vis_default_editor/public/components/controls/use_geocentroid.tsx @@ -33,7 +33,7 @@ function UseGeocentroidParamEditor({ value = false, setValue }: AggParamEditorPr compressed={true} label={label} checked={value} - onChange={ev => setValue(ev.target.checked)} + onChange={(ev) => setValue(ev.target.checked)} /> ); diff --git a/src/plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts b/src/plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts index f4c0814748ebc..ee24e2b42113d 100644 --- a/src/plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts +++ b/src/plugins/vis_default_editor/public/components/controls/utils/agg_utils.ts @@ -54,7 +54,7 @@ function useFallbackMetric( // ensure that metric is set to a valid agg const respAgg = metricAggs .filter(isCompatibleAgg) - .find(aggregation => aggregation.id === value); + .find((aggregation) => aggregation.id === value); if (!respAgg && value !== fallbackValue) { setValue(fallbackValue); @@ -76,7 +76,7 @@ function useAvailableOptions( const options = useMemo( () => [ - ...metricAggs.map(respAgg => ({ + ...metricAggs.map((respAgg) => ({ text: i18n.translate('visDefaultEditor.controls.definiteMetricLabel', { defaultMessage: 'Metric: {metric}', values: { diff --git a/src/plugins/vis_default_editor/public/components/controls/utils/strings/comma_separated_list.ts b/src/plugins/vis_default_editor/public/components/controls/utils/strings/comma_separated_list.ts index af14227382164..050a2b1b290cf 100644 --- a/src/plugins/vis_default_editor/public/components/controls/utils/strings/comma_separated_list.ts +++ b/src/plugins/vis_default_editor/public/components/controls/utils/strings/comma_separated_list.ts @@ -24,6 +24,6 @@ export function parseCommaSeparatedList(input: any) { return String(input || '') .split(',') - .map(word => word.trim()) + .map((word) => word.trim()) .filter(Boolean); } diff --git a/src/plugins/vis_default_editor/public/components/sidebar/controls.tsx b/src/plugins/vis_default_editor/public/components/sidebar/controls.tsx index db9d7d9e3316a..2e4fcb4fa35aa 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/controls.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/controls.tsx @@ -52,7 +52,7 @@ function DefaultEditorControls({ }: DefaultEditorControlsProps) { const { enableAutoApply } = vis.type.editorConfig; const [autoApplyEnabled, setAutoApplyEnabled] = useState(false); - const toggleAutoApply = useCallback(e => setAutoApplyEnabled(e.target.checked), []); + const toggleAutoApply = useCallback((e) => setAutoApplyEnabled(e.target.checked), []); const onClickDiscard = useCallback(() => dispatch(discardChanges(vis)), [dispatch, vis]); useDebounce( diff --git a/src/plugins/vis_default_editor/public/components/sidebar/data_tab.tsx b/src/plugins/vis_default_editor/public/components/sidebar/data_tab.tsx index 0466c64541e23..26567d05e0427 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/data_tab.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/data_tab.tsx @@ -76,10 +76,10 @@ function DefaultEditorDataTab({ ); const lastParentPipelineAggTitle = lastParentPipelineAgg && lastParentPipelineAgg.type.title; - const addSchema: AddSchema = useCallback(schema => dispatch(addNewAgg(schema)), [dispatch]); + const addSchema: AddSchema = useCallback((schema) => dispatch(addNewAgg(schema)), [dispatch]); const onAggRemove: DefaultEditorAggCommonProps['removeAgg'] = useCallback( - aggId => dispatch(removeAgg(aggId, schemas.all || [])), + (aggId) => dispatch(removeAgg(aggId, schemas.all || [])), [dispatch, schemas] ); diff --git a/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx b/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx index 68b7ab06c4875..837dd9bff2c6d 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/sidebar.tsx @@ -66,10 +66,10 @@ function DefaultEditorSideBar({ ]); const metricSchemas = (vis.type.schemas.metrics || []).map((s: Schema) => s.name); const metricAggs = useMemo( - () => responseAggs.filter(agg => metricSchemas.includes(get(agg, 'schema'))), + () => responseAggs.filter((agg) => metricSchemas.includes(get(agg, 'schema'))), [responseAggs, metricSchemas] ); - const hasHistogramAgg = useMemo(() => responseAggs.some(agg => agg.type.name === 'histogram'), [ + const hasHistogramAgg = useMemo(() => responseAggs.some((agg) => agg.type.name === 'histogram'), [ responseAggs, ]); @@ -100,7 +100,9 @@ function DefaultEditorSideBar({ vis.setState({ ...vis.serialize(), params: state.params, - data: { aggs: state.data.aggs ? (state.data.aggs.aggs.map(agg => agg.toJSON()) as any) : [] }, + data: { + aggs: state.data.aggs ? (state.data.aggs.aggs.map((agg) => agg.toJSON()) as any) : [], + }, }); eventEmitter.emit('updateVis'); eventEmitter.emit('dirtyStateChange', { @@ -110,7 +112,7 @@ function DefaultEditorSideBar({ }, [vis, state, formState.invalid, setTouched, isDirty, eventEmitter]); const onSubmit: KeyboardEventHandler = useCallback( - event => { + (event) => { if (event.ctrlKey && event.keyCode === keyCodes.ENTER) { event.preventDefault(); event.stopPropagation(); diff --git a/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx b/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx index c2f4c8830e9bf..ebc92170c8735 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx +++ b/src/plugins/vis_default_editor/public/components/sidebar/sidebar_title.tsx @@ -58,7 +58,7 @@ export function LinkedSearch({ savedSearch, eventEmitter }: LinkedSearchProps) { } = useKibana(); const closePopover = useCallback(() => setShowPopover(false), []); - const onClickButtonLink = useCallback(() => setShowPopover(v => !v), []); + const onClickButtonLink = useCallback(() => setShowPopover((v) => !v), []); const onClickUnlikFromSavedSearch = useCallback(() => { setShowPopover(false); eventEmitter.emit('unlinkFromSavedSearch'); diff --git a/src/plugins/vis_default_editor/public/components/sidebar/state/actions.ts b/src/plugins/vis_default_editor/public/components/sidebar/state/actions.ts index 16c3632bed697..0e2724ecc08a8 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/state/actions.ts +++ b/src/plugins/vis_default_editor/public/components/sidebar/state/actions.ts @@ -92,14 +92,14 @@ export interface EditorActions { updateStateParams(params: VisParams): UpdateStateParams; } -const addNewAgg: EditorActions['addNewAgg'] = schema => ({ +const addNewAgg: EditorActions['addNewAgg'] = (schema) => ({ type: EditorStateActionTypes.ADD_NEW_AGG, payload: { schema, }, }); -const discardChanges: EditorActions['discardChanges'] = vis => ({ +const discardChanges: EditorActions['discardChanges'] = (vis) => ({ type: EditorStateActionTypes.DISCARD_CHANGES, payload: vis, }); @@ -153,7 +153,7 @@ const toggleEnabledAgg: EditorActions['toggleEnabledAgg'] = (aggId, enabled) => }, }); -const updateStateParams: EditorActions['updateStateParams'] = params => ({ +const updateStateParams: EditorActions['updateStateParams'] = (params) => ({ type: EditorStateActionTypes.UPDATE_STATE_PARAMS, payload: { params, diff --git a/src/plugins/vis_default_editor/public/components/sidebar/state/editor_form_state.ts b/src/plugins/vis_default_editor/public/components/sidebar/state/editor_form_state.ts index 1f98a5f7fa7df..7b75727fa9f1f 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/state/editor_form_state.ts +++ b/src/plugins/vis_default_editor/public/components/sidebar/state/editor_form_state.ts @@ -32,7 +32,7 @@ function useEditorFormState() { const [formState, setFormState] = useState(initialFormState); const setValidity: SetValidity = useCallback((modelName, value) => { - setFormState(model => { + setFormState((model) => { const validity = { ...model.validity, [modelName]: value, @@ -41,7 +41,7 @@ function useEditorFormState() { return { ...model, validity, - invalid: Object.values(validity).some(valid => !valid), + invalid: Object.values(validity).some((valid) => !valid), }; }); }, []); @@ -51,7 +51,7 @@ function useEditorFormState() { }, []); const setTouched = useCallback((touched: boolean) => { - setFormState(model => ({ + setFormState((model) => ({ ...model, touched, })); diff --git a/src/plugins/vis_default_editor/public/components/sidebar/state/reducers.ts b/src/plugins/vis_default_editor/public/components/sidebar/state/reducers.ts index 4e7a2904584da..f5efb6263166a 100644 --- a/src/plugins/vis_default_editor/public/components/sidebar/state/reducers.ts +++ b/src/plugins/vis_default_editor/public/components/sidebar/state/reducers.ts @@ -43,7 +43,7 @@ const createEditorStateReducer = ({ case EditorStateActionTypes.ADD_NEW_AGG: { const { schema } = action.payload; const defaultConfig = - !state.data.aggs!.aggs.find(agg => agg.schema === schema.name) && schema.defaults + !state.data.aggs!.aggs.find((agg) => agg.schema === schema.name) && schema.defaults ? (schema as any).defaults.slice(0, schema.max) : { schema: schema.name }; const aggConfig = state.data.aggs!.createAggConfig(defaultConfig, { @@ -68,7 +68,7 @@ const createEditorStateReducer = ({ case EditorStateActionTypes.CHANGE_AGG_TYPE: { const { aggId, value } = action.payload; - const newAggs = state.data.aggs!.aggs.map(agg => { + const newAggs = state.data.aggs!.aggs.map((agg) => { if (agg.id === aggId) { agg.type = value; @@ -90,7 +90,7 @@ const createEditorStateReducer = ({ case EditorStateActionTypes.SET_AGG_PARAM_VALUE: { const { aggId, paramName, value } = action.payload; - const newAggs = state.data.aggs!.aggs.map(agg => { + const newAggs = state.data.aggs!.aggs.map((agg) => { if (agg.id === aggId) { const parsedAgg = agg.toJSON(); @@ -131,7 +131,7 @@ const createEditorStateReducer = ({ let isMetric = false; const newAggs = state.data.aggs!.aggs.filter(({ id, schema }) => { if (id === action.payload.aggId) { - const schemaDef = action.payload.schemas.find(s => s.name === schema); + const schemaDef = action.payload.schemas.find((s) => s.name === schema); if (schemaDef && schemaDef.group === AggGroupNames.Metrics) { isMetric = true; } @@ -143,7 +143,7 @@ const createEditorStateReducer = ({ }); if (isMetric && getEnabledMetricAggsCount(newAggs) === 0) { - const aggToEnable = newAggs.find(agg => agg.schema === 'metric'); + const aggToEnable = newAggs.find((agg) => agg.schema === 'metric'); if (aggToEnable) { aggToEnable.enabled = true; @@ -181,7 +181,7 @@ const createEditorStateReducer = ({ case EditorStateActionTypes.TOGGLE_ENABLED_AGG: { const { aggId, enabled } = action.payload; - const newAggs = state.data.aggs!.aggs.map(agg => { + const newAggs = state.data.aggs!.aggs.map((agg) => { if (agg.id === aggId) { const parsedAgg = agg.toJSON(); diff --git a/src/plugins/vis_default_editor/public/default_editor.tsx b/src/plugins/vis_default_editor/public/default_editor.tsx index 43d097345001e..731358bdcbdec 100644 --- a/src/plugins/vis_default_editor/public/default_editor.tsx +++ b/src/plugins/vis_default_editor/public/default_editor.tsx @@ -49,7 +49,7 @@ function DefaultEditor({ const [isCollapsed, setIsCollapsed] = useState(false); const onClickCollapse = useCallback(() => { - setIsCollapsed(value => !value); + setIsCollapsed((value) => !value); }, []); useEffect(() => { diff --git a/src/plugins/vis_default_editor/public/schemas.ts b/src/plugins/vis_default_editor/public/schemas.ts index 26d1cbe91b996..54520b85cb5ec 100644 --- a/src/plugins/vis_default_editor/public/schemas.ts +++ b/src/plugins/vis_default_editor/public/schemas.ts @@ -58,7 +58,7 @@ export class Schemas implements ISchemas { > ) { _(schemas || []) - .map(schema => { + .map((schema) => { if (!schema.name) throw new Error('all schema must have a unique name'); if (schema.name === 'split') { @@ -95,5 +95,5 @@ export class Schemas implements ISchemas { } export const getSchemaByName = (schemas: Schema[], schemaName?: string) => { - return schemas.find(s => s.name === schemaName) || ({} as Schema); + return schemas.find((s) => s.name === schemaName) || ({} as Schema); }; diff --git a/src/plugins/vis_default_editor/public/utils.ts b/src/plugins/vis_default_editor/public/utils.ts index 60eeb49e201a0..d0a9c067e9da2 100644 --- a/src/plugins/vis_default_editor/public/utils.ts +++ b/src/plugins/vis_default_editor/public/utils.ts @@ -45,7 +45,7 @@ export function groupAndSortBy< TLabelName extends string = 'title' >(objects: T[], groupBy: TGroupBy, labelName: TLabelName): ComboBoxGroupedOptions { const groupedOptions = objects.reduce((array, obj) => { - const group = array.find(element => element.label === obj[groupBy]); + const group = array.find((element) => element.label === obj[groupBy]); const option = { label: obj[labelName], target: obj, @@ -62,7 +62,7 @@ export function groupAndSortBy< groupedOptions.sort(sortByLabel); - groupedOptions.forEach(group => { + groupedOptions.forEach((group) => { if (Array.isArray(group.options)) { group.options.sort(sortByLabel); } diff --git a/src/plugins/vis_type_metric/public/components/metric_vis_component.test.tsx b/src/plugins/vis_type_metric/public/components/metric_vis_component.test.tsx index 3969b28d75414..ba32fb2712e68 100644 --- a/src/plugins/vis_type_metric/public/components/metric_vis_component.test.tsx +++ b/src/plugins/vis_type_metric/public/components/metric_vis_component.test.tsx @@ -40,7 +40,7 @@ const baseVisData = { rows: [{ 'col-0': 4301021 }], } as any; -describe('MetricVisComponent', function() { +describe('MetricVisComponent', function () { const vis: ExprVis = { params: { metric: { @@ -74,11 +74,11 @@ describe('MetricVisComponent', function() { expect(getComponent().exists()).toBe(true); }); - it('should render correct structure for single metric', function() { + it('should render correct structure for single metric', function () { expect(getComponent()).toMatchSnapshot(); }); - it('should render correct structure for multi-value metrics', function() { + it('should render correct structure for multi-value metrics', function () { const component = getComponent({ visData: { columns: [ diff --git a/src/plugins/vis_type_metric/public/components/metric_vis_options.tsx b/src/plugins/vis_type_metric/public/components/metric_vis_options.tsx index 009d63ded39b4..ac6ab9e9e69a8 100644 --- a/src/plugins/vis_type_metric/public/components/metric_vis_options.tsx +++ b/src/plugins/vis_type_metric/public/components/metric_vis_options.tsx @@ -86,7 +86,7 @@ function MetricVisOptions({ ); const setColorMode: EuiButtonGroupProps['onChange'] = useCallback( - id => setMetricValue('metricColorMode', id as ColorModes), + (id) => setMetricValue('metricColorMode', id as ColorModes), [setMetricValue] ); diff --git a/src/plugins/vis_type_table/public/agg_table/agg_table.js b/src/plugins/vis_type_table/public/agg_table/agg_table.js index 6b5796d6eb5bc..abea5fa06693a 100644 --- a/src/plugins/vis_type_table/public/agg_table/agg_table.js +++ b/src/plugins/vis_type_table/public/agg_table/agg_table.js @@ -37,12 +37,12 @@ export function KbnAggTable(config, RecursionHelper) { filter: '=', }, controllerAs: 'aggTable', - compile: function($el) { + compile: function ($el) { // Use the compile function from the RecursionHelper, // And return the linking function(s) which it returns return RecursionHelper.compile($el); }, - controller: function($scope) { + controller: function ($scope) { const self = this; self._saveAs = require('@elastic/filesaver').saveAs; @@ -51,12 +51,12 @@ export function KbnAggTable(config, RecursionHelper) { quoteValues: config.get('csv:quoteValues'), }; - self.exportAsCsv = function(formatted) { + self.exportAsCsv = function (formatted) { const csv = new Blob([self.toCsv(formatted)], { type: 'text/plain;charset=utf-8' }); self._saveAs(csv, self.csv.filename); }; - self.toCsv = function(formatted) { + self.toCsv = function (formatted) { const rows = $scope.table.rows; const columns = formatted ? $scope.formattedColumns : $scope.table.columns; const nonAlphaNumRE = /[^a-zA-Z0-9]/; @@ -72,9 +72,9 @@ export function KbnAggTable(config, RecursionHelper) { } // escape each cell in each row - const csvRows = rows.map(function(row) { + const csvRows = rows.map(function (row) { return Object.entries(row).map(([k, v]) => { - const column = columns.find(c => c.id === k); + const column = columns.find((c) => c.id === k); if (formatted && column) { return escape(column.formatter.convert(v)); } @@ -84,13 +84,13 @@ export function KbnAggTable(config, RecursionHelper) { // add the columns to the rows csvRows.unshift( - columns.map(function(col) { + columns.map(function (col) { return escape(formatted ? col.title : col.name); }) ); return csvRows - .map(function(row) { + .map(function (row) { return row.join(self.csv.separator) + '\r\n'; }) .join(''); @@ -98,7 +98,7 @@ export function KbnAggTable(config, RecursionHelper) { $scope.$watchMulti( ['table', 'exportTitle', 'percentageCol', 'totalFunc', '=scope.dimensions'], - function() { + function () { const { table, exportTitle, percentageCol } = $scope; const showPercentage = percentageCol !== ''; @@ -117,13 +117,13 @@ export function KbnAggTable(config, RecursionHelper) { const { buckets, metrics, splitColumn } = $scope.dimensions; $scope.formattedColumns = table.columns - .map(function(col, i) { - const isBucket = buckets.find(bucket => bucket.accessor === i); + .map(function (col, i) { + const isBucket = buckets.find((bucket) => bucket.accessor === i); const isSplitColumn = splitColumn - ? splitColumn.find(splitColumn => splitColumn.accessor === i) + ? splitColumn.find((splitColumn) => splitColumn.accessor === i) : undefined; const dimension = - isBucket || isSplitColumn || metrics.find(metric => metric.accessor === i); + isBucket || isSplitColumn || metrics.find((metric) => metric.accessor === i); if (!dimension) return; @@ -152,10 +152,10 @@ export function KbnAggTable(config, RecursionHelper) { } if (allowsNumericalAggregations || isDate || totalFunc === 'count') { - const sum = tableRows => { + const sum = (tableRows) => { return _.reduce( tableRows, - function(prev, curr) { + function (prev, curr) { // some metrics return undefined for some of the values // derivative is an example of this as it returns undefined in the first row if (curr[col.id] === undefined) return prev; @@ -184,19 +184,13 @@ export function KbnAggTable(config, RecursionHelper) { break; } case 'min': { - const total = _.chain(table.rows) - .map(col.id) - .min() - .value(); + const total = _.chain(table.rows).map(col.id).min().value(); formattedColumn.formattedTotal = formatter.convert(total); formattedColumn.total = total; break; } case 'max': { - const total = _.chain(table.rows) - .map(col.id) - .max() - .value(); + const total = _.chain(table.rows).map(col.id).max().value(); formattedColumn.formattedTotal = formatter.convert(total); formattedColumn.total = total; break; @@ -214,7 +208,7 @@ export function KbnAggTable(config, RecursionHelper) { return formattedColumn; }) - .filter(column => column); + .filter((column) => column); if (showPercentage) { const insertAtIndex = _.findIndex($scope.formattedColumns, { title: percentageCol }); @@ -257,7 +251,7 @@ function addPercentageCol(columns, title, rows, insertAtIndex) { id: newId, formatter, }); - const newRows = rows.map(row => ({ + const newRows = rows.map((row) => ({ [newId]: row[id] / sumTotal, ...row, })); diff --git a/src/plugins/vis_type_table/public/agg_table/agg_table_group.js b/src/plugins/vis_type_table/public/agg_table/agg_table_group.js index 95ee64251026f..fb17a558ca0d8 100644 --- a/src/plugins/vis_type_table/public/agg_table/agg_table_group.js +++ b/src/plugins/vis_type_table/public/agg_table/agg_table_group.js @@ -34,12 +34,12 @@ export function KbnAggTableGroup(RecursionHelper) { percentageCol: '=', filter: '=', }, - compile: function($el) { + compile: function ($el) { // Use the compile function from the RecursionHelper, // And return the linking function(s) which it returns return RecursionHelper.compile($el, { - post: function($scope) { - $scope.$watch('group', function(group) { + post: function ($scope) { + $scope.$watch('group', function (group) { // clear the previous "state" $scope.rows = $scope.columns = false; diff --git a/src/plugins/vis_type_table/public/components/table_vis_options.tsx b/src/plugins/vis_type_table/public/components/table_vis_options.tsx index 837d478535936..d220a6b2db842 100644 --- a/src/plugins/vis_type_table/public/components/table_vis_options.tsx +++ b/src/plugins/vis_type_table/public/components/table_vis_options.tsx @@ -46,7 +46,7 @@ function TableOptions({ }), }, ...tabifyGetColumns(aggs.getResponseAggs(), true) - .filter(col => get(col.aggConfig.type.getFormat(col.aggConfig), 'type.id') === 'number') + .filter((col) => get(col.aggConfig.type.getFormat(col.aggConfig), 'type.id') === 'number') .map(({ name }) => ({ value: name, text: name })), ], [aggs] diff --git a/src/plugins/vis_type_table/public/get_inner_angular.ts b/src/plugins/vis_type_table/public/get_inner_angular.ts index 732e99a593f17..4e4269a1f44f4 100644 --- a/src/plugins/vis_type_table/public/get_inner_angular.ts +++ b/src/plugins/vis_type_table/public/get_inner_angular.ts @@ -71,7 +71,7 @@ function createLocalPrivateModule() { } function createLocalConfigModule(uiSettings: IUiSettingsClient) { - angular.module('tableVisConfig', []).provider('config', function() { + angular.module('tableVisConfig', []).provider('config', function () { return { $get: () => ({ get: (value: string) => { diff --git a/src/plugins/vis_type_table/public/paginated_table/paginated_table.js b/src/plugins/vis_type_table/public/paginated_table/paginated_table.js index 9b82a3d4baa4b..b1810e7143326 100644 --- a/src/plugins/vis_type_table/public/paginated_table/paginated_table.js +++ b/src/plugins/vis_type_table/public/paginated_table/paginated_table.js @@ -42,14 +42,14 @@ export function PaginatedTable($filter) { percentageCol: '=', }, controllerAs: 'paginatedTable', - controller: function($scope) { + controller: function ($scope) { const self = this; self.sort = { columnIndex: null, direction: null, }; - self.sortColumn = function(colIndex, sortDirection = 'asc') { + self.sortColumn = function (colIndex, sortDirection = 'asc') { const col = $scope.columns[colIndex]; if (!col) return; diff --git a/src/plugins/vis_type_table/public/paginated_table/paginated_table.test.ts b/src/plugins/vis_type_table/public/paginated_table/paginated_table.test.ts index 23e4aee0378dc..de253f26ff9e7 100644 --- a/src/plugins/vis_type_table/public/paginated_table/paginated_table.test.ts +++ b/src/plugins/vis_type_table/public/paginated_table/paginated_table.test.ts @@ -100,7 +100,7 @@ describe('Table Vis - Paginated table', () => { let rows: Row[] = []; if (isNumber(colCount)) { - times(colCount, i => { + times(colCount, (i) => { columns.push({ id: `${i}`, title: `column${i}`, formatter: { convert: identity } }); }); } else { @@ -115,10 +115,10 @@ describe('Table Vis - Paginated table', () => { } if (isNumber(rowCount)) { - times(rowCount, row => { + times(rowCount, (row) => { const rowItems: Row = {}; - times(columns.length, col => { + times(columns.length, (col) => { rowItems[`${col}`] = `item-${col}-${row}`; }); @@ -192,34 +192,10 @@ describe('Table Vis - Paginated table', () => { const tableRows = $el.find('tbody tr'); // should contain the row data - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe(rows[0][0]); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe(rows[0][1]); - expect( - tableRows - .eq(1) - .find('td') - .eq(0) - .text() - ).toBe(rows[1][0]); - expect( - tableRows - .eq(1) - .find('td') - .eq(1) - .text() - ).toBe(rows[1][1]); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe(rows[0][0]); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe(rows[0][1]); + expect(tableRows.eq(1).find('td').eq(0).text()).toBe(rows[1][0]); + expect(tableRows.eq(1).find('td').eq(1).text()).toBe(rows[1][1]); }); test('should paginate rows', () => { @@ -281,20 +257,8 @@ describe('Table Vis - Paginated table', () => { test('should not sort by default', () => { const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe(data.rows[0][0]); - expect( - tableRows - .eq(lastRowIndex) - .find('td') - .eq(0) - .text() - ).toBe(data.rows[lastRowIndex][0]); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe(data.rows[0][0]); + expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe(data.rows[lastRowIndex][0]); }); test('should do nothing when sorting by invalid column id', () => { @@ -303,27 +267,9 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('bbbb'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(0) - .find('td') - .eq(2) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('bbbb'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(2).text()).toBe('zzzz'); }); test('should do nothing when sorting by non sortable column', () => { @@ -334,27 +280,9 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('bbbb'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(0) - .find('td') - .eq(2) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('bbbb'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(2).text()).toBe('zzzz'); }); test("should set the sort direction to asc when it's not explicitly set", () => { @@ -362,27 +290,9 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(2) - .find('td') - .eq(1) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(1) - .find('td') - .eq(1) - .text() - ).toBe('bbbb'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('aaaa'); + expect(tableRows.eq(2).find('td').eq(1).text()).toBe('cccc'); + expect(tableRows.eq(1).find('td').eq(1).text()).toBe('bbbb'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa'); }); test('should allow you to explicitly set the sort direction', () => { @@ -390,27 +300,9 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('zzzz'); - expect( - tableRows - .eq(1) - .find('td') - .eq(1) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(2) - .find('td') - .eq(1) - .text() - ).toBe('bbbb'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('zzzz'); + expect(tableRows.eq(1).find('td').eq(1).text()).toBe('cccc'); + expect(tableRows.eq(2).find('td').eq(1).text()).toBe('bbbb'); }); test('should sort ascending on first invocation', () => { @@ -419,20 +311,8 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(lastRowIndex) - .find('td') - .eq(0) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('aaaa'); + expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('zzzz'); }); test('should sort descending on second invocation', () => { @@ -442,20 +322,8 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('zzzz'); - expect( - tableRows - .eq(lastRowIndex) - .find('td') - .eq(0) - .text() - ).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('zzzz'); + expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('aaaa'); }); test('should clear sorting on third invocation', () => { @@ -466,20 +334,8 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe(data.rows[0][0]); - expect( - tableRows - .eq(lastRowIndex) - .find('td') - .eq(0) - .text() - ).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe(data.rows[0][0]); + expect(tableRows.eq(lastRowIndex).find('td').eq(0).text()).toBe('aaaa'); }); test('should sort new column ascending', () => { @@ -492,20 +348,8 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(lastRowIndex) - .find('td') - .eq(1) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('aaaa'); + expect(tableRows.eq(lastRowIndex).find('td').eq(1).text()).toBe('zzzz'); }); }); @@ -539,48 +383,12 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); const tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(0) - .find('td') - .eq(2) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(1) - .find('td') - .eq(2) - .text() - ).toBe('bbbb'); - expect( - tableRows - .eq(2) - .find('td') - .eq(2) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(3) - .find('td') - .eq(2) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('cccc'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('cccc'); + expect(tableRows.eq(0).find('td').eq(2).text()).toBe('aaaa'); + expect(tableRows.eq(1).find('td').eq(2).text()).toBe('bbbb'); + expect(tableRows.eq(2).find('td').eq(2).text()).toBe('cccc'); + expect(tableRows.eq(3).find('td').eq(2).text()).toBe('zzzz'); }); test('should sort correctly between columns', () => { @@ -589,76 +397,22 @@ describe('Table Vis - Paginated table', () => { $scope.$digest(); let tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(0) - .find('td') - .eq(2) - .text() - ).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('cccc'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('cccc'); + expect(tableRows.eq(0).find('td').eq(2).text()).toBe('aaaa'); // sort by the first column paginatedTable.sortColumn(0); $scope.$digest(); tableRows = $el.find('tbody tr'); - expect( - tableRows - .eq(0) - .find('td') - .eq(0) - .text() - ).toBe('aaaa'); - expect( - tableRows - .eq(0) - .find('td') - .eq(1) - .text() - ).toBe('zzzz'); - expect( - tableRows - .eq(0) - .find('td') - .eq(2) - .text() - ).toBe('cccc'); - - expect( - tableRows - .eq(1) - .find('td') - .eq(0) - .text() - ).toBe('bbbb'); - expect( - tableRows - .eq(2) - .find('td') - .eq(0) - .text() - ).toBe('cccc'); - expect( - tableRows - .eq(3) - .find('td') - .eq(0) - .text() - ).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(0).text()).toBe('aaaa'); + expect(tableRows.eq(0).find('td').eq(1).text()).toBe('zzzz'); + expect(tableRows.eq(0).find('td').eq(2).text()).toBe('cccc'); + + expect(tableRows.eq(1).find('td').eq(0).text()).toBe('bbbb'); + expect(tableRows.eq(2).find('td').eq(0).text()).toBe('cccc'); + expect(tableRows.eq(3).find('td').eq(0).text()).toBe('zzzz'); }); test('should not sort duplicate columns', () => { @@ -682,7 +436,7 @@ describe('Table Vis - Paginated table', () => { title: 'object test', id: '0', formatter: { - convert: val => { + convert: (val) => { return val === 'zzz' ? '

hello

' : val; }, }, diff --git a/src/plugins/vis_type_table/public/paginated_table/rows.js b/src/plugins/vis_type_table/public/paginated_table/rows.js index 2939534c6fa8d..d2192a5843644 100644 --- a/src/plugins/vis_type_table/public/paginated_table/rows.js +++ b/src/plugins/vis_type_table/public/paginated_table/rows.js @@ -24,7 +24,7 @@ import tableCellFilterHtml from './table_cell_filter.html'; export function KbnRows($compile) { return { restrict: 'A', - link: function($scope, $el, attr) { + link: function ($scope, $el, attr) { function addCell($tr, contents, column, row) { function createCell() { return $(document.createElement('td')); @@ -46,8 +46,8 @@ export function KbnRows($compile) { data: [ { table: $scope.table, - row: $scope.rows.findIndex(r => r === row), - column: $scope.table.columns.findIndex(c => c.id === column.id), + row: $scope.rows.findIndex((r) => r === row), + column: $scope.table.columns.findIndex((c) => c.id === column.id), value, }, ], @@ -103,7 +103,7 @@ export function KbnRows($compile) { $tr.append($cell); } - $scope.$watchMulti([attr.kbnRows, attr.kbnRowsMin], function(vals) { + $scope.$watchMulti([attr.kbnRows, attr.kbnRowsMin], function (vals) { let rows = vals[0]; const min = vals[1]; @@ -117,14 +117,14 @@ export function KbnRows($compile) { // crate the empty row which will be pushed into the row list over and over const emptyRow = {}; // push as many empty rows into the row array as needed - _.times(min - rows.length, function() { + _.times(min - rows.length, function () { rows.push(emptyRow); }); } - rows.forEach(function(row) { + rows.forEach(function (row) { const $tr = $(document.createElement('tr')).appendTo($el); - $scope.columns.forEach(column => { + $scope.columns.forEach((column) => { const value = row[column.id]; addCell($tr, value, column, row); }); diff --git a/src/plugins/vis_type_table/public/table_vis_controller.js b/src/plugins/vis_type_table/public/table_vis_controller.js index 04ddb3f7bb1d4..8a620df986090 100644 --- a/src/plugins/vis_type_table/public/table_vis_controller.js +++ b/src/plugins/vis_type_table/public/table_vis_controller.js @@ -23,7 +23,7 @@ export function TableVisController($scope) { assign($scope.visParams.sort, uiStateSort); $scope.sort = $scope.visParams.sort; - $scope.$watchCollection('sort', function(newSort) { + $scope.$watchCollection('sort', function (newSort) { $scope.uiState.set('vis.params.sort', newSort); }); @@ -32,7 +32,7 @@ export function TableVisController($scope) { * - the underlying data changes (esResponse) * - one of the view options changes (vis.params) */ - $scope.$watch('renderComplete', function() { + $scope.$watch('renderComplete', function () { let tableGroups = ($scope.tableGroups = null); let hasSomeRows = ($scope.hasSomeRows = null); diff --git a/src/plugins/vis_type_tagcloud/public/components/tag_cloud.js b/src/plugins/vis_type_tagcloud/public/components/tag_cloud.js index fae7cdf797958..e48515d243844 100644 --- a/src/plugins/vis_type_tagcloud/public/components/tag_cloud.js +++ b/src/plugins/vis_type_tagcloud/public/components/tag_cloud.js @@ -23,10 +23,10 @@ import { EventEmitter } from 'events'; const ORIENTATIONS = { single: () => 0, - 'right angled': tag => { + 'right angled': (tag) => { return hashWithinRange(tag.text, 2) * 90; }, - multiple: tag => { + multiple: (tag) => { return hashWithinRange(tag.text, 12) * 15 - 90; //fan out 12 * 15 degrees over top-right and bottom-right quadrant (=-90 deg offset) }, }; @@ -167,7 +167,7 @@ export class TagCloud extends EventEmitter { } async _pickPendingJob() { - return await new Promise(resolve => { + return await new Promise((resolve) => { this._setTimeoutId = setTimeout(async () => { const job = this._pendingJob; this._pendingJob = null; @@ -201,7 +201,7 @@ export class TagCloud extends EventEmitter { const svgTextNodes = this._svgGroup.selectAll('text'); const stage = svgTextNodes.data(job.words, getText); - await new Promise(resolve => { + await new Promise((resolve) => { const enterSelection = stage.enter(); const enteringTags = enterSelection.append('text'); enteringTags.style('font-size', getSizeInPixels); @@ -216,13 +216,13 @@ export class TagCloud extends EventEmitter { const self = this; enteringTags.on({ - click: function(event) { + click: function (event) { self.emit('select', event); }, - mouseover: function() { + mouseover: function () { d3.select(this).style('cursor', 'pointer'); }, - mouseout: function() { + mouseout: function () { d3.select(this).style('cursor', 'default'); }, }); @@ -288,7 +288,7 @@ export class TagCloud extends EventEmitter { return { refreshLayout: false, size: this._size.slice(), - words: this._completedJob.words.map(tag => { + words: this._completedJob.words.map((tag) => { return { x: tag.x, y: tag.y, @@ -329,7 +329,7 @@ export class TagCloud extends EventEmitter { tagCloudLayoutGenerator.font(this._fontFamily); tagCloudLayoutGenerator.fontStyle(this._fontStyle); tagCloudLayoutGenerator.fontWeight(this._fontWeight); - tagCloudLayoutGenerator.fontSize(tag => mapSizeToFontSize(tag.value)); + tagCloudLayoutGenerator.fontSize((tag) => mapSizeToFontSize(tag.value)); tagCloudLayoutGenerator.random(seed); tagCloudLayoutGenerator.spiral(this._spiral); tagCloudLayoutGenerator.words(job.words); @@ -337,7 +337,7 @@ export class TagCloud extends EventEmitter { tagCloudLayoutGenerator.timeInterval(this._timeInterval); this._layoutIsUpdating = true; - await new Promise(resolve => { + await new Promise((resolve) => { tagCloudLayoutGenerator.on('end', () => { this._layoutIsUpdating = false; resolve(true); @@ -353,7 +353,7 @@ export class TagCloud extends EventEmitter { getDebugInfo() { const debug = {}; debug.positions = this._completedJob - ? this._completedJob.words.map(tag => { + ? this._completedJob.words.map((tag) => { return { displayText: tag.displayText, rawText: tag.rawText || tag.text, diff --git a/src/plugins/vis_type_tagcloud/public/components/tag_cloud_visualization.js b/src/plugins/vis_type_tagcloud/public/components/tag_cloud_visualization.js index 4094f2ab59158..e43b3bdc747ab 100644 --- a/src/plugins/vis_type_tagcloud/public/components/tag_cloud_visualization.js +++ b/src/plugins/vis_type_tagcloud/public/components/tag_cloud_visualization.js @@ -51,7 +51,7 @@ export function createTagCloudVisualization({ colors }) { this._vis = vis; this._truncated = false; this._tagCloud = new TagCloud(cloudContainer, colorScale); - this._tagCloud.on('select', event => { + this._tagCloud.on('select', (event) => { if (!this._visParams.bucket) { return; } diff --git a/src/plugins/vis_type_timelion/common/lib/calculate_interval.test.ts b/src/plugins/vis_type_timelion/common/lib/calculate_interval.test.ts index 17e8a01911071..d2eb0a58444eb 100644 --- a/src/plugins/vis_type_timelion/common/lib/calculate_interval.test.ts +++ b/src/plugins/vis_type_timelion/common/lib/calculate_interval.test.ts @@ -22,9 +22,7 @@ import { calculateInterval as fn } from './calculate_interval'; import moment, { unitOfTime } from 'moment'; const from = (count: number, unit: unitOfTime.DurationConstructor) => - moment() - .subtract(count, unit) - .valueOf(); + moment().subtract(count, unit).valueOf(); const to = moment().valueOf(); const size = 200; const min = '1ms'; diff --git a/src/plugins/vis_type_timelion/common/lib/to_milliseconds.ts b/src/plugins/vis_type_timelion/common/lib/to_milliseconds.ts index f6fcb08b48b25..3dfa4602a9525 100644 --- a/src/plugins/vis_type_timelion/common/lib/to_milliseconds.ts +++ b/src/plugins/vis_type_timelion/common/lib/to_milliseconds.ts @@ -38,7 +38,7 @@ const unitMappings = [ ] as Units[][]; const vals = {} as Values; -unitMappings.forEach(units => { +unitMappings.forEach((units) => { const normal = moment.normalizeUnits(units[0]) as Units; const val = moment.duration(1, normal).asMilliseconds(); ([] as Units[]).concat(normal, units).forEach((unit: Units) => { diff --git a/src/plugins/vis_type_timelion/public/components/panel.tsx b/src/plugins/vis_type_timelion/public/components/panel.tsx index 8f796526e8520..4c28e4e5a18ab 100644 --- a/src/plugins/vis_type_timelion/public/components/panel.tsx +++ b/src/plugins/vis_type_timelion/public/components/panel.tsx @@ -83,13 +83,13 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { const [legendValueNumbers, setLegendValueNumbers] = useState(); const [legendCaption, setLegendCaption] = useState(); - const canvasRef = useCallback(node => { + const canvasRef = useCallback((node) => { if (node !== null) { setCanvasElem(node); } }, []); - const elementRef = useCallback(node => { + const elementRef = useCallback((node) => { if (node !== null) { setChartElem(node); } @@ -97,10 +97,7 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { useEffect( () => () => { - $(chartElem) - .off('plotselected') - .off('plothover') - .off('mouseleave'); + $(chartElem).off('plotselected').off('plothover').off('mouseleave'); }, [chartElem] ); @@ -113,7 +110,7 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { } setHighlightedSeries(id); - setChart(chartState => + setChart((chartState) => chartState.map((series: Series, seriesIndex: number) => { series.color = seriesIndex === id @@ -139,7 +136,7 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { const toggleSeries = useCallback(({ currentTarget }: JQuery.TriggeredEvent) => { const id = Number(currentTarget.getAttribute(SERIES_ID_ATTR)); - setChart(chartState => + setChart((chartState) => chartState.map((series: Series, seriesIndex: number) => { if (seriesIndex === id) { series._hide = !series._hide; @@ -169,10 +166,7 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { // legend has been re-created. Apply focus on legend element when previously set if (focusedSeries || focusedSeries === 0) { - canvasNode - .find('div.legend table .legendLabel>span') - .get(focusedSeries) - .focus(); + canvasNode.find('div.legend table .legendLabel>span').get(focusedSeries).focus(); } } }, @@ -241,7 +235,7 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { setHighlightedSeries(null); setFocusedSeries(null); - setChart(chartState => + setChart((chartState) => chartState.map((series: Series) => { series.color = originalColorMap.get(series); // reset the colors return series; @@ -349,25 +343,19 @@ function Panel({ interval, seriesList, renderComplete }: PanelProps) { useEffect(() => { if (chartElem) { - $(chartElem) - .off('plotselected') - .on('plotselected', plotSelectedHandler); + $(chartElem).off('plotselected').on('plotselected', plotSelectedHandler); } }, [chartElem, plotSelectedHandler]); useEffect(() => { if (chartElem) { - $(chartElem) - .off('mouseleave') - .on('mouseleave', mouseLeaveHandler); + $(chartElem).off('mouseleave').on('mouseleave', mouseLeaveHandler); } }, [chartElem, mouseLeaveHandler]); useEffect(() => { if (chartElem) { - $(chartElem) - .off('plothover') - .on('plothover', plotHoverHandler); + $(chartElem).off('plothover').on('plothover', plotHoverHandler); } }, [chartElem, plotHoverHandler]); diff --git a/src/plugins/vis_type_timelion/public/components/timelion_expression_input.tsx b/src/plugins/vis_type_timelion/public/components/timelion_expression_input.tsx index 999409ef35063..8c76b41df0ced 100644 --- a/src/plugins/vis_type_timelion/public/components/timelion_expression_input.tsx +++ b/src/plugins/vis_type_timelion/public/components/timelion_expression_input.tsx @@ -95,7 +95,7 @@ function TimelionExpressionInput({ value, setValue }: TimelionExpressionInputPro useEffect(() => { if (kibana.services.http) { - kibana.services.http.get('../api/timelion/functions').then(data => { + kibana.services.http.get('../api/timelion/functions').then((data) => { functionList.current = data; }); } diff --git a/src/plugins/vis_type_timelion/public/components/timelion_expression_input_helpers.ts b/src/plugins/vis_type_timelion/public/components/timelion_expression_input_helpers.ts index 04cb54306c90e..f7b3433105b76 100644 --- a/src/plugins/vis_type_timelion/public/components/timelion_expression_input_helpers.ts +++ b/src/plugins/vis_type_timelion/public/components/timelion_expression_input_helpers.ts @@ -51,8 +51,8 @@ function getArgumentsHelp( const argsHelp = functionHelp.chainable ? functionHelp.args.slice(1) : functionHelp.args.slice(0); // ignore arguments that are already provided in function declaration - const functionArgNames = functionArgs.map(arg => arg.name); - return argsHelp.filter(arg => !functionArgNames.includes(arg.name)); + const functionArgNames = functionArgs.map((arg) => arg.name); + return argsHelp.filter((arg) => !functionArgNames.includes(arg.name)); } async function extractSuggestionsFromParsedResult( @@ -108,7 +108,7 @@ async function extractSuggestionsFromParsedResult( ); } else { const { suggestions: staticSuggestions } = - functionHelp.args.find(arg => arg.name === activeArg.name) || {}; + functionHelp.args.find((arg) => arg.name === activeArg.name) || {}; valueSuggestions = argValueSuggestions.getStaticSuggestionsForInput( partialInput, staticSuggestions @@ -122,7 +122,7 @@ async function extractSuggestionsFromParsedResult( // return argument suggestions const argsHelp = getArgumentsHelp(functionHelp, activeFunc.arguments); - const argumentSuggestions = argsHelp.filter(arg => { + const argumentSuggestions = argsHelp.filter((arg) => { if (get(activeArg, 'type') === 'namedArg') { return startsWith(arg.name, activeArg.name); } else if (activeArg) { @@ -167,7 +167,7 @@ export async function suggest( if (message.function) { // The user has start typing a function name, so we'll filter the list down to only // possible matches. - list = functionList.filter(func => startsWith(func.name, message.function)); + list = functionList.filter((func) => startsWith(func.name, message.function)); } else { // The user hasn't typed anything yet, so we'll just return the entire list. list = functionList; @@ -176,7 +176,7 @@ export async function suggest( } case 'incompleteArgument': { const { currentFunction: functionName, currentArgs: functionArgs } = message; - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); return { list: getArgumentsHelp(functionHelp, functionArgs), type: SUGGESTION_TYPE.ARGUMENTS, @@ -192,9 +192,9 @@ export async function suggest( functionArgs ); } else { - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); if (functionHelp) { - const argHelp = functionHelp.args.find(arg => arg.name === argName); + const argHelp = functionHelp.args.find((arg) => arg.name === argName); if (argHelp && argHelp.suggestions) { valueSuggestions = argHelp.suggestions; } diff --git a/src/plugins/vis_type_timelion/public/components/timelion_interval.tsx b/src/plugins/vis_type_timelion/public/components/timelion_interval.tsx index 985ecaeaf3e5a..7ed98f0fb802e 100644 --- a/src/plugins/vis_type_timelion/public/components/timelion_interval.tsx +++ b/src/plugins/vis_type_timelion/public/components/timelion_interval.tsx @@ -98,11 +98,11 @@ function TimelionInterval({ value, setValue, setValidity }: TimelionIntervalProp ); const selectedOptions = useMemo( - () => [intervalOptions.find(op => op.value === value) || { label: value, value }], + () => [intervalOptions.find((op) => op.value === value) || { label: value, value }], [value] ); - const isValid = intervalOptions.some(int => int.value === value) || isValidEsInterval(value); + const isValid = intervalOptions.some((int) => int.value === value) || isValidEsInterval(value); useValidation(setValidity, isValid); diff --git a/src/plugins/vis_type_timelion/public/helpers/arg_value_suggestions.ts b/src/plugins/vis_type_timelion/public/helpers/arg_value_suggestions.ts index 76c25b9b9e8de..19ec46bd7f659 100644 --- a/src/plugins/vis_type_timelion/public/helpers/arg_value_suggestions.ts +++ b/src/plugins/vis_type_timelion/public/helpers/arg_value_suggestions.ts @@ -92,8 +92,8 @@ export function getArgValueSuggestions() { perPage: 25, }); return resp.savedObjects - .filter(savedObject => !savedObject.get('type')) - .map(savedObject => { + .filter((savedObject) => !savedObject.get('type')) + .map((savedObject) => { return { name: savedObject.attributes.title }; }); }, @@ -117,7 +117,7 @@ export function getArgValueSuggestions() { const valueSplit = partial.split(':'); return indexPattern.fields - .filter(field => { + .filter((field) => { return ( field.aggregatable && 'number' === field.type && @@ -125,7 +125,7 @@ export function getArgValueSuggestions() { !indexPatternsUtils.isNestedField(field) ); }) - .map(field => { + .map((field) => { return { name: `${valueSplit[0]}:${field.name}`, help: field.type }; }); }, @@ -136,7 +136,7 @@ export function getArgValueSuggestions() { } return indexPattern.fields - .filter(field => { + .filter((field) => { return ( field.aggregatable && ['number', 'boolean', 'date', 'ip', 'string'].includes(field.type) && @@ -144,7 +144,7 @@ export function getArgValueSuggestions() { !indexPatternsUtils.isNestedField(field) ); }) - .map(field => { + .map((field) => { return { name: field.name, help: field.type }; }); }, @@ -155,14 +155,14 @@ export function getArgValueSuggestions() { } return indexPattern.fields - .filter(field => { + .filter((field) => { return ( 'date' === field.type && containsFieldName(partial, field) && !indexPatternsUtils.isNestedField(field) ); }) - .map(field => { + .map((field) => { return { name: field.name }; }); }, @@ -209,7 +209,7 @@ export function getArgValueSuggestions() { staticSuggestions: TimelionFunctionArgs['suggestions'] = [] ) => { if (partialInput) { - return staticSuggestions.filter(suggestion => { + return staticSuggestions.filter((suggestion) => { return suggestion.name.includes(partialInput); }); } diff --git a/src/plugins/vis_type_timelion/public/helpers/tick_formatters.test.ts b/src/plugins/vis_type_timelion/public/helpers/tick_formatters.test.ts index 01734f2f5888a..cbcb869dc2578 100644 --- a/src/plugins/vis_type_timelion/public/helpers/tick_formatters.test.ts +++ b/src/plugins/vis_type_timelion/public/helpers/tick_formatters.test.ts @@ -19,24 +19,24 @@ import { tickFormatters } from './tick_formatters'; -describe('Tick Formatters', function() { +describe('Tick Formatters', function () { let formatters: any; - beforeEach(function() { + beforeEach(function () { formatters = tickFormatters(); }); - describe('Bits mode', function() { + describe('Bits mode', function () { let bitFormatter: any; - beforeEach(function() { + beforeEach(function () { bitFormatter = formatters.bits; }); - it('is a function', function() { + it('is a function', function () { expect(bitFormatter).toEqual(expect.any(Function)); }); - it('formats with b/kb/mb/gb', function() { + it('formats with b/kb/mb/gb', function () { expect(bitFormatter(7)).toEqual('7b'); expect(bitFormatter(4 * 1000)).toEqual('4kb'); expect(bitFormatter(4.1 * 1000 * 1000)).toEqual('4.1mb'); @@ -51,24 +51,24 @@ describe('Tick Formatters', function() { }); }); - describe('Bits/s mode', function() { + describe('Bits/s mode', function () { let bitsFormatter: any; - beforeEach(function() { + beforeEach(function () { bitsFormatter = formatters['bits/s']; }); - it('is a function', function() { + it('is a function', function () { expect(bitsFormatter).toEqual(expect.any(Function)); }); - it('formats with b/kb/mb/gb', function() { + it('formats with b/kb/mb/gb', function () { expect(bitsFormatter(7)).toEqual('7b/s'); expect(bitsFormatter(4 * 1000)).toEqual('4kb/s'); expect(bitsFormatter(4.1 * 1000 * 1000)).toEqual('4.1mb/s'); expect(bitsFormatter(3 * 1000 * 1000 * 1000)).toEqual('3gb/s'); }); - it('formats negative values with b/kb/mb/gb', function() { + it('formats negative values with b/kb/mb/gb', function () { expect(bitsFormatter(-7)).toEqual('-7b/s'); expect(bitsFormatter(-4 * 1000)).toEqual('-4kb/s'); expect(bitsFormatter(-4.1 * 1000 * 1000)).toEqual('-4.1mb/s'); @@ -76,24 +76,24 @@ describe('Tick Formatters', function() { }); }); - describe('Bytes mode', function() { + describe('Bytes mode', function () { let byteFormatter: any; - beforeEach(function() { + beforeEach(function () { byteFormatter = formatters.bytes; }); - it('is a function', function() { + it('is a function', function () { expect(byteFormatter).toEqual(expect.any(Function)); }); - it('formats with B/KB/MB/GB', function() { + it('formats with B/KB/MB/GB', function () { expect(byteFormatter(10)).toEqual('10B'); expect(byteFormatter(10 * 1024)).toEqual('10KB'); expect(byteFormatter(10.2 * 1024 * 1024)).toEqual('10.2MB'); expect(byteFormatter(3 * 1024 * 1024 * 1024)).toEqual('3GB'); }); - it('formats negative values with B/KB/MB/GB', function() { + it('formats negative values with B/KB/MB/GB', function () { expect(byteFormatter(-10)).toEqual('-10B'); expect(byteFormatter(-10 * 1024)).toEqual('-10KB'); expect(byteFormatter(-10.2 * 1024 * 1024)).toEqual('-10.2MB'); @@ -101,24 +101,24 @@ describe('Tick Formatters', function() { }); }); - describe('Bytes/s mode', function() { + describe('Bytes/s mode', function () { let bytesFormatter: any; - beforeEach(function() { + beforeEach(function () { bytesFormatter = formatters['bytes/s']; }); - it('is a function', function() { + it('is a function', function () { expect(bytesFormatter).toEqual(expect.any(Function)); }); - it('formats with B/KB/MB/GB', function() { + it('formats with B/KB/MB/GB', function () { expect(bytesFormatter(10)).toEqual('10B/s'); expect(bytesFormatter(10 * 1024)).toEqual('10KB/s'); expect(bytesFormatter(10.2 * 1024 * 1024)).toEqual('10.2MB/s'); expect(bytesFormatter(3 * 1024 * 1024 * 1024)).toEqual('3GB/s'); }); - it('formats negative values with B/KB/MB/GB', function() { + it('formats negative values with B/KB/MB/GB', function () { expect(bytesFormatter(-10)).toEqual('-10B/s'); expect(bytesFormatter(-10 * 1024)).toEqual('-10KB/s'); expect(bytesFormatter(-10.2 * 1024 * 1024)).toEqual('-10.2MB/s'); @@ -126,17 +126,17 @@ describe('Tick Formatters', function() { }); }); - describe('Currency mode', function() { + describe('Currency mode', function () { let currencyFormatter: any; - beforeEach(function() { + beforeEach(function () { currencyFormatter = formatters.currency; }); - it('is a function', function() { + it('is a function', function () { expect(currencyFormatter).toEqual(expect.any(Function)); }); - it('formats with $ by default', function() { + it('formats with $ by default', function () { const axis = { options: { units: {}, @@ -145,7 +145,7 @@ describe('Tick Formatters', function() { expect(currencyFormatter(10.2, axis)).toEqual('$10.20'); }); - it('accepts currency in ISO 4217', function() { + it('accepts currency in ISO 4217', function () { const axis = { options: { units: { @@ -158,17 +158,17 @@ describe('Tick Formatters', function() { }); }); - describe('Percent mode', function() { + describe('Percent mode', function () { let percentFormatter: any; - beforeEach(function() { + beforeEach(function () { percentFormatter = formatters.percent; }); - it('is a function', function() { + it('is a function', function () { expect(percentFormatter).toEqual(expect.any(Function)); }); - it('formats with %', function() { + it('formats with %', function () { const axis = { options: { units: {}, @@ -177,7 +177,7 @@ describe('Tick Formatters', function() { expect(percentFormatter(0.1234, axis)).toEqual('12%'); }); - it('formats with % with decimal precision', function() { + it('formats with % with decimal precision', function () { const tickDecimals = 3; const tickDecimalShift = 2; const axis = { @@ -192,17 +192,17 @@ describe('Tick Formatters', function() { }); }); - describe('Custom mode', function() { + describe('Custom mode', function () { let customFormatter: any; - beforeEach(function() { + beforeEach(function () { customFormatter = formatters.custom; }); - it('is a function', function() { + it('is a function', function () { expect(customFormatter).toEqual(expect.any(Function)); }); - it('accepts prefix and suffix', function() { + it('accepts prefix and suffix', function () { const axis = { options: { units: { @@ -216,7 +216,7 @@ describe('Tick Formatters', function() { expect(customFormatter(10.2, axis)).toEqual('prefix10.2suffix'); }); - it('correctly renders small values', function() { + it('correctly renders small values', function () { const axis = { options: { units: { diff --git a/src/plugins/vis_type_timelion/public/helpers/tick_generator.test.ts b/src/plugins/vis_type_timelion/public/helpers/tick_generator.test.ts index d1d959dee9501..3a0a2d395072f 100644 --- a/src/plugins/vis_type_timelion/public/helpers/tick_generator.test.ts +++ b/src/plugins/vis_type_timelion/public/helpers/tick_generator.test.ts @@ -19,20 +19,20 @@ import { generateTicksProvider } from './tick_generator'; -describe('Tick Generator', function() { +describe('Tick Generator', function () { let generateTicks: any; - beforeEach(function() { + beforeEach(function () { generateTicks = generateTicksProvider(); }); - describe('generateTicksProvider()', function() { - it('should return a function', function() { + describe('generateTicksProvider()', function () { + it('should return a function', function () { expect(generateTicks).toEqual(expect.any(Function)); }); }); - describe('generateTicks()', function() { + describe('generateTicks()', function () { const axes = [ { min: 0, @@ -51,8 +51,8 @@ describe('Tick Generator', function() { }, ]; - axes.forEach(axis => { - it(`generates ticks from ${axis.min} to ${axis.max}`, function() { + axes.forEach((axis) => { + it(`generates ticks from ${axis.min} to ${axis.max}`, function () { const ticks = generateTicks(axis); let n = 1; while (Math.pow(2, n) < axis.delta) n++; diff --git a/src/plugins/vis_type_timelion/public/helpers/timelion_request_handler.ts b/src/plugins/vis_type_timelion/public/helpers/timelion_request_handler.ts index 55edff98a748e..0cf6f3723a639 100644 --- a/src/plugins/vis_type_timelion/public/helpers/timelion_request_handler.ts +++ b/src/plugins/vis_type_timelion/public/helpers/timelion_request_handler.ts @@ -68,7 +68,7 @@ export function getTimelionRequestHandler({ }: TimelionVisDependencies) { const timezone = getTimezone(uiSettings); - return async function({ + return async function ({ timeRange, filters, query, diff --git a/src/plugins/vis_type_timelion/server/fit_functions/average.js b/src/plugins/vis_type_timelion/server/fit_functions/average.js index 10baeb8552a4e..06db7bd0e9324 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/average.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/average.js @@ -29,7 +29,7 @@ export default function average(dataTuples, targetTuples) { // they had when creating their own average const resultTimes = _.pluck(targetTuples, 0); const dataTuplesQueue = _.clone(dataTuples); - const resultValues = _.map(targetTuples, function(bucket) { + const resultValues = _.map(targetTuples, function (bucket) { const time = bucket[0]; let i = 0; const avgSet = []; @@ -53,7 +53,7 @@ export default function average(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 - const naNIndex = _.findIndex(resultValues, function(val) { + const naNIndex = _.findIndex(resultValues, function (val) { return isNaN(val); }); diff --git a/src/plugins/vis_type_timelion/server/fit_functions/average.test.js b/src/plugins/vis_type_timelion/server/fit_functions/average.test.js index 2f61a29bc25b2..595a5f79a2e13 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/average.test.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/average.test.js @@ -22,9 +22,9 @@ import moment from 'moment'; const expect = require('chai').expect; import _ from 'lodash'; -describe('average.js', function() { - describe('average', function() { - it('fills holes in the data', function() { +describe('average.js', function () { + describe('average', function () { + it('fills holes in the data', function () { const data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], @@ -42,8 +42,8 @@ describe('average.js', function() { expect(_.map(fn(data, target), 1)).to.eql([10, 20, 30, 40, 50]); }); - describe('sampling', function() { - it('up', function() { + describe('sampling', function () { + it('up', function () { const data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], @@ -61,7 +61,7 @@ describe('average.js', function() { expect(_.map(fn(data, target), 1)).to.eql([10, 20, 30, 50, 70]); }); - it('down', function() { + it('down', function () { const data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], diff --git a/src/plugins/vis_type_timelion/server/fit_functions/carry.js b/src/plugins/vis_type_timelion/server/fit_functions/carry.js index c08932bacb69e..155ed9ebeecbf 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/carry.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/carry.js @@ -37,7 +37,7 @@ export default function carry(dataTuples, targetTuples) { } let currentCarry = dataTuples[0][1]; - return _.map(targetTuples, function(bucket) { + return _.map(targetTuples, function (bucket) { const targetTime = bucket[0]; const dataTime = dataTuples[0][0]; diff --git a/src/plugins/vis_type_timelion/server/fit_functions/carry.test.js b/src/plugins/vis_type_timelion/server/fit_functions/carry.test.js index 22608e0bf4988..79575911d2022 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/carry.test.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/carry.test.js @@ -22,8 +22,8 @@ import moment from 'moment'; const expect = require('chai').expect; import _ from 'lodash'; -describe('carry.js', function() { - it('fills holes in the data', function() { +describe('carry.js', function () { + it('fills holes in the data', function () { const data = [ [moment.utc('1980', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 40], @@ -41,8 +41,8 @@ describe('carry.js', function() { expect(_.map(fn(data, target), 1)).to.eql([10, 10, 10, 40, 50]); }); - describe('sampling', function() { - it('up', function() { + describe('sampling', function () { + it('up', function () { const data = [ [moment.utc('1981', 'YYYY').valueOf(), 10], [moment.utc('1983', 'YYYY').valueOf(), 30], @@ -60,7 +60,7 @@ describe('carry.js', function() { expect(_.map(fn(data, target), 1)).to.eql([10, 10, 30, 30, 70]); }); - it('down does not make sense', function() { + it('down does not make sense', function () { const data = [ [moment.utc('1980', 'YYYY').valueOf(), 0], [moment.utc('1981', 'YYYY').valueOf(), 2], diff --git a/src/plugins/vis_type_timelion/server/fit_functions/nearest.js b/src/plugins/vis_type_timelion/server/fit_functions/nearest.js index f1907f9603de3..f15f529b5fde4 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/nearest.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/nearest.js @@ -23,7 +23,7 @@ import _ from 'lodash'; // Good: average, min, max // Bad: sum, count export default function nearest(dataTuples, targetTuples) { - return _.map(targetTuples, function(bucket) { + return _.map(targetTuples, function (bucket) { const time = bucket[0]; let i = 0; while ( diff --git a/src/plugins/vis_type_timelion/server/fit_functions/scale.js b/src/plugins/vis_type_timelion/server/fit_functions/scale.js index 3f5ece1d6e61a..3c80d8611b205 100644 --- a/src/plugins/vis_type_timelion/server/fit_functions/scale.js +++ b/src/plugins/vis_type_timelion/server/fit_functions/scale.js @@ -30,7 +30,7 @@ import _ from 'lodash'; function sum(set) { return _.reduce( set, - function(sum, num) { + function (sum, num) { return sum + num; }, 0 diff --git a/src/plugins/vis_type_timelion/server/handlers/chain_runner.js b/src/plugins/vis_type_timelion/server/handlers/chain_runner.js index 9a87909b0a857..59adea30730c7 100644 --- a/src/plugins/vis_type_timelion/server/handlers/chain_runner.js +++ b/src/plugins/vis_type_timelion/server/handlers/chain_runner.js @@ -97,7 +97,7 @@ export default function chainRunner(tlConfig) { args = _.map(args, resolveArgument); - return Bluebird.all(args).then(function(args) { + return Bluebird.all(args).then(function (args) { args.byName = indexArguments(functionDef, args); return functionDef.fn(args, tlConfig); }); @@ -119,23 +119,20 @@ export default function chainRunner(tlConfig) { promise = invoke(link.function, args); } - return promise.then(function(result) { + return promise.then(function (result) { return invokeChain({ type: 'chain', chain: chain }, [result]); }); } function resolveChainList(chainList) { - const seriesList = _.map(chainList, function(chain) { + const seriesList = _.map(chainList, function (chain) { const values = invoke('first', [chain]); - return values.then(function(args) { + return values.then(function (args) { return args; }); }); - return Bluebird.all(seriesList).then(function(args) { - const list = _.chain(args) - .pluck('list') - .flatten() - .value(); + return Bluebird.all(seriesList).then(function (args) { + const list = _.chain(args).pluck('list').flatten().value(); const seriesList = _.merge.apply(this, _.flatten([{}, args])); seriesList.list = list; return seriesList; @@ -144,9 +141,9 @@ export default function chainRunner(tlConfig) { function preProcessSheet(sheet) { let queries = {}; - _.each(sheet, function(chainList, i) { + _.each(sheet, function (chainList, i) { try { - const queriesInCell = _.mapValues(preprocessChain(chainList), function(val) { + const queriesInCell = _.mapValues(preprocessChain(chainList), function (val) { val.cell = i; return val; }); @@ -159,15 +156,15 @@ export default function chainRunner(tlConfig) { const promises = _.chain(queries) .values() - .map(function(query) { + .map(function (query) { return invoke(query.function, query.arguments); }) .value(); - return Bluebird.settle(promises).then(function(resolvedDatasources) { + return Bluebird.settle(promises).then(function (resolvedDatasources) { stats.queryTime = new Date().getTime(); - _.each(queries, function(query, i) { + _.each(queries, function (query, i) { const functionDef = tlConfig.getFunction(query.function); const resolvedDatasource = resolvedDatasources[i]; @@ -211,14 +208,14 @@ export default function chainRunner(tlConfig) { // This is setting the "global" sheet, required for resolving references sheet = parseSheet(request.sheet); - return preProcessSheet(sheet).then(function() { - return _.map(sheet, function(chainList, i) { + return preProcessSheet(sheet).then(function () { + return _.map(sheet, function (chainList, i) { return resolveChainList(chainList) - .then(function(seriesList) { + .then(function (seriesList) { stats.sheetTime = new Date().getTime(); return seriesList; }) - .catch(function(e) { + .catch(function (e) { throwWithCell(i, e); }); }); @@ -227,7 +224,7 @@ export default function chainRunner(tlConfig) { return { processRequest: processRequest, - getStats: function() { + getStats: function () { return stats; }, }; diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/arg_type.js b/src/plugins/vis_type_timelion/server/handlers/lib/arg_type.js index 59741827fdad2..69e105ebaac9f 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/arg_type.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/arg_type.js @@ -21,10 +21,7 @@ import _ from 'lodash'; export default function argType(arg) { if (Array.isArray(arg)) { - return _.chain(arg) - .map(argType) - .flattenDeep() - .value(); + return _.chain(arg).map(argType).flattenDeep().value(); } if (_.isObject(arg) && arg) { diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/index_arguments.js b/src/plugins/vis_type_timelion/server/handlers/lib/index_arguments.js index 20e46383baa3a..7ea8cd362c94b 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/index_arguments.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/index_arguments.js @@ -41,7 +41,7 @@ export default function indexArguments(functionDef, orderedArgs) { const indexedArgs = {}; // Check and index each known argument - _.each(functionDef.args, function(argDef, i) { + _.each(functionDef.args, function (argDef, i) { const value = orderedArgs[i]; validateArg(value, argDef.name, argDef); indexedArgs[argDef.name] = value; @@ -51,7 +51,7 @@ export default function indexArguments(functionDef, orderedArgs) { if (functionDef.extended) { const values = orderedArgs[orderedArgs.length - 1]; const names = orderedArgs[orderedArgs.length - 2]; - _.each(values, function(value, i) { + _.each(values, function (value, i) { validateArg(value, names[i], functionDef.extended); indexedArgs[names[i]] = value; }); diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.js b/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.js index 4880c73f42bb2..a210cf594f48b 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.js @@ -26,7 +26,7 @@ import PEG from 'pegjs'; const Parser = PEG.generate(grammar); export default function parseSheet(sheet) { - return _.map(sheet, function(plot) { + return _.map(sheet, function (plot) { try { return Parser.parse(plot).tree; } catch (e) { diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.test.js b/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.test.js index 16d5f8b4a02bb..a21b969d9fc5b 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.test.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/parse_sheet.test.js @@ -21,8 +21,8 @@ const parseSheet = require('./parse_sheet'); const expect = require('chai').expect; -describe('timelion parse_sheet function', function() { - it(`doesn't split expressions on whitespace`, async function() { +describe('timelion parse_sheet function', function () { + it(`doesn't split expressions on whitespace`, async function () { const data = ['.es() .es(404)']; const ast = parseSheet(data); @@ -31,7 +31,7 @@ describe('timelion parse_sheet function', function() { expect(expressions[0].type).to.equal('chain'); }); - it('splits expressions on commas', function() { + it('splits expressions on commas', function () { const data = ['.es(), .es(404)']; const ast = parseSheet(data); @@ -41,7 +41,7 @@ describe('timelion parse_sheet function', function() { expect(expressions[1].type).to.equal('chain'); }); - it('splits expressions on newlines', function() { + it('splits expressions on newlines', function () { const data = [`.es()\n\r ,\n\r .es(404)`]; const ast = parseSheet(data); diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/preprocess_chain.js b/src/plugins/vis_type_timelion/server/handlers/lib/preprocess_chain.js index 6a667e36054ce..78b71b8ced282 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/preprocess_chain.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/preprocess_chain.js @@ -41,7 +41,7 @@ export default function preProcessChainFn(tlConfig) { if (!Array.isArray(chain)) return; - _.each(chain, function(operator) { + _.each(chain, function (operator) { if (!_.isObject(operator)) { return; } diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/reposition_arguments.js b/src/plugins/vis_type_timelion/server/handlers/lib/reposition_arguments.js index 85a78564bf506..aa9992495b201 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/reposition_arguments.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/reposition_arguments.js @@ -24,7 +24,7 @@ import { i18n } from '@kbn/i18n'; export default function repositionArguments(functionDef, unorderedArgs) { const args = []; - _.each(unorderedArgs, function(unorderedArg, i) { + _.each(unorderedArgs, function (unorderedArg, i) { let argDef; let targetIndex; let value; @@ -45,7 +45,7 @@ export default function repositionArguments(functionDef, unorderedArgs) { storeAsArray = true; } } else { - targetIndex = _.findIndex(functionDef.args, function(orderedArg) { + targetIndex = _.findIndex(functionDef.args, function (orderedArg) { return unorderedArg.name === orderedArg.name; }); storeAsArray = argDef.multi; diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/tl_config.js b/src/plugins/vis_type_timelion/server/handlers/lib/tl_config.js index 28edafbc3be67..bb97e92ef0eed 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/tl_config.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/tl_config.js @@ -24,17 +24,17 @@ export default function tlConfigFn(setup) { let targetSeries; let tlConfig = { - getTargetSeries: function() { - return _.map(targetSeries, function(bucket) { + getTargetSeries: function () { + return _.map(targetSeries, function (bucket) { // eslint-disable-line no-use-before-define return [bucket, null]; }); }, - setTargetSeries: function() { + setTargetSeries: function () { targetSeries = buildTarget(this); }, - writeTargetSeries: function(series) { - targetSeries = _.map(series, function(p) { + writeTargetSeries: function (series) { + targetSeries = _.map(series, function (p) { return p[0]; }); }, diff --git a/src/plugins/vis_type_timelion/server/handlers/lib/validate_arg.js b/src/plugins/vis_type_timelion/server/handlers/lib/validate_arg.js index 1fb325bb6ee86..9b4fdddc2186e 100644 --- a/src/plugins/vis_type_timelion/server/handlers/lib/validate_arg.js +++ b/src/plugins/vis_type_timelion/server/handlers/lib/validate_arg.js @@ -26,7 +26,7 @@ export default function validateArgFn(functionDef) { const type = argType(value); const required = argDef.types; const multi = argDef.multi; - const isCorrectType = (function() { + 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/plugins/vis_type_timelion/server/lib/alter.js b/src/plugins/vis_type_timelion/server/lib/alter.js index c49d5f5f3ba25..46bf0a44aaf76 100644 --- a/src/plugins/vis_type_timelion/server/lib/alter.js +++ b/src/plugins/vis_type_timelion/server/lib/alter.js @@ -30,7 +30,7 @@ import _ from 'lodash'; export default function alter(args, fn) { // In theory none of the args should ever be promises. This is probably a waste. return Bluebird.all(args) - .then(function(args) { + .then(function (args) { const seriesList = args.shift(); if (seriesList.type !== 'seriesList') { @@ -38,7 +38,7 @@ export default function alter(args, fn) { } const list = _.chain(seriesList.list) - .map(function(series) { + .map(function (series) { return fn.apply(this, [series].concat(args)); }) .flatten() @@ -47,7 +47,7 @@ export default function alter(args, fn) { seriesList.list = list; return seriesList; }) - .catch(function(e) { + .catch(function (e) { throw e; }); } diff --git a/src/plugins/vis_type_timelion/server/lib/build_target.js b/src/plugins/vis_type_timelion/server/lib/build_target.js index 5ef11e79d9baa..639a7a1783b56 100644 --- a/src/plugins/vis_type_timelion/server/lib/build_target.js +++ b/src/plugins/vis_type_timelion/server/lib/build_target.js @@ -20,7 +20,7 @@ import moment from 'moment'; import splitInterval from './split_interval.js'; -export default function(tlConfig) { +export default function (tlConfig) { const min = moment(tlConfig.time.from); const max = moment(tlConfig.time.to); diff --git a/src/plugins/vis_type_timelion/server/lib/classes/datasource.js b/src/plugins/vis_type_timelion/server/lib/classes/datasource.js index e9d5fa8774b24..c694942ee8793 100644 --- a/src/plugins/vis_type_timelion/server/lib/classes/datasource.js +++ b/src/plugins/vis_type_timelion/server/lib/classes/datasource.js @@ -26,7 +26,7 @@ import _ from 'lodash'; function offsetSeries(response, offset) { if (offset) { - response = _.map(response, function(point) { + response = _.map(response, function (point) { return [offsetTime(point[0], offset, true), point[1]]; }); } @@ -62,7 +62,7 @@ export default class Datasource extends TimelionFunction { // Wrap the original function so we can modify inputs/outputs with offset & fit const originalFunction = config.fn; - config.fn = function(args, tlConfig) { + config.fn = function (args, tlConfig) { const config = _.clone(tlConfig); let offset = args.byName.offset; if (offset) { @@ -72,8 +72,8 @@ export default class Datasource extends TimelionFunction { config.time.to = offsetTime(config.time.to, offset); } - return Promise.resolve(originalFunction(args, config)).then(function(seriesList) { - seriesList.list = _.map(seriesList.list, function(series) { + return Promise.resolve(originalFunction(args, config)).then(function (seriesList) { + seriesList.list = _.map(seriesList.list, function (series) { if (series.data.length === 0) throw new Error(name + '() returned no results'); series.data = offsetSeries(series.data, offset); series.fit = args.byName.fit || series.fit || 'nearest'; @@ -89,7 +89,7 @@ export default class Datasource extends TimelionFunction { // otherwise teh series will end up being offset twice. this.timelionFn = originalFunction; this.datasource = true; - this.cacheKey = function(item) { + this.cacheKey = function (item) { return item.text; }; Object.freeze(this); diff --git a/src/plugins/vis_type_timelion/server/lib/classes/timelion_function.js b/src/plugins/vis_type_timelion/server/lib/classes/timelion_function.js index 2b6919dbcb350..83466e263cf2f 100644 --- a/src/plugins/vis_type_timelion/server/lib/classes/timelion_function.js +++ b/src/plugins/vis_type_timelion/server/lib/classes/timelion_function.js @@ -33,17 +33,17 @@ export default class TimelionFunction { // WTF is this? How could you not have a fn? Wtf would the thing be used for? const originalFunction = config.fn || - function(input) { + function (input) { return input; }; // Currently only re-fits the series. this.originalFn = originalFunction; - this.fn = function(args, tlConfig) { + this.fn = function (args, tlConfig) { const config = _.clone(tlConfig); - return Promise.resolve(originalFunction(args, config)).then(function(seriesList) { - seriesList.list = _.map(seriesList.list, function(series) { + return Promise.resolve(originalFunction(args, config)).then(function (seriesList) { + seriesList.list = _.map(seriesList.list, function (series) { const target = tlConfig.getTargetSeries(); // Don't fit if the series are already the same diff --git a/src/plugins/vis_type_timelion/server/lib/config_manager.ts b/src/plugins/vis_type_timelion/server/lib/config_manager.ts index 17471ca34f5ba..cc679b5155368 100644 --- a/src/plugins/vis_type_timelion/server/lib/config_manager.ts +++ b/src/plugins/vis_type_timelion/server/lib/config_manager.ts @@ -26,11 +26,11 @@ export class ConfigManager { private graphiteUrls: string[] = []; constructor(config: PluginInitializerContext['config']) { - config.create>().subscribe(configUpdate => { + config.create>().subscribe((configUpdate) => { this.graphiteUrls = configUpdate.graphiteUrls || []; }); - config.legacy.globalConfig$.subscribe(configUpdate => { + config.legacy.globalConfig$.subscribe((configUpdate) => { this.esShardTimeout = configUpdate.elasticsearch.shardTimeout.asMilliseconds(); }); } diff --git a/src/plugins/vis_type_timelion/server/lib/functions_md.js b/src/plugins/vis_type_timelion/server/lib/functions_md.js index 79302cef588d6..275e27e5081a9 100644 --- a/src/plugins/vis_type_timelion/server/lib/functions_md.js +++ b/src/plugins/vis_type_timelion/server/lib/functions_md.js @@ -21,8 +21,8 @@ import loadFunctions from './load_functions.js'; const functions = loadFunctions('series_functions/'); import _ from 'lodash'; -export default (function() { - const functionArray = _.map(functions, function(val, key) { +export default (function () { + 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 }); }); @@ -45,7 +45,7 @@ export default (function() { help += 'Argument | Accepts | Description\n'; help += '--- | --- | ---\n'; - _.each(args, function(arg) { + _.each(args, function (arg) { help += arg.name + ' | *' + _.without(arg.types, 'null').join('/') + '* | '; help += arg.help ? arg.help : '*no help available*'; help += ' \n'; @@ -69,11 +69,7 @@ export default (function() { "Data sources can start a chain, they don't need to be attached to anything, but they still need to start" + ' with a `.` (dot). Data retrieved from a data source can be passed into the chainable functions in the next section.\n\n'; - help += _.chain(functionArray) - .filter('datasource') - .map(toDocBlock) - .value() - .join(''); + help += _.chain(functionArray).filter('datasource').map(toDocBlock).value().join(''); help += '### Chainable functions\n'; help += @@ -81,11 +77,7 @@ export default (function() { ' functions modify the data output directly from a data source, or from another chainable function that has a data' + ' source somewhere before it.\n\n'; - help += _.chain(functionArray) - .filter('chainable') - .map(toDocBlock) - .value() - .join(''); + help += _.chain(functionArray).filter('chainable').map(toDocBlock).value().join(''); return help; } diff --git a/src/plugins/vis_type_timelion/server/lib/get_namespaced_settings.js b/src/plugins/vis_type_timelion/server/lib/get_namespaced_settings.js index 31bd6b440f9b8..51264decf8a31 100644 --- a/src/plugins/vis_type_timelion/server/lib/get_namespaced_settings.js +++ b/src/plugins/vis_type_timelion/server/lib/get_namespaced_settings.js @@ -20,12 +20,12 @@ import _ from 'lodash'; import configFile from '../timelion.json'; -export default function() { +export default function () { function flattenWith(dot, nestedObj, flattenArrays) { const stack = []; // track key stack const flatObj = {}; (function flattenObj(obj) { - _.keys(obj).forEach(function(key) { + _.keys(obj).forEach(function (key) { stack.push(key); if (!flattenArrays && Array.isArray(obj[key])) flatObj[stack.join(dot)] = obj[key]; else if (_.isObject(obj[key])) flattenObj(obj[key]); diff --git a/src/plugins/vis_type_timelion/server/lib/load_functions.js b/src/plugins/vis_type_timelion/server/lib/load_functions.js index b7cec8f68faf2..d6cb63b7c427b 100644 --- a/src/plugins/vis_type_timelion/server/lib/load_functions.js +++ b/src/plugins/vis_type_timelion/server/lib/load_functions.js @@ -22,7 +22,7 @@ import glob from 'glob'; import path from 'path'; import processFunctionDefinition from './process_function_definition'; -export default function(directory) { +export default function (directory) { function getTuple(directory, name) { return [name, require('../' + directory + '/' + name)]; // eslint-disable-line import/no-dynamic-require } @@ -31,8 +31,8 @@ export default function(directory) { const files = _.map( glob .sync(path.resolve(__dirname, '../' + directory + '/*.js')) - .filter(filename => !filename.includes('.test')), - function(file) { + .filter((filename) => !filename.includes('.test')), + function (file) { const name = file.substring(file.lastIndexOf('/') + 1, file.lastIndexOf('.')); return getTuple(directory, name); } @@ -40,7 +40,7 @@ export default function(directory) { // Get a list of all directories with an index.js, use the directory name as the key in the object const directories = _.chain(glob.sync(path.resolve(__dirname, '../' + directory + '/*/index.js'))) - .map(function(file) { + .map(function (file) { const parts = file.split('/'); const name = parts[parts.length - 2]; return getTuple(directory, name); @@ -49,7 +49,7 @@ export default function(directory) { const functions = _.zipObject(files.concat(directories)); - _.each(functions, function(func) { + _.each(functions, function (func) { _.assign(functions, processFunctionDefinition(func)); }); diff --git a/src/plugins/vis_type_timelion/server/lib/process_function_definition.js b/src/plugins/vis_type_timelion/server/lib/process_function_definition.js index e569b9b062218..3159d33c884e8 100644 --- a/src/plugins/vis_type_timelion/server/lib/process_function_definition.js +++ b/src/plugins/vis_type_timelion/server/lib/process_function_definition.js @@ -19,11 +19,11 @@ import _ from 'lodash'; -export default function(func) { +export default function (func) { const functions = {}; functions[func.name] = func; if (func.aliases) { - _.each(func.aliases, function(alias) { + _.each(func.aliases, function (alias) { const aliasFn = _.clone(func); aliasFn.isAlias = true; functions[alias] = aliasFn; diff --git a/src/plugins/vis_type_timelion/server/lib/reduce.js b/src/plugins/vis_type_timelion/server/lib/reduce.js index be36e0695bea6..cc13b75fde12d 100644 --- a/src/plugins/vis_type_timelion/server/lib/reduce.js +++ b/src/plugins/vis_type_timelion/server/lib/reduce.js @@ -45,10 +45,10 @@ async function pairwiseReduce(left, right, fn) { const indexedList = _.indexBy(right.list, pairwiseField); // ensure seriesLists contain same pairwise labels - left.list.forEach(leftSeries => { + left.list.forEach((leftSeries) => { if (!indexedList[leftSeries[pairwiseField]]) { const rightSeriesLabels = right.list - .map(rightSeries => { + .map((rightSeries) => { return `"${rightSeries[pairwiseField]}"`; }) .join(','); @@ -60,7 +60,7 @@ async function pairwiseReduce(left, right, fn) { // pairwise reduce seriesLists const pairwiseSeriesList = { type: 'seriesList', list: [] }; - left.list.forEach(async leftSeries => { + left.list.forEach(async (leftSeries) => { const first = { type: 'seriesList', list: [leftSeries] }; const second = { type: 'seriesList', list: [indexedList[leftSeries[pairwiseField]]] }; const reducedSeriesList = await reduce([first, second], fn); @@ -100,8 +100,8 @@ async function reduce(argsPromises, fn) { } function reduceSeries(series) { - return _.reduce(series, function(destinationObject, argument, i, p) { - let output = _.map(destinationObject.data, function(point, index) { + return _.reduce(series, function (destinationObject, argument, i, p) { + let output = _.map(destinationObject.data, function (point, index) { const value = point[1]; if (value == null) { @@ -131,7 +131,7 @@ async function reduce(argsPromises, fn) { let reduced; if (argument != null) { - reduced = _.map(seriesList.list, function(series) { + reduced = _.map(seriesList.list, function (series) { return reduceSeries([series].concat(argument)); }); } else { diff --git a/src/plugins/vis_type_timelion/server/lib/unzip_pairs.js b/src/plugins/vis_type_timelion/server/lib/unzip_pairs.js index 071e3873ccb30..7a34b5ec98ff0 100644 --- a/src/plugins/vis_type_timelion/server/lib/unzip_pairs.js +++ b/src/plugins/vis_type_timelion/server/lib/unzip_pairs.js @@ -22,10 +22,10 @@ import _ from 'lodash'; export default function unzipPairs(timeValObject) { const paired = _.chain(timeValObject) .pairs() - .map(function(point) { + .map(function (point) { return [parseInt(point[0], 10), point[1]]; }) - .sortBy(function(point) { + .sortBy(function (point) { return point[0]; }) .value(); diff --git a/src/plugins/vis_type_timelion/server/routes/functions.ts b/src/plugins/vis_type_timelion/server/routes/functions.ts index a908fefa377eb..85723824d2141 100644 --- a/src/plugins/vis_type_timelion/server/routes/functions.ts +++ b/src/plugins/vis_type_timelion/server/routes/functions.ts @@ -28,7 +28,7 @@ export function functionsRoute(router: IRouter, { functions }: { functions: Load validate: false, }, async (context, request, response) => { - const 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 }); }); diff --git a/src/plugins/vis_type_timelion/server/routes/validate_es.ts b/src/plugins/vis_type_timelion/server/routes/validate_es.ts index 70d53b6b2c5e3..511a5852e4641 100644 --- a/src/plugins/vis_type_timelion/server/routes/validate_es.ts +++ b/src/plugins/vis_type_timelion/server/routes/validate_es.ts @@ -26,7 +26,7 @@ export function validateEsRoute(router: IRouter) { path: '/api/timelion/validate/es', validate: false, }, - async function(context, request, response) { + async function (context, request, response) { const uiSettings = await context.core.uiSettings.client.getAll(); const { callAsCurrentUser } = context.core.elasticsearch.dataClient; diff --git a/src/plugins/vis_type_timelion/server/series_functions/abs.js b/src/plugins/vis_type_timelion/server/series_functions/abs.js index c072522ebd906..d55da3b7ec0e0 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/abs.js +++ b/src/plugins/vis_type_timelion/server/series_functions/abs.js @@ -33,8 +33,8 @@ export default new Chainable('abs', { defaultMessage: 'Return the absolute value of each value in the series list', }), fn: function absFn(args) { - return alter(args, function(eachSeries) { - const data = _.map(eachSeries.data, function(point) { + return alter(args, function (eachSeries) { + const data = _.map(eachSeries.data, function (point) { return [point[0], Math.abs(point[1])]; }); eachSeries.data = data; diff --git a/src/plugins/vis_type_timelion/server/series_functions/abs.test.js b/src/plugins/vis_type_timelion/server/series_functions/abs.test.js index 385fad7db739c..2e01370ddfb99 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/abs.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/abs.test.js @@ -24,14 +24,14 @@ const expect = require('chai').expect; const seriesList = require('./fixtures/series_list.js')(); import invoke from './helpers/invoke_series_fn.js'; -describe('abs.js', function() { - it('should return the positive value of every value', function() { - return invoke(fn, [seriesList]).then(function(result) { - const before = _.filter(result.input[0].list[0].data, function(point) { +describe('abs.js', function () { + it('should return the positive value of every value', function () { + return invoke(fn, [seriesList]).then(function (result) { + const before = _.filter(result.input[0].list[0].data, function (point) { return point[1] < 0; }); - const 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/plugins/vis_type_timelion/server/series_functions/aggregate/aggregate.test.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/aggregate.test.js index d2708a525b9c6..8686c6b6542db 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/aggregate.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/aggregate.test.js @@ -30,43 +30,43 @@ describe('aggregate', () => { }); it('first', () => { - return invoke(fn, [seriesList, 'first']).then(r => { + return invoke(fn, [seriesList, 'first']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([100, 100, 100, 100]); }); }); it('last', () => { - return invoke(fn, [seriesList, 'last']).then(r => { + return invoke(fn, [seriesList, 'last']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([20, 20, 20, 20]); }); }); it('min', () => { - return invoke(fn, [seriesList, 'min']).then(r => { + return invoke(fn, [seriesList, 'min']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([20, 20, 20, 20]); }); }); it('max', () => { - return invoke(fn, [seriesList, 'max']).then(r => { + return invoke(fn, [seriesList, 'max']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([100, 100, 100, 100]); }); }); it('sum', () => { - return invoke(fn, [seriesList, 'sum']).then(r => { + return invoke(fn, [seriesList, 'sum']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([220, 220, 220, 220]); }); }); it('cardinality', () => { - return invoke(fn, [seriesList, 'cardinality']).then(r => { + return invoke(fn, [seriesList, 'cardinality']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([3, 3, 3, 3]); }); }); it('avg', () => { - return invoke(fn, [seriesList, 'avg']).then(r => { + return invoke(fn, [seriesList, 'avg']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([55, 55, 55, 55]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/avg.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/avg.js index 26e768a76f84e..853ce337efac2 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/avg.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/avg.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.sum(points) / points.length; } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/cardinality.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/cardinality.js index 938039a465c31..807e620ee941b 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/cardinality.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/cardinality.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.uniq(points).length; } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/first.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/first.js index 8eb9565d2711c..05e560b84335f 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/first.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/first.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.first(points); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/index.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/index.js index 81ed1dff15967..2340456e589ad 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/index.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/index.js @@ -61,7 +61,7 @@ export default new Chainable('aggregate', { if (!fn) throw new Error('.aggregate() function must be one of: ' + _.keys(functions).join(', ')); - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { const times = _.map(eachSeries.data, 0); const values = _.map(eachSeries.data, 1); diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/last.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/last.js index 751f6e87fff99..8f252fb451027 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/last.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/last.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.last(points); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/max.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/max.js index 7cac21932001f..5b2610f07bbea 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/max.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/max.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.max(points); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/min.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/min.js index 6ff6812dde527..1ebf9be2f9146 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/min.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/min.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.min(points); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/aggregate/sum.js b/src/plugins/vis_type_timelion/server/series_functions/aggregate/sum.js index 481f6f529fa66..34b5fe277dd34 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/aggregate/sum.js +++ b/src/plugins/vis_type_timelion/server/series_functions/aggregate/sum.js @@ -19,6 +19,6 @@ import _ from 'lodash'; -export default function(points) { +export default function (points) { return _.sum(points); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/bars.js b/src/plugins/vis_type_timelion/server/series_functions/bars.js index 4fe08caed0986..796b36ec0a303 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/bars.js +++ b/src/plugins/vis_type_timelion/server/series_functions/bars.js @@ -46,7 +46,7 @@ export default new Chainable('bars', { defaultMessage: 'Show the seriesList as bars', }), fn: function barsFn(args) { - return alter(args, function(eachSeries, width, stack) { + return alter(args, function (eachSeries, width, stack) { eachSeries.bars = eachSeries.bars || {}; eachSeries.bars.show = width == null ? 1 : width; eachSeries.bars.lineWidth = width == null ? 6 : width; diff --git a/src/plugins/vis_type_timelion/server/series_functions/bars.test.js b/src/plugins/vis_type_timelion/server/series_functions/bars.test.js index 74105330e6053..936c68b64d580 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/bars.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/bars.test.js @@ -30,17 +30,17 @@ describe('bars.js', () => { }); it('creates the bars property, with defaults, on all series', () => { - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { 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)); + _.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)); }); }); it('leaves existing bars alone when called without option, if they exist', () => { seriesList.list[0].bars = { foo: true }; - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { const bars = _.map(r.output.list, 'bars'); expect(bars[0].foo).to.equal(true); expect(bars[1].foo).to.equal(undefined); @@ -48,7 +48,7 @@ describe('bars.js', () => { }); it('sets lineWidth and show to the same value', () => { - return invoke(fn, [seriesList, 0]).then(r => { + return invoke(fn, [seriesList, 0]).then((r) => { 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/plugins/vis_type_timelion/server/series_functions/color.js b/src/plugins/vis_type_timelion/server/series_functions/color.js index 85a622ceb7d07..245a647f02899 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/color.js +++ b/src/plugins/vis_type_timelion/server/series_functions/color.js @@ -55,7 +55,7 @@ colors, and have multiple series, you will get a gradient, e.g., "#00B1CC:#00FF9 } let i = 0; - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { if (gradient) { eachSeries.color = gradient[i++].toHexString(); } else if (colors.length === 1 || gradientStops === 1) { diff --git a/src/plugins/vis_type_timelion/server/series_functions/color.test.js b/src/plugins/vis_type_timelion/server/series_functions/color.test.js index 2dc8c6fbcb896..b0eb11219ed01 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/color.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/color.test.js @@ -30,9 +30,9 @@ describe('color.js', () => { }); it('sets the color, on all series', () => { - return invoke(fn, [seriesList, '#eee']).then(r => { + return invoke(fn, [seriesList, '#eee']).then((r) => { const colors = _.map(r.output.list, 'color'); - _.each(colors, color => expect(color).to.equal('#eee')); + _.each(colors, (color) => expect(color).to.equal('#eee')); }); }); @@ -42,7 +42,7 @@ describe('color.js', () => { type: 'seriesList', list: seriesList.list.slice(0, 4), }; - return invoke(fn, [fourLongList, '#000:#333']).then(r => { + return invoke(fn, [fourLongList, '#000:#333']).then((r) => { const colors = _.map(r.output.list, 'color'); _.each(colors, (color, i) => expect(color).to.equal(expected[i])); }); @@ -71,7 +71,7 @@ describe('color.js', () => { }); it('throws if you do not pass a color', () => { - invoke(fn, [seriesList, '']).catch(e => { + invoke(fn, [seriesList, '']).catch((e) => { expect(e).to.be.an(Error); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/condition.js b/src/plugins/vis_type_timelion/server/series_functions/condition.js index 625b25762d04f..789b3c60e4a9c 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/condition.js +++ b/src/plugins/vis_type_timelion/server/series_functions/condition.js @@ -127,8 +127,8 @@ export default new Chainable('condition', { aliases: ['if'], fn: function conditionFn(args) { const config = args.byName; - return alter(args, function(eachSeries) { - const data = _.map(eachSeries.data, function(point, i) { + return alter(args, function (eachSeries) { + const data = _.map(eachSeries.data, function (point, i) { function getNumber(source) { if (argType(source) === 'number') return source; if (argType(source) === 'null') return null; @@ -144,7 +144,7 @@ export default new Chainable('condition', { const thenVal = getNumber(config.then); const elseVal = _.isUndefined(config.else) ? point[1] : getNumber(config.else); - const newValue = (function() { + const newValue = (function () { switch (config.operator) { case 'lt': return point[1] < ifVal ? thenVal : elseVal; diff --git a/src/plugins/vis_type_timelion/server/series_functions/condition.test.js b/src/plugins/vis_type_timelion/server/series_functions/condition.test.js index 469f84344eb4f..7730bcc1acca3 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/condition.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/condition.test.js @@ -24,10 +24,10 @@ import invoke from './helpers/invoke_series_fn.js'; import getSeriesList from './helpers/get_single_series_list'; import _ from 'lodash'; -describe('condition.js', function() { +describe('condition.js', function () { let comparable; let seriesList; - beforeEach(function() { + beforeEach(function () { seriesList = require('./fixtures/series_list.js')(); comparable = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 12], @@ -37,71 +37,71 @@ describe('condition.js', function() { ]); }); - describe('a single number with', function() { - it('eq', function() { - return invoke(fn, [seriesList, 'eq', 17, 0]).then(function(r) { + describe('a single number with', function () { + it('eq', function () { + return invoke(fn, [seriesList, 'eq', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([-51, 0, 82, 20]); }); }); - it('ne', function() { - return invoke(fn, [seriesList, 'ne', 17, 0]).then(function(r) { + it('ne', function () { + return invoke(fn, [seriesList, 'ne', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 17, 0, 0]); }); }); - it('gte', function() { - return invoke(fn, [seriesList, 'gte', 17, 0]).then(function(r) { + it('gte', function () { + return invoke(fn, [seriesList, 'gte', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([-51, 0, 0, 0]); }); }); - it('gt', function() { - return invoke(fn, [seriesList, 'gt', 17, 0]).then(function(r) { + it('gt', function () { + return invoke(fn, [seriesList, 'gt', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([-51, 17, 0, 0]); }); }); - it('lt', function() { - return invoke(fn, [seriesList, 'lt', 17, 0]).then(function(r) { + it('lt', function () { + return invoke(fn, [seriesList, 'lt', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 17, 82, 20]); }); }); - it('lte', function() { - return invoke(fn, [seriesList, 'lte', 17, 0]).then(function(r) { + it('lte', function () { + return invoke(fn, [seriesList, 'lte', 17, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 0, 82, 20]); }); }); }); - it('can compare against another series', function() { - return invoke(fn, [seriesList, 'ne', comparable, 0]).then(function(r) { + it('can compare against another series', function () { + return invoke(fn, [seriesList, 'ne', comparable, 0]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 0, 82, 0]); }); }); - it('can set the resultant value to that of another series', function() { - return invoke(fn, [seriesList, 'lt', comparable, comparable]).then(function(r) { + it('can set the resultant value to that of another series', function () { + return invoke(fn, [seriesList, 'lt', comparable, comparable]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([12, 33, 82, 20]); }); }); - it('can set the resultant value to null', function() { - return invoke(fn, [seriesList, 'lt', 17, null]).then(function(r) { + it('can set the resultant value to null', function () { + return invoke(fn, [seriesList, 'lt', 17, null]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([null, 17, 82, 20]); }); }); - describe('else', function() { - it('has else', function() { - return invoke(fn, [seriesList, 'lt', 30, 0, 1]).then(function(r) { + describe('else', function () { + it('has else', function () { + return invoke(fn, [seriesList, 'lt', 30, 0, 1]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 0, 1, 0]); }); }); - it('works with other series', function() { - return invoke(fn, [seriesList, 'lt', 30, 0, comparable]).then(function(r) { + it('works with other series', function () { + return invoke(fn, [seriesList, 'lt', 30, 0, comparable]).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([0, 0, 82, 0]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/cusum.js b/src/plugins/vis_type_timelion/server/series_functions/cusum.js index cf4dd21b98261..decbd22b4345c 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/cusum.js +++ b/src/plugins/vis_type_timelion/server/series_functions/cusum.js @@ -41,10 +41,10 @@ export default new Chainable('cusum', { defaultMessage: 'Return the cumulative sum of a series, starting at a base.', }), fn: function cusumFn(args) { - return alter(args, function(eachSeries, base) { + return alter(args, function (eachSeries, base) { const pairs = eachSeries.data; let total = base || 0; - eachSeries.data = _.map(pairs, function(point) { + eachSeries.data = _.map(pairs, function (point) { total += point[1]; return [point[0], total]; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/cusum.test.js b/src/plugins/vis_type_timelion/server/series_functions/cusum.test.js index 29927a8d0faf2..91d01e10c5826 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/cusum.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/cusum.test.js @@ -30,7 +30,7 @@ describe('cusum.js', () => { }); it('progressively adds the numbers in the list', () => { - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([100, 150, 200, 220]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/derivative.js b/src/plugins/vis_type_timelion/server/series_functions/derivative.js index bde4fe9f29abc..a034585597d63 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/derivative.js +++ b/src/plugins/vis_type_timelion/server/series_functions/derivative.js @@ -33,9 +33,9 @@ export default new Chainable('derivative', { defaultMessage: 'Plot the change in values over time.', }), fn: function derivativeFn(args) { - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { const pairs = eachSeries.data; - eachSeries.data = _.map(pairs, function(point, i) { + eachSeries.data = _.map(pairs, function (point, i) { if (i === 0 || pairs[i - 1][1] == null || point[1] == null) { return [point[0], null]; } diff --git a/src/plugins/vis_type_timelion/server/series_functions/derivative.test.js b/src/plugins/vis_type_timelion/server/series_functions/derivative.test.js index 296cf91711d02..2da72ecf9f4e0 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/derivative.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/derivative.test.js @@ -30,7 +30,7 @@ describe('derivative.js', () => { }); it('gets the change in the set', () => { - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([null, -50, 0, -30]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/divide.js b/src/plugins/vis_type_timelion/server/series_functions/divide.js index 5d7eab23197ef..45ead08d9ed36 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/divide.js +++ b/src/plugins/vis_type_timelion/server/series_functions/divide.js @@ -41,7 +41,7 @@ export default new Chainable('divide', { 'Divides the values of one or more series in a seriesList to each position, in each series, of the input seriesList', }), fn: function divideFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return a / b; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/divide.test.js b/src/plugins/vis_type_timelion/server/series_functions/divide.test.js index e24ec7d60541c..ceb435f6c9898 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/divide.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/divide.test.js @@ -30,7 +30,7 @@ describe('divide.js', () => { }); it('divides by a single number', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([50, 25, 25, 10]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/es.test.js b/src/plugins/vis_type_timelion/server/series_functions/es/es.test.js index 56d4b6812d3d9..1bc979399b1b1 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/es.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/es.test.js @@ -34,12 +34,12 @@ import invoke from '../helpers/invoke_series_fn.js'; function stubRequestAndServer(response, indexPatternSavedObjects = []) { return { esDataClient: sinon.stub().returns({ - callAsCurrentUser: function() { + callAsCurrentUser: function () { return Bluebird.resolve(response); }, }), savedObjectsClient: { - find: function() { + find: function () { return Bluebird.resolve({ saved_objects: indexPatternSavedObjects, }); @@ -58,14 +58,14 @@ describe('es', () => { }); return invoke(es, [5], tlConfig) .then(expect.fail) - .catch(e => { + .catch((e) => { expect(e).to.be.an('error'); }); }); it('returns a seriesList', () => { tlConfig = stubRequestAndServer(esResponse); - return invoke(es, [5], tlConfig).then(r => { + return invoke(es, [5], tlConfig).then((r) => { expect(r.output.type).to.eql('seriesList'); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/index.js b/src/plugins/vis_type_timelion/server/series_functions/es/index.js index eb41663b71cf7..fd392f599c1d2 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/index.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/index.js @@ -114,13 +114,13 @@ export default new Datasource('es', { search: `"${config.index}"`, search_fields: ['title'], }); - const indexPatternSavedObject = findResp.saved_objects.find(savedObject => { + const indexPatternSavedObject = findResp.saved_objects.find((savedObject) => { return savedObject.attributes.title === config.index; }); let scriptedFields = []; if (indexPatternSavedObject) { const fields = JSON.parse(indexPatternSavedObject.attributes.fields); - scriptedFields = fields.filter(field => { + scriptedFields = fields.filter((field) => { return field.scripted; }); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_body.js b/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_body.js index c9ffe07793803..c24e4cf08b93d 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_body.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_body.js @@ -18,7 +18,7 @@ */ export function buildAggBody(fieldName, scriptedFields) { - const scriptedField = scriptedFields.find(field => { + const scriptedField = scriptedFields.find((field) => { return field.name === fieldName; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_response_to_series_list.js b/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_response_to_series_list.js index a5876944db250..409372da24724 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_response_to_series_list.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/lib/agg_response_to_series_list.js @@ -22,11 +22,11 @@ import _ from 'lodash'; export function timeBucketsToPairs(buckets) { const timestamps = _.pluck(buckets, 'key'); const series = {}; - _.each(buckets, function(bucket) { - _.forOwn(bucket, function(val, key) { + _.each(buckets, function (bucket) { + _.forOwn(bucket, function (val, key) { if (_.isPlainObject(val)) { if (val.values) { - _.forOwn(val.values, function(bucketValue, bucketKey) { + _.forOwn(val.values, function (bucketValue, bucketKey) { const k = key + ':' + bucketKey; const v = isNaN(bucketValue) ? NaN : bucketValue; series[k] = series[k] || []; @@ -40,7 +40,7 @@ export function timeBucketsToPairs(buckets) { }); }); - return _.mapValues(series, function(values) { + return _.mapValues(series, function (values) { return _.zip(timestamps, values); }); } @@ -48,16 +48,16 @@ export function timeBucketsToPairs(buckets) { export function flattenBucket(bucket, splitKey, path, result) { result = result || {}; path = path || []; - _.forOwn(bucket, function(val, key) { + _.forOwn(bucket, function (val, key) { if (!_.isPlainObject(val)) return; if (_.get(val, 'meta.type') === 'split') { - _.each(val.buckets, function(bucket, bucketKey) { + _.each(val.buckets, function (bucket, bucketKey) { if (bucket.key == null) bucket.key = bucketKey; // For handling "keyed" response formats, e.g., filters agg flattenBucket(bucket, bucket.key, path.concat([key + ':' + bucket.key]), result); }); } else if (_.get(val, 'meta.type') === 'time_buckets') { const metrics = timeBucketsToPairs(val.buckets); - _.each(metrics, function(pairs, metricName) { + _.each(metrics, function (pairs, metricName) { result[path.concat([metricName]).join(' > ')] = { data: pairs, splitKey: splitKey, @@ -69,7 +69,7 @@ export function flattenBucket(bucket, splitKey, path, result) { } export default function toSeriesList(aggs, config) { - return _.map(flattenBucket(aggs), function(metrics, name) { + return _.map(flattenBucket(aggs), function (metrics, name) { return { data: metrics.data, type: 'series', diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/lib/build_request.js b/src/plugins/vis_type_timelion/server/series_functions/es/lib/build_request.js index 38618ccf66d6f..65b28fb833279 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/lib/build_request.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/lib/build_request.js @@ -46,7 +46,7 @@ export default function buildRequest(config, tlConfig, scriptedFields, timeout) meta: { type: 'split' }, filters: { filters: _.chain(config.q) - .map(function(q) { + .map(function (q) { return [q, { query_string: { query: q } }]; }) .zipObject() @@ -58,7 +58,7 @@ export default function buildRequest(config, tlConfig, scriptedFields, timeout) let aggCursor = aggs.q.aggs; - _.each(config.split, function(clause) { + _.each(config.split, function (clause) { clause = clause.split(':'); if (clause[0] && clause[1]) { const termsAgg = buildAggBody(clause[0], scriptedFields); diff --git a/src/plugins/vis_type_timelion/server/series_functions/es/lib/create_date_agg.js b/src/plugins/vis_type_timelion/server/series_functions/es/lib/create_date_agg.js index b8bf83116b43b..904fe69cbc57c 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/es/lib/create_date_agg.js +++ b/src/plugins/vis_type_timelion/server/series_functions/es/lib/create_date_agg.js @@ -38,7 +38,7 @@ export default function createDateAgg(config, tlConfig, scriptedFields) { }; dateAgg.time_buckets.aggs = {}; - _.each(config.metric, function(metric) { + _.each(config.metric, function (metric) { metric = metric.split(':'); if (metric[0] === 'count') { // This is pretty lame, but its how the "doc_count" metric has to be implemented at the moment @@ -55,7 +55,7 @@ export default function createDateAgg(config, tlConfig, scriptedFields) { dateAgg.time_buckets.aggs[metricName][metric[0]] = buildAggBody(metric[1], scriptedFields); if (metric[0] === 'percentiles' && metric[2]) { let percentList = metric[2].split(','); - percentList = percentList.map(x => parseFloat(x)); + percentList = percentList.map((x) => parseFloat(x)); dateAgg.time_buckets.aggs[metricName][metric[0]].percents = percentList; } } else { diff --git a/src/plugins/vis_type_timelion/server/series_functions/first.js b/src/plugins/vis_type_timelion/server/series_functions/first.js index 06b8c1e81b4c4..3b7feaeb08eba 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/first.js +++ b/src/plugins/vis_type_timelion/server/series_functions/first.js @@ -32,7 +32,7 @@ export default new Chainable('first', { defaultMessage: `This is an internal function that simply returns the input seriesList. Don't use this`, }), fn: function firstFn(args) { - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { return eachSeries; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/first.test.js b/src/plugins/vis_type_timelion/server/series_functions/first.test.js index 96192b2b3903f..625a6930badb9 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/first.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/first.test.js @@ -23,9 +23,9 @@ const expect = require('chai').expect; const seriesList = require('./fixtures/series_list.js')(); import invoke from './helpers/invoke_series_fn.js'; -describe('first.js', function() { - it('should return exactly the data input', function() { - return invoke(fn, [seriesList]).then(function(result) { +describe('first.js', function () { + it('should return exactly the data input', function () { + return invoke(fn, [seriesList]).then(function (result) { expect(result.input[0]).to.eql(result.output); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/fit.js b/src/plugins/vis_type_timelion/server/series_functions/fit.js index c47f8dc84908c..b472c23b9c79f 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/fit.js +++ b/src/plugins/vis_type_timelion/server/series_functions/fit.js @@ -40,7 +40,7 @@ export default new Chainable('fit', { fitFunctions: _.keys(fitFunctions).join(', '), }, }), - suggestions: _.keys(fitFunctions).map(key => { + suggestions: _.keys(fitFunctions).map((key) => { return { name: key }; }), }, @@ -49,8 +49,8 @@ export default new Chainable('fit', { defaultMessage: 'Fills null values using a defined fit function', }), fn: function absFn(args) { - return alter(args, function(eachSeries, mode) { - const noNulls = eachSeries.data.filter(item => item[1] === 0 || item[1]); + return alter(args, function (eachSeries, mode) { + const noNulls = eachSeries.data.filter((item) => item[1] === 0 || item[1]); if (noNulls.length === 0) { return eachSeries; diff --git a/src/plugins/vis_type_timelion/server/series_functions/fit.test.js b/src/plugins/vis_type_timelion/server/series_functions/fit.test.js index 6622259a1fd87..c352f3ba60b87 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/fit.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/fit.test.js @@ -24,9 +24,9 @@ import invoke from './helpers/invoke_series_fn.js'; import getSeriesList from './helpers/get_single_series_list'; import _ from 'lodash'; -describe('fit.js', function() { - describe('should not filter out zeros', function() { - it('all zeros', function() { +describe('fit.js', function () { + describe('should not filter out zeros', function () { + it('all zeros', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 0], [moment.utc('1981-01-01T00:00:00.000Z'), null], @@ -34,14 +34,14 @@ describe('fit.js', function() { [moment.utc('1983-01-01T00:00:00.000Z'), 0], ]); - return invoke(fn, [seriesList, 'carry']).then(function(r) { + return invoke(fn, [seriesList, 'carry']).then(function (r) { expect(r.input[0].list[0].data[1][1]).to.equal(null); expect(_.map(r.output.list[0].data, 1)).to.eql([0, 0, 0, 0]); expect(r.output.list[0].data[1][0]).to.not.equal(r.output.list[0].data[0][0]); }); }); - it('mixed zeros and numbers', function() { + it('mixed zeros and numbers', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 26], [moment.utc('1981-01-01T00:00:00.000Z'), 42], @@ -50,13 +50,13 @@ describe('fit.js', function() { [moment.utc('1984-01-01T00:00:00.000Z'), 1], ]); - return invoke(fn, [seriesList, 'carry']).then(function(r) { + return invoke(fn, [seriesList, 'carry']).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([26, 42, 0, 0, 1]); }); }); }); - it('should return original series when all values are null', function() { + it('should return original series when all values are null', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), null], [moment.utc('1981-01-01T00:00:00.000Z'), null], @@ -64,13 +64,13 @@ describe('fit.js', function() { [moment.utc('1983-01-01T00:00:00.000Z'), null], ]); - return invoke(fn, [seriesList, 'carry']).then(function(r) { + return invoke(fn, [seriesList, 'carry']).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([null, null, null, null]); }); }); - describe('carry', function() { - it('should maintain the previous value until it changes', function() { + describe('carry', function () { + it('should maintain the previous value until it changes', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], @@ -78,7 +78,7 @@ describe('fit.js', function() { [moment.utc('1983-01-01T00:00:00.000Z'), 171], ]); - return invoke(fn, [seriesList, 'carry']).then(function(r) { + return invoke(fn, [seriesList, 'carry']).then(function (r) { expect(r.input[0].list[0].data[1][1]).to.equal(null); expect(_.map(r.output.list[0].data, 1)).to.eql([5, 5, 3.4, 171]); expect(r.output.list[0].data[1][0]).to.not.equal(r.output.list[0].data[0][0]); @@ -86,8 +86,8 @@ describe('fit.js', function() { }); }); - describe('nearest', function() { - it('should use the closest temporal value to fill the null', function() { + describe('nearest', function () { + it('should use the closest temporal value to fill the null', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 5], [moment.utc('1981-01-01T00:00:00.000Z'), null], @@ -95,7 +95,7 @@ describe('fit.js', function() { [moment.utc('1983-01-01T00:00:00.000Z'), 171], ]); - return invoke(fn, [seriesList, 'nearest']).then(function(r) { + return invoke(fn, [seriesList, 'nearest']).then(function (r) { expect(r.input[0].list[0].data[1][1]).to.equal(null); expect(_.map(r.output.list[0].data, 1)).to.eql([5, 3.4, 3.4, 171]); expect(r.output.list[0].data[1][0]).to.not.equal(r.output.list[0].data[0][0]); @@ -103,8 +103,8 @@ describe('fit.js', function() { }); }); - describe('average', function() { - it('should produce a smooth, straight line between points', function() { + describe('average', function () { + it('should produce a smooth, straight line between points', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], @@ -113,15 +113,15 @@ describe('fit.js', function() { [moment.utc('1984-01-01T00:00:00.000Z'), 50], ]); - return invoke(fn, [seriesList, 'average']).then(function(r) { + return invoke(fn, [seriesList, 'average']).then(function (r) { expect(r.input[0].list[0].data[1][1]).to.eql(null); expect(_.map(r.output.list[0].data, 1)).to.eql([10, 20, 30, 40, 50]); }); }); }); - describe('scale', function() { - it('should distribute the next points value across the preceeding nulls', function() { + describe('scale', function () { + it('should distribute the next points value across the preceeding nulls', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], @@ -130,14 +130,14 @@ describe('fit.js', function() { [moment.utc('1984-01-01T00:00:00.000Z'), 50], ]); - return invoke(fn, [seriesList, 'scale']).then(function(r) { + return invoke(fn, [seriesList, 'scale']).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([10, 20, 20, 20, 50]); }); }); }); - describe('none', function() { - it('basically just drops the nulls. This is going to screw you', function() { + describe('none', function () { + it('basically just drops the nulls. This is going to screw you', function () { const seriesList = getSeriesList('', [ [moment.utc('1980-01-01T00:00:00.000Z'), 10], [moment.utc('1981-07-01T00:00:00.000Z'), null], @@ -146,7 +146,7 @@ describe('fit.js', function() { [moment.utc('1984-01-01T00:00:00.000Z'), 50], ]); - return invoke(fn, [seriesList, 'none']).then(function(r) { + return invoke(fn, [seriesList, 'none']).then(function (r) { expect(_.map(r.output.list[0].data, 1)).to.eql([10, 40, 50]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/fixtures/series_list.js b/src/plugins/vis_type_timelion/server/series_functions/fixtures/series_list.js index 90d9bc8417ef7..71db5e74efb34 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/fixtures/series_list.js +++ b/src/plugins/vis_type_timelion/server/series_functions/fixtures/series_list.js @@ -21,7 +21,7 @@ import buckets from './bucket_list'; import getSeries from '../helpers/get_series'; import getSeriesList from '../helpers/get_series_list'; -export default function() { +export default function () { return getSeriesList([ getSeries('Negative', buckets, [-51, 17, 82, 20]), getSeries('Nice', buckets, [100, 50, 50, 20]), diff --git a/src/plugins/vis_type_timelion/server/series_functions/fixtures/tl_config.js b/src/plugins/vis_type_timelion/server/series_functions/fixtures/tl_config.js index bf477110be379..6107a2845a7cc 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/fixtures/tl_config.js +++ b/src/plugins/vis_type_timelion/server/series_functions/fixtures/tl_config.js @@ -22,16 +22,16 @@ import sinon from 'sinon'; import timelionDefaults from '../../lib/get_namespaced_settings'; import esResponse from './es_response'; -export default function() { +export default function () { const functions = require('../../lib/load_functions')('series_functions'); const tlConfig = require('../../handlers/lib/tl_config.js')({ - getFunction: name => { + getFunction: (name) => { if (!functions[name]) throw new Error('No such function: ' + name); return functions[name]; }, esDataClient: sinon.stub().returns({ - callAsCurrentUser: function() { + callAsCurrentUser: function () { return Promise.resolve(esResponse); }, }), diff --git a/src/plugins/vis_type_timelion/server/series_functions/graphite.js b/src/plugins/vis_type_timelion/server/series_functions/graphite.js index 7b7bb1541bea0..c0b6ba1bc0fff 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/graphite.js +++ b/src/plugins/vis_type_timelion/server/series_functions/graphite.js @@ -70,12 +70,12 @@ export default new Datasource('graphite', { config.metric; return fetch(URL) - .then(function(resp) { + .then(function (resp) { return resp.json(); }) - .then(function(resp) { - const list = _.map(resp, function(series) { - const data = _.map(series.datapoints, function(point) { + .then(function (resp) { + const list = _.map(resp, function (series) { + const data = _.map(series.datapoints, function (point) { return [point[1] * 1000, point[0]]; }); return { @@ -91,7 +91,7 @@ export default new Datasource('graphite', { list: list, }; }) - .catch(function(e) { + .catch(function (e) { throw e; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/graphite.test.js b/src/plugins/vis_type_timelion/server/series_functions/graphite.test.js index 914e0a7aaa4a1..1184ea5630138 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/graphite.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/graphite.test.js @@ -23,7 +23,7 @@ import fn from './graphite'; jest.mock('node-fetch', () => () => { return Promise.resolve({ - json: function() { + json: function () { return [ { target: '__beer__', @@ -41,22 +41,22 @@ jest.mock('node-fetch', () => () => { import invoke from './helpers/invoke_series_fn.js'; -describe('graphite', function() { - it('should wrap the graphite response up in a seriesList', function() { - return invoke(fn, []).then(function(result) { +describe('graphite', function () { + it('should wrap the graphite response up in a seriesList', function () { + return invoke(fn, []).then(function (result) { expect(result.output.list[0].data[0][1]).to.eql(3); expect(result.output.list[0].data[1][1]).to.eql(14); }); }); - it('should convert the seconds to milliseconds', function() { - return invoke(fn, []).then(function(result) { + it('should convert the seconds to milliseconds', function () { + return invoke(fn, []).then(function (result) { expect(result.output.list[0].data[1][0]).to.eql(2000 * 1000); }); }); - it('should set the label to that of the graphite target', function() { - return invoke(fn, []).then(function(result) { + it('should set the label to that of the graphite target', function () { + return invoke(fn, []).then(function (result) { expect(result.output.list[0].label).to.eql('__beer__'); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series.js b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series.js index 0c5c61923d6e7..76ac57f8247ec 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series.js +++ b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series.js @@ -22,7 +22,7 @@ import _ from 'lodash'; export default function getSeries(name, buckets, points) { const fill = _.partial( _.zip, - _.map(buckets, function(bucket) { + _.map(buckets, function (bucket) { return bucket.valueOf(); }) ); diff --git a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series_list.js b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series_list.js index b8e64caeeade7..c32f919a269b8 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series_list.js +++ b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_series_list.js @@ -19,7 +19,7 @@ import _ from 'lodash'; -export default function(list, overrides) { +export default function (list, overrides) { return _.merge( { type: 'seriesList', diff --git a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_single_series_list.js b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_single_series_list.js index c9cd3393e62f0..b307461a4133e 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/helpers/get_single_series_list.js +++ b/src/plugins/vis_type_timelion/server/series_functions/helpers/get_single_series_list.js @@ -21,6 +21,6 @@ import getSeries from './get_series'; import getSeriesList from './get_series_list'; import _ from 'lodash'; -export default function(name, data) { +export default function (name, data) { return getSeriesList([getSeries(name, _.map(data, 0), _.map(data, 1))]); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/helpers/invoke_series_fn.js b/src/plugins/vis_type_timelion/server/series_functions/helpers/invoke_series_fn.js index 3a8bb92a883f8..8ea6e7af59231 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/helpers/invoke_series_fn.js +++ b/src/plugins/vis_type_timelion/server/series_functions/helpers/invoke_series_fn.js @@ -25,12 +25,12 @@ import indexArguments from '../../handlers/lib/index_arguments'; export default function invokeSeriesFn(fnDef, args, tlConfigOverrides) { const tlConfig = _.merge(require('../fixtures/tl_config')(), tlConfigOverrides); - return Promise.all(args).then(function(args) { + return Promise.all(args).then(function (args) { args.byName = indexArguments(fnDef, args); const input = _.cloneDeep(args); - return Promise.resolve(fnDef.originalFn(args, tlConfig)).then(function(output) { + return Promise.resolve(fnDef.originalFn(args, tlConfig)).then(function (output) { const result = { output: output, input: input, diff --git a/src/plugins/vis_type_timelion/server/series_functions/hide.js b/src/plugins/vis_type_timelion/server/series_functions/hide.js index 5a461e833b75a..fb33f739d6057 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/hide.js +++ b/src/plugins/vis_type_timelion/server/series_functions/hide.js @@ -39,7 +39,7 @@ export default new Chainable('hide', { defaultMessage: 'Hide the series by default', }), fn: function hideFn(args) { - return alter(args, function(eachSeries, hide) { + return alter(args, function (eachSeries, hide) { eachSeries._hide = hide == null ? true : hide; return eachSeries; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/hide.test.js b/src/plugins/vis_type_timelion/server/series_functions/hide.test.js index 5e71c1508e9e0..ad330bb7844de 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/hide.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/hide.test.js @@ -30,14 +30,14 @@ describe('hide.js', () => { }); it('hides a series', () => { - return invoke(fn, [seriesList, true]).then(r => { - _.each(r.output.list, series => expect(series._hide).to.equal(true)); + return invoke(fn, [seriesList, true]).then((r) => { + _.each(r.output.list, (series) => expect(series._hide).to.equal(true)); }); }); it('unhides a series', () => { - return invoke(fn, [seriesList, false]).then(r => { - _.each(r.output.list, series => expect(series._hide).to.equal(false)); + return invoke(fn, [seriesList, false]).then((r) => { + _.each(r.output.list, (series) => expect(series._hide).to.equal(false)); }); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/holt/index.js b/src/plugins/vis_type_timelion/server/series_functions/holt/index.js index 39cfe0bb3556d..dd3274c5766af 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/holt/index.js +++ b/src/plugins/vis_type_timelion/server/series_functions/holt/index.js @@ -98,7 +98,7 @@ export default new Chainable('holt', { const beta = args.byName.beta; const gamma = args.byName.gamma; - _.each(newSeries.list, function(series) { + _.each(newSeries.list, function (series) { const sample = args.byName.sample || series.data.length; // If we use length it should simply never predict // Single exponential smoothing diff --git a/src/plugins/vis_type_timelion/server/series_functions/holt/lib/tes.js b/src/plugins/vis_type_timelion/server/series_functions/holt/lib/tes.js index cafb32614db74..d8d136a5e78ce 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/holt/lib/tes.js +++ b/src/plugins/vis_type_timelion/server/series_functions/holt/lib/tes.js @@ -48,9 +48,9 @@ function initSeasonalComponents(samplePoints, seasonLength) { [] ); - const seasonals = _.times(seasonLength, i => { + const seasonals = _.times(seasonLength, (i) => { let sumOfValsOverAvg = 0; - _.times(sampledSeasonCount, j => { + _.times(sampledSeasonCount, (j) => { sumOfValsOverAvg += samplePoints[seasonLength * j + i] - seasonalAverages[j]; }); @@ -64,7 +64,7 @@ function initSeasonalComponents(samplePoints, seasonLength) { // the difference in points between seasons function initTrend(samplePoints, seasonLength) { let sum = 0; - _.times(seasonLength, i => { + _.times(seasonLength, (i) => { sum += (samplePoints[i + seasonLength] - samplePoints[i]) / seasonLength; }); return sum / seasonLength; diff --git a/src/plugins/vis_type_timelion/server/series_functions/label.js b/src/plugins/vis_type_timelion/server/series_functions/label.js index 1e4782e5a381e..4d9a26c46aaaf 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/label.js +++ b/src/plugins/vis_type_timelion/server/series_functions/label.js @@ -49,7 +49,7 @@ export default new Chainable('label', { }), fn: function labelFn(args) { const config = args.byName; - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { if (config.regex) { eachSeries.label = eachSeries.label.replace(new RegExp(config.regex), config.label); } else { diff --git a/src/plugins/vis_type_timelion/server/series_functions/label.test.js b/src/plugins/vis_type_timelion/server/series_functions/label.test.js index 8d97083769060..6ce6b688c77c4 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/label.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/label.test.js @@ -30,13 +30,13 @@ describe('label.js', () => { }); it('changes the label on the series', () => { - return invoke(fn, [seriesList, 'free beer']).then(r => { - _.each(r.output.list, series => expect(series.label).to.equal('free beer')); + return invoke(fn, [seriesList, 'free beer']).then((r) => { + _.each(r.output.list, (series) => expect(series.label).to.equal('free beer')); }); }); it('can use a regex to capture parts of a series label', () => { - return invoke(fn, [seriesList, 'beer$1', 'Neg(.*)']).then(r => { + return invoke(fn, [seriesList, 'beer$1', 'Neg(.*)']).then((r) => { expect(r.output.list[0].label).to.equal('beerative'); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/legend.js b/src/plugins/vis_type_timelion/server/series_functions/legend.js index b467318686729..aae5b723e30bf 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/legend.js +++ b/src/plugins/vis_type_timelion/server/series_functions/legend.js @@ -113,7 +113,7 @@ export default new Chainable('legend', { defaultMessage: 'Set the position and style of the legend on the plot', }), fn: function legendFn(args) { - return alter(args, function( + return alter(args, function ( eachSeries, position, columns, diff --git a/src/plugins/vis_type_timelion/server/series_functions/legend.test.js b/src/plugins/vis_type_timelion/server/series_functions/legend.test.js index 10789555deac8..3a3b50316c258 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/legend.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/legend.test.js @@ -30,7 +30,7 @@ describe('legend.js', () => { it('should create the _global object if it does not exist', () => { expect(seriesList.list[0]._global).to.equal(undefined); - return invoke(fn, [seriesList, 'nw', 3, true, 'YYYY']).then(r => { + return invoke(fn, [seriesList, 'nw', 3, true, 'YYYY']).then((r) => { expect(r.output.list[0]._global).to.eql({ legend: { noColumns: 3, position: 'nw', showTime: true, timeFormat: 'YYYY' }, }); @@ -38,21 +38,21 @@ describe('legend.js', () => { }); it('should provide default values for time axis display', () => { - return invoke(fn, [seriesList, 'nw', 3]).then(r => { + return invoke(fn, [seriesList, 'nw', 3]).then((r) => { expect(r.output.list[0]._global.legend.showTime).to.equal(true); expect(r.output.list[0]._global.legend.timeFormat).to.equal('MMMM Do YYYY, HH:mm:ss.SSS'); }); }); it('should hide the legend is position is false', () => { - return invoke(fn, [seriesList, false]).then(r => { + return invoke(fn, [seriesList, false]).then((r) => { expect(r.output.list[0]._global.legend.show).to.equal(false); expect(r.output.list[0]._global.legend.showTime).to.equal(false); }); }); it('should set legend.showTime to false when showTime parameter is false', () => { - return invoke(fn, [seriesList, 'nw', 3, false]).then(r => { + return invoke(fn, [seriesList, 'nw', 3, false]).then((r) => { expect(r.output.list[0]._global.legend.showTime).to.equal(false); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/lines.js b/src/plugins/vis_type_timelion/server/series_functions/lines.js index 39b8893692619..b5b6068ce5281 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/lines.js +++ b/src/plugins/vis_type_timelion/server/series_functions/lines.js @@ -67,7 +67,7 @@ export default new Chainable('lines', { defaultMessage: 'Show the seriesList as lines', }), fn: function linesFn(args) { - return alter(args, function(eachSeries, width, fill, stack, show, steps) { + return alter(args, function (eachSeries, width, fill, stack, show, steps) { eachSeries.lines = eachSeries.lines || {}; // Defaults diff --git a/src/plugins/vis_type_timelion/server/series_functions/lines.test.js b/src/plugins/vis_type_timelion/server/series_functions/lines.test.js index c8985cd479150..0a4ba685ab39a 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/lines.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/lines.test.js @@ -30,7 +30,7 @@ describe('lines.js', () => { it('should simply set show, steps, stack and lineWidth', () => { expect(seriesList.list[0]._global).to.equal(undefined); - return invoke(fn, [seriesList, 1, 2, true, true, false]).then(r => { + return invoke(fn, [seriesList, 1, 2, true, true, false]).then((r) => { expect(r.output.list[0].lines.lineWidth).to.equal(1); expect(r.output.list[0].lines.show).to.equal(true); expect(r.output.list[0].stack).to.equal(true); @@ -40,7 +40,7 @@ describe('lines.js', () => { it('should set lineWidth to 3 by default, and nothing else', () => { expect(seriesList.list[0]._global).to.equal(undefined); - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { expect(r.output.list[0].lines.lineWidth).to.equal(3); expect(r.output.list[0].lines.fill).to.equal(undefined); expect(r.output.list[0].lines.show).to.equal(undefined); diff --git a/src/plugins/vis_type_timelion/server/series_functions/log.js b/src/plugins/vis_type_timelion/server/series_functions/log.js index 4dc356cb9e7df..7b9ce4c9f68ec 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/log.js +++ b/src/plugins/vis_type_timelion/server/series_functions/log.js @@ -42,8 +42,8 @@ export default new Chainable('log', { }), fn: function logFn(args) { const config = args.byName; - return alter(args, function(eachSeries) { - const data = _.map(eachSeries.data, function(point) { + return alter(args, function (eachSeries) { + 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/plugins/vis_type_timelion/server/series_functions/log.test.js b/src/plugins/vis_type_timelion/server/series_functions/log.test.js index f37553508bc8a..b658d84cd1afa 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/log.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/log.test.js @@ -30,7 +30,7 @@ describe('log.js', () => { }); it('should return the log10 value of every value', () => { - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { expect(_.map(r.output.list[4].data, 1)).to.eql([1, 2, 1, 0]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/max.js b/src/plugins/vis_type_timelion/server/series_functions/max.js index 26680df7df1c4..65cf627801338 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/max.js +++ b/src/plugins/vis_type_timelion/server/series_functions/max.js @@ -42,7 +42,7 @@ export default new Chainable('max', { 'Maximum values of one or more series in a seriesList to each position, in each series, of the input seriesList', }), fn: function maxFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return Math.max(a, b); }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/max.test.js b/src/plugins/vis_type_timelion/server/series_functions/max.test.js index 7b3d819d0666b..9ac9a3eff5582 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/max.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/max.test.js @@ -30,7 +30,7 @@ describe('max.js', () => { }); it('keeps the max of a series vs a number', () => { - return invoke(fn, [seriesList, 20]).then(r => { + return invoke(fn, [seriesList, 20]).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([20, 20, 82, 20]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/min.js b/src/plugins/vis_type_timelion/server/series_functions/min.js index a3dc912d1d14b..0c838023405d7 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/min.js +++ b/src/plugins/vis_type_timelion/server/series_functions/min.js @@ -42,7 +42,7 @@ export default new Chainable('min', { 'Minimum values of one or more series in a seriesList to each position, in each series, of the input seriesList', }), fn: function minFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return Math.min(a, b); }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/min.test.js b/src/plugins/vis_type_timelion/server/series_functions/min.test.js index d30339d6218f8..691185a7d068e 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/min.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/min.test.js @@ -30,7 +30,7 @@ describe('min.js', () => { }); it('keeps the min of a series vs a number', () => { - return invoke(fn, [seriesList, 20]).then(r => { + return invoke(fn, [seriesList, 20]).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([-51, 17, 20, 20]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/movingaverage.js b/src/plugins/vis_type_timelion/server/series_functions/movingaverage.js index be5f902770347..108eb0c72f19d 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/movingaverage.js +++ b/src/plugins/vis_type_timelion/server/series_functions/movingaverage.js @@ -52,7 +52,7 @@ export default new Chainable('movingaverage', { validPositions: validPositions.join(', '), }, }), - suggestions: validPositions.map(position => { + suggestions: validPositions.map((position) => { const suggestion = { name: position }; if (position === defaultPosition) { suggestion.help = 'default'; @@ -67,7 +67,7 @@ export default new Chainable('movingaverage', { 'Calculate the moving average over a given window. Nice for smoothing noisy series', }), fn: function movingaverageFn(args, tlConfig) { - return alter(args, function(eachSeries, _window, _position) { + return alter(args, function (eachSeries, _window, _position) { // _window always needs to be a number, if isn't we have to make it into one. if (typeof _window !== 'number') { // Ok, I guess its a datemath expression @@ -103,7 +103,7 @@ export default new Chainable('movingaverage', { const average = _.chain(pairSlice) .map(1) - .reduce(function(memo, num) { + .reduce(function (memo, num) { return memo + num; }) .value() / _window; @@ -114,18 +114,18 @@ export default new Chainable('movingaverage', { if (_position === 'center') { const windowLeft = Math.floor(_window / 2); const windowRight = _window - windowLeft; - eachSeries.data = _.map(pairs, function(point, i) { + 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)); }); } else if (_position === 'left') { - eachSeries.data = _.map(pairs, function(point, i) { + eachSeries.data = _.map(pairs, function (point, i) { const cursor = i + 1; if (cursor < _window) return [point[0], null]; return toPoint(point, pairs.slice(cursor - _window, cursor)); }); } else if (_position === 'right') { - eachSeries.data = _.map(pairs, function(point, i) { + eachSeries.data = _.map(pairs, function (point, i) { if (i > pairsLen - _window) return [point[0], null]; return toPoint(point, pairs.slice(i, i + _window)); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/movingaverage.test.js b/src/plugins/vis_type_timelion/server/series_functions/movingaverage.test.js index 760d5af92a1ef..a71c57cab28e3 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/movingaverage.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/movingaverage.test.js @@ -46,32 +46,32 @@ describe('movingaverage.js', () => { }); it('centers the averaged series by default', () => { - return invoke(fn, [seriesList, 3]).then(r => { + return invoke(fn, [seriesList, 3]).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([null, 20, 30, 40, null]); }); }); it('aligns the moving average to the left', () => { - return invoke(fn, [seriesList, 3, 'left']).then(r => { + return invoke(fn, [seriesList, 3, 'left']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([null, null, 20, 30, 40]); }); }); it('aligns the moving average to the right', () => { - return invoke(fn, [seriesList, 3, 'right']).then(r => { + return invoke(fn, [seriesList, 3, 'right']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([20, 30, 40, null, null]); }); }); describe('date math', () => { it('accepts 2 years', () => { - return invoke(fn, [seriesList, '2y', 'left']).then(r => { + return invoke(fn, [seriesList, '2y', 'left']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([null, 15, 25, 35, 45]); }); }); it('accepts 3 years', () => { - return invoke(fn, [seriesList, '3y', 'left']).then(r => { + return invoke(fn, [seriesList, '3y', 'left']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([null, null, 20, 30, 40]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/movingstd.js b/src/plugins/vis_type_timelion/server/series_functions/movingstd.js index 318bfd1d06300..a7ecb4d5b4738 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/movingstd.js +++ b/src/plugins/vis_type_timelion/server/series_functions/movingstd.js @@ -58,7 +58,7 @@ export default new Chainable('movingstd', { 'Rounding errors may become more noticeable with very long series, or series with very large numbers.', }), fn: function movingstdFn(args) { - return alter(args, function(eachSeries, _window, _position) { + return alter(args, function (eachSeries, _window, _position) { _position = _position || defaultPosition; if (!_.contains(positions, _position)) { @@ -83,17 +83,17 @@ export default new Chainable('movingstd', { const average = _.chain(pairSlice) .map(1) - .reduce(function(memo, num) { + .reduce(function (memo, num) { return memo + num; }) .value() / _window; const variance = _.chain(pairSlice) - .map(function(point) { + .map(function (point) { return Math.pow(point[1] - average, 2); }) - .reduce(function(memo, num) { + .reduce(function (memo, num) { return memo + num; }) .value() / @@ -105,17 +105,17 @@ export default new Chainable('movingstd', { if (_position === 'center') { const windowLeft = Math.floor(_window / 2); const windowRight = _window - windowLeft; - eachSeries.data = _.map(pairs, function(point, i) { + 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)); }); } else if (_position === 'left') { - eachSeries.data = _.map(pairs, function(point, i) { + eachSeries.data = _.map(pairs, function (point, i) { if (i < _window) return [point[0], null]; return toPoint(point, pairs.slice(i - _window, i)); }); } else if (_position === 'right') { - eachSeries.data = _.map(pairs, function(point, i) { + eachSeries.data = _.map(pairs, function (point, i) { if (i >= pairsLen - _window) return [point[0], null]; return toPoint(point, pairs.slice(i, i + _window)); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/movingstd.test.js b/src/plugins/vis_type_timelion/server/series_functions/movingstd.test.js index bd165488687d4..8f37097959e96 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/movingstd.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/movingstd.test.js @@ -66,7 +66,7 @@ describe('movingstd.js', () => { const position = 'left'; const results = await invoke(fn, [seriesList, numWindows, position]); - const resultPoints = results.output.list[0].data.map(row => { + const resultPoints = results.output.list[0].data.map((row) => { // row is an array; index 0 is the time bucket, index 1 is the value return row[1]; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/multiply.js b/src/plugins/vis_type_timelion/server/series_functions/multiply.js index 3bab685b530e8..126200f8b9ab0 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/multiply.js +++ b/src/plugins/vis_type_timelion/server/series_functions/multiply.js @@ -41,7 +41,7 @@ export default new Chainable('multiply', { 'Multiply the values of one or more series in a seriesList to each position, in each series, of the input seriesList', }), fn: function multiplyFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return a * b; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/multiply.test.js b/src/plugins/vis_type_timelion/server/series_functions/multiply.test.js index f460e5dd30731..906646cf971b5 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/multiply.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/multiply.test.js @@ -30,7 +30,7 @@ describe('multiply.js', () => { }); it('multiplies by a number', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([200, 100, 100, 40]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/points.js b/src/plugins/vis_type_timelion/server/series_functions/points.js index f2c0472c70ab2..bf797bb5aa343 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/points.js +++ b/src/plugins/vis_type_timelion/server/series_functions/points.js @@ -68,7 +68,7 @@ export default new Chainable('points', { }, }), types: ['string', 'null'], - suggestions: validSymbols.map(symbol => { + suggestions: validSymbols.map((symbol) => { const suggestion = { name: symbol }; if (symbol === defaultSymbol) { suggestion.help = 'default'; @@ -88,7 +88,7 @@ export default new Chainable('points', { defaultMessage: 'Show the series as points', }), fn: function pointsFn(args) { - return alter(args, function(eachSeries, radius, weight, fill, fillColor, symbol, show) { + return alter(args, function (eachSeries, radius, weight, fill, fillColor, symbol, show) { eachSeries.points = eachSeries.points || {}; eachSeries.points.radius = radius == null ? undefined : radius; diff --git a/src/plugins/vis_type_timelion/server/series_functions/points.test.js b/src/plugins/vis_type_timelion/server/series_functions/points.test.js index c45d68a5e4550..fe7b6f13e1378 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/points.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/points.test.js @@ -31,40 +31,40 @@ describe('points.js', () => { }); it('should set the point radius', () => { - return invoke(fn, [seriesList, 1]).then(r => { + return invoke(fn, [seriesList, 1]).then((r) => { expect(r.output.list[0].points.radius).to.equal(1); }); }); it('should set the point lineWidth', () => { - return invoke(fn, [seriesList, null, 3]).then(r => { + return invoke(fn, [seriesList, null, 3]).then((r) => { expect(r.output.list[0].points.lineWidth).to.equal(3); }); }); it('should set the point fill', () => { - return invoke(fn, [seriesList, null, null, 3]).then(r => { + return invoke(fn, [seriesList, null, null, 3]).then((r) => { expect(r.output.list[0].points.fill).to.equal(3 / 10); }); }); it('should not set the fill color if fill is not specified', () => { - return invoke(fn, [seriesList, null, null, null, '#333']).then(r => { + return invoke(fn, [seriesList, null, null, null, '#333']).then((r) => { expect(r.output.list[0].points.fillColor).to.equal(undefined); }); }); it('should set the fill color ', () => { - return invoke(fn, [seriesList, null, null, 10, '#333']).then(r => { + return invoke(fn, [seriesList, null, null, 10, '#333']).then((r) => { expect(r.output.list[0].points.fillColor).to.equal('#333'); }); }); describe('symbol', () => { const symbols = ['triangle', 'cross', 'square', 'diamond', 'circle']; - _.each(symbols, symbol => { + _.each(symbols, (symbol) => { it(`is ${symbol}`, () => { - return invoke(fn, [seriesList, null, null, null, null, symbol]).then(r => { + return invoke(fn, [seriesList, null, null, null, null, symbol]).then((r) => { expect(r.output.list[0].points.symbol).to.equal(symbol); }); }); @@ -73,7 +73,7 @@ describe('points.js', () => { it('does not allow undefined symbols', () => { return invoke(fn, [seriesList, null, null, null, null, 'beer']) .then(expect.fail) - .catch(e => { + .catch((e) => { expect(e).to.be.an('error'); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/precision.js b/src/plugins/vis_type_timelion/server/series_functions/precision.js index 71c15fdd46fdd..5c26f6a0dbce3 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/precision.js +++ b/src/plugins/vis_type_timelion/server/series_functions/precision.js @@ -40,13 +40,13 @@ export default new Chainable('precision', { defaultMessage: 'The number of digits to truncate the decimal portion of the value to', }), fn: async function precisionFn(args) { - await alter(args, function(eachSeries, precision) { + await alter(args, function (eachSeries, precision) { eachSeries._meta = eachSeries._meta || {}; eachSeries._meta.precision = precision; return eachSeries; }); - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return parseInt(a * Math.pow(10, b), 10) / Math.pow(10, b); }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/precision.test.js b/src/plugins/vis_type_timelion/server/series_functions/precision.test.js index e8bd2c947c200..e56feb3d7c420 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/precision.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/precision.test.js @@ -30,13 +30,13 @@ describe('precision.js', () => { }); it('keeps the min of a series vs a number', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(_.map(r.output.list[3].data, 1)).to.eql([3.14, 2, 1.43, 0.34]); }); }); it('Adds a _meta to describe the precision to display', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(r.output.list[3]._meta.precision).to.eql(2); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/props.js b/src/plugins/vis_type_timelion/server/series_functions/props.js index 0ec8534d8fff2..6205e4d43fbf0 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/props.js +++ b/src/plugins/vis_type_timelion/server/series_functions/props.js @@ -27,7 +27,7 @@ function unflatten(data) { const regex = new RegExp(/\.?([^.\[\]]+)|\[(\d+)\]/g); const result = {}; - _.each(data, function(val, p) { + _.each(data, function (val, p) { let cur = result; let prop = ''; let m; @@ -77,7 +77,7 @@ export default new Chainable('props', { _.assign(args.byName.inputSeries, properties); return args.byName.inputSeries; } else { - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { _.assign(eachSeries, properties); return eachSeries; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/quandl.js b/src/plugins/vis_type_timelion/server/series_functions/quandl.js index 40400ea44c7fc..775ebb17a8d2c 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/quandl.js +++ b/src/plugins/vis_type_timelion/server/series_functions/quandl.js @@ -108,11 +108,11 @@ export default new Datasource('quandl', { config.apikey; return fetch(URL) - .then(function(resp) { + .then(function (resp) { return resp.json(); }) - .then(function(resp) { - const data = _.map(resp.data, function(bucket) { + .then(function (resp) { + const data = _.map(resp.data, function (bucket) { return [moment(bucket[0]).valueOf(), bucket[config.position]]; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/quandl.test.js b/src/plugins/vis_type_timelion/server/series_functions/quandl.test.js index 67d81e56f145f..22c43a2d6f155 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/quandl.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/quandl.test.js @@ -32,7 +32,7 @@ function parseUrlParams(url) { jest.mock('node-fetch', () => jest.fn(() => Promise.resolve({ - json: function() { + json: function () { return { name: '__beer__', data: [ @@ -49,45 +49,45 @@ jest.mock('node-fetch', () => import invoke from './helpers/invoke_series_fn.js'; -describe('quandl', function() { - beforeEach(function() { +describe('quandl', function () { + beforeEach(function () { jest.clearAllMocks(); }); - it('should wrap the quandl response up in a seriesList', function() { - return invoke(fn, []).then(function(result) { + it('should wrap the quandl response up in a seriesList', function () { + return invoke(fn, []).then(function (result) { expect(result.output.list[0].data[0][1]).toEqual(3); expect(result.output.list[0].data[1][1]).toEqual(14); }); }); - it('should set the label to that of the quandl name', function() { - return invoke(fn, []).then(function(result) { + it('should set the label to that of the quandl name', function () { + return invoke(fn, []).then(function (result) { expect(result.output.list[0].label).toEqual('__beer__'); }); }); - it('should call the quandl API with the quandl code that has been passed', function() { - return invoke(fn, ['BEER/IS_GOOD']).then(function() { + it('should call the quandl API with the quandl code that has been passed', function () { + return invoke(fn, ['BEER/IS_GOOD']).then(function () { expect(fetchMock).toHaveBeenCalled(); expect(fetchMock.mock.calls[0][0].match(/datasets\/(.*).json/)[1]).toEqual('BEER/IS_GOOD'); }); }); - it('should limit the time span and interval to the stuff attached to tlConfig', function() { - return invoke(fn, []).then(function() { + it('should limit the time span and interval to the stuff attached to tlConfig', function () { + return invoke(fn, []).then(function () { const params = parseUrlParams(fetchMock.mock.calls[0][0]); expect(params.trim_start).toEqual(moment.utc(tlConfig.time.from).format('YYYY-MM-DD')); expect(params.trim_end).toEqual(moment.utc(tlConfig.time.to).format('YYYY-MM-DD')); }); }); - it('should throw an error is passed an unsupported interval', function() { + it('should throw an error is passed an unsupported interval', function () { return expect(invoke(fn, [], { time: { interval: '2d' } })).rejects.toThrowError(); }); - it('should use the configured API key when talking to quandl', function() { - return invoke(fn, [], { settings: { 'timelion:quandl.key': 'bEeR' } }).then(function() { + it('should use the configured API key when talking to quandl', function () { + return invoke(fn, [], { settings: { 'timelion:quandl.key': 'bEeR' } }).then(function () { const params = parseUrlParams(fetchMock.mock.calls[0][0]); expect(params.auth_token).toEqual('bEeR'); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/range.js b/src/plugins/vis_type_timelion/server/series_functions/range.js index 5305d0b20cd26..38525bec7226a 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/range.js +++ b/src/plugins/vis_type_timelion/server/series_functions/range.js @@ -47,13 +47,13 @@ export default new Chainable('range', { defaultMessage: 'Changes the max and min of a series while keeping the same shape', }), fn: function range(args) { - return alter(args, function(eachSeries) { + return alter(args, function (eachSeries) { const values = _.map(eachSeries.data, 1); const min = _.min(values); const max = _.max(values); // newvalue= (max'-min')/(max-min)*(value-min)+min'. - const data = _.map(eachSeries.data, function(point) { + 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/plugins/vis_type_timelion/server/series_functions/range.test.js b/src/plugins/vis_type_timelion/server/series_functions/range.test.js index f03488a6f2cf2..b9a514602e364 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/range.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/range.test.js @@ -36,7 +36,7 @@ describe('range.js', () => { }); it('keeps the min of a series vs a number', () => { - return invoke(fn, [seriesList, 1, 4]).then(r => { + return invoke(fn, [seriesList, 1, 4]).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([2, 1, 3, 4]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/scale_interval.js b/src/plugins/vis_type_timelion/server/series_functions/scale_interval.js index 821f2714631cc..8d7ea463df186 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/scale_interval.js +++ b/src/plugins/vis_type_timelion/server/series_functions/scale_interval.js @@ -46,8 +46,8 @@ export default new Chainable('scale_interval', { const currentInterval = toMS(tlConfig.time.interval); const scaleInterval = toMS(args.byName.interval); - return alter(args, function(eachSeries) { - const data = _.map(eachSeries.data, function(point) { + return alter(args, function (eachSeries) { + const data = _.map(eachSeries.data, function (point) { return [point[0], (point[1] / currentInterval) * scaleInterval]; }); eachSeries.data = data; diff --git a/src/plugins/vis_type_timelion/server/series_functions/scale_interval.test.js b/src/plugins/vis_type_timelion/server/series_functions/scale_interval.test.js index dfd5fd349ea04..24e7e1b07048d 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/scale_interval.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/scale_interval.test.js @@ -30,7 +30,7 @@ describe('scale_interval.js', () => { }); it('Can multiply to transform one interval to another', () => { - return invoke(fn, [seriesList, '5y']).then(r => { + return invoke(fn, [seriesList, '5y']).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([500, 250, 250, 100]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/static.js b/src/plugins/vis_type_timelion/server/series_functions/static.js index 405f595cd4d32..631131e6f0b57 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/static.js +++ b/src/plugins/vis_type_timelion/server/series_functions/static.js @@ -53,11 +53,11 @@ export default new Datasource('static', { const begin = _.first(target)[0]; const end = _.last(target)[0]; const step = (end - begin) / (points.length - 1); - data = _.map(points, function(point, i) { + data = _.map(points, function (point, i) { return [begin + i * step, parseFloat(point)]; }); } else { - data = _.map(target, function(bucket) { + data = _.map(target, function (bucket) { return [bucket[0], args.byName.value]; }); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/static.test.js b/src/plugins/vis_type_timelion/server/series_functions/static.test.js index f791009e9e2b4..88ec9fecd904a 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/static.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/static.test.js @@ -25,19 +25,19 @@ import invoke from './helpers/invoke_series_fn.js'; describe('static.js', () => { it('returns a series in which all numbers are the same', () => { - return invoke(fn, [5]).then(r => { + return invoke(fn, [5]).then((r) => { expect(_.unique(_.map(r.output.list[0].data, 1))).to.eql([5]); }); }); it('plots a provided series', () => { - return invoke(fn, ['4:3:2:1']).then(r => { + return invoke(fn, ['4:3:2:1']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([4, 3, 2, 1]); }); }); it('leaves interpolation up to the data source wrapper', () => { - return invoke(fn, ['1:4']).then(r => { + return invoke(fn, ['1:4']).then((r) => { expect(_.map(r.output.list[0].data, 1)).to.eql([1, 4]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/subtract.js b/src/plugins/vis_type_timelion/server/series_functions/subtract.js index c2d83e5d24a61..3f2bd436a91bb 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/subtract.js +++ b/src/plugins/vis_type_timelion/server/series_functions/subtract.js @@ -41,7 +41,7 @@ export default new Chainable('subtract', { 'Subtract the values of one or more series in a seriesList to each position, in each series, of the input seriesList', }), fn: function subtractFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return a - b; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/sum.js b/src/plugins/vis_type_timelion/server/series_functions/sum.js index 269c44badc90c..f09eb29c65241 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/sum.js +++ b/src/plugins/vis_type_timelion/server/series_functions/sum.js @@ -42,7 +42,7 @@ export default new Chainable('sum', { }), aliases: ['add', 'plus'], fn: function sumFn(args) { - return reduce(args, function(a, b) { + return reduce(args, function (a, b) { return a + b; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/sum.test.js b/src/plugins/vis_type_timelion/server/series_functions/sum.test.js index d897d1a958460..360f19c97f8e1 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/sum.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/sum.test.js @@ -30,7 +30,7 @@ describe('sum.js', () => { }); it('it adds a number', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([102, 52, 52, 22]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/title.js b/src/plugins/vis_type_timelion/server/series_functions/title.js index 30202b682cf1b..9d56d04a76017 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/title.js +++ b/src/plugins/vis_type_timelion/server/series_functions/title.js @@ -40,7 +40,7 @@ export default new Chainable('title', { 'Adds a title to the top of the plot. If called on more than 1 seriesList the last call will be used.', }), fn: function hideFn(args) { - return alter(args, function(eachSeries, title) { + return alter(args, function (eachSeries, title) { eachSeries._title = title; return eachSeries; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/title.test.js b/src/plugins/vis_type_timelion/server/series_functions/title.test.js index e2238bb740bcd..c45b91ebfd4d1 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/title.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/title.test.js @@ -30,8 +30,8 @@ describe('title.js', () => { }); it('sets the title property', () => { - return invoke(fn, [seriesList, 'beer']).then(r => { - _.each(r.output.list, series => expect(series._title).to.equal('beer')); + return invoke(fn, [seriesList, 'beer']).then((r) => { + _.each(r.output.list, (series) => expect(series._title).to.equal('beer')); }); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/trend/index.js b/src/plugins/vis_type_timelion/server/series_functions/trend/index.js index a194e6c4c161c..ea5175db3c84b 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/trend/index.js +++ b/src/plugins/vis_type_timelion/server/series_functions/trend/index.js @@ -43,7 +43,7 @@ export default new Chainable('trend', { validRegressions: _.keys(validRegressions).join(', '), }, }), - suggestions: _.keys(validRegressions).map(key => { + suggestions: _.keys(validRegressions).map((key) => { return { name: key, help: validRegressions[key] }; }), }, @@ -72,7 +72,7 @@ export default new Chainable('trend', { fn: function absFn(args) { const newSeries = _.cloneDeep(args.byName.inputSeries); - _.each(newSeries.list, function(series) { + _.each(newSeries.list, function (series) { const length = series.data.length; let start = args.byName.start == null ? 0 : args.byName.start; let end = args.byName.end == null ? length : args.byName.end; @@ -83,11 +83,11 @@ export default new Chainable('trend', { const result = args.byName.mode === 'log' ? log(subset) : linear(subset); - _.each(series.data, function(point) { + _.each(series.data, function (point) { point[1] = null; }); - _.each(result, function(point, i) { + _.each(result, function (point, i) { series.data[start + i] = point; }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/trend/lib/regress.js b/src/plugins/vis_type_timelion/server/series_functions/trend/lib/regress.js index da72e92be9312..816692da7d017 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/trend/lib/regress.js +++ b/src/plugins/vis_type_timelion/server/series_functions/trend/lib/regress.js @@ -28,7 +28,7 @@ import _ from 'lodash'; function sum(data, fn) { return _.reduce( data, - function(sum, d) { + function (sum, d) { return sum + (d[1] == null ? 0 : fn(d)); }, 0 @@ -36,28 +36,28 @@ function sum(data, fn) { } function count(data) { - return _.filter(data, function(d) { + return _.filter(data, function (d) { return d[1] == null ? false : true; }).length; } function mapTuples(data, fn) { - return _.map(data, function(d) { + return _.map(data, function (d) { return [d[0], fn(d)]; }); } export function linear(data) { - const xSum = sum(data, d => { + const xSum = sum(data, (d) => { return d[0]; }); - const ySum = sum(data, d => { + const ySum = sum(data, (d) => { return d[1]; }); - const xSqSum = sum(data, d => { + const xSqSum = sum(data, (d) => { return d[0] * d[0]; }); - const xySum = sum(data, d => { + const xySum = sum(data, (d) => { return d[0] * d[1]; }); const observations = count(data); @@ -66,22 +66,22 @@ export function linear(data) { const intercept = ySum / observations - (gradient * xSum) / observations; - return mapTuples(data, d => { + return mapTuples(data, (d) => { return d[0] * gradient + intercept; }); } export function log(data) { - const logXSum = sum(data, d => { + const logXSum = sum(data, (d) => { return Math.log(d[0]); }); - const yLogXSum = sum(data, d => { + const yLogXSum = sum(data, (d) => { return d[1] * Math.log(d[0]); }); - const ySum = sum(data, d => { + const ySum = sum(data, (d) => { return d[1]; }); - const logXsqSum = sum(data, d => { + const logXsqSum = sum(data, (d) => { return Math.pow(Math.log(d[0]), 2); }); const observations = count(data); @@ -91,7 +91,7 @@ export function log(data) { const a = (ySum - b * logXSum) / observations; - return mapTuples(data, d => { + return mapTuples(data, (d) => { return a + b * Math.log(d[0]); }); } diff --git a/src/plugins/vis_type_timelion/server/series_functions/trim.js b/src/plugins/vis_type_timelion/server/series_functions/trim.js index 7c4ecbbe89e1f..8a8e38ab3a5a7 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/trim.js +++ b/src/plugins/vis_type_timelion/server/series_functions/trim.js @@ -52,12 +52,12 @@ export default new Chainable('trim', { if (config.start == null) config.start = 1; if (config.end == null) config.end = 1; - return alter(args, function(eachSeries) { - _.times(config.start, function(i) { + return alter(args, function (eachSeries) { + _.times(config.start, function (i) { eachSeries.data[i][1] = null; }); - _.times(config.end, function(i) { + _.times(config.end, function (i) { eachSeries.data[eachSeries.data.length - 1 - i][1] = null; }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/trim.test.js b/src/plugins/vis_type_timelion/server/series_functions/trim.test.js index e2b88a52f0045..6b1e88f37c145 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/trim.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/trim.test.js @@ -30,31 +30,31 @@ describe('trim.js', () => { }); it('Sets the first and last values to null by default', () => { - return invoke(fn, [seriesList]).then(r => { + return invoke(fn, [seriesList]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([null, 50, 50, null]); }); }); it('Trims more from the beginning', () => { - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([null, null, 50, null]); }); }); it('Trims more from the end', () => { - return invoke(fn, [seriesList, null, 2]).then(r => { + return invoke(fn, [seriesList, null, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([null, 50, null, null]); }); }); it('Trims nothing from the end', () => { - return invoke(fn, [seriesList, 1, 0]).then(r => { + return invoke(fn, [seriesList, 1, 0]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([null, 50, 50, 20]); }); }); it('Trims nothing from the beginning', () => { - return invoke(fn, [seriesList, 0, 2]).then(r => { + return invoke(fn, [seriesList, 0, 2]).then((r) => { expect(_.map(r.output.list[1].data, 1)).to.eql([100, 50, null, null]); }); }); diff --git a/src/plugins/vis_type_timelion/server/series_functions/worldbank.js b/src/plugins/vis_type_timelion/server/series_functions/worldbank.js index f19bfab01b0f9..7a73fd341a8da 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/worldbank.js +++ b/src/plugins/vis_type_timelion/server/series_functions/worldbank.js @@ -72,24 +72,24 @@ export default new Datasource('worldbank', { '&per_page=1000'; return fetch(URL) - .then(function(resp) { + .then(function (resp) { return resp.json(); }) - .then(function(resp) { + .then(function (resp) { let hasData = false; const respSeries = resp[1]; const deduped = {}; let description; - _.each(respSeries, function(bucket) { + _.each(respSeries, function (bucket) { if (bucket.value != null) hasData = true; description = bucket.country.value + ' ' + bucket.indicator.value; deduped[bucket.date] = bucket.value; }); const data = _.compact( - _.map(deduped, function(val, date) { + _.map(deduped, function (val, date) { // Discard nulls if (val == null) return; return [moment(date, 'YYYY').valueOf(), Number(val)]; @@ -121,7 +121,7 @@ export default new Datasource('worldbank', { ], }; }) - .catch(function(e) { + .catch(function (e) { throw e; }); }, diff --git a/src/plugins/vis_type_timelion/server/series_functions/worldbank_indicators.js b/src/plugins/vis_type_timelion/server/series_functions/worldbank_indicators.js index 7049eefb8f808..305c586a2090f 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/worldbank_indicators.js +++ b/src/plugins/vis_type_timelion/server/series_functions/worldbank_indicators.js @@ -65,16 +65,16 @@ export default new Datasource('worldbank_indicators', { }); const countries = config.country.split(':'); - const seriesLists = _.map(countries, function(country) { + const seriesLists = _.map(countries, function (country) { const code = 'country/' + country + '/indicator/' + config.indicator; const wbArgs = [code]; wbArgs.byName = { code: code }; return worldbank.timelionFn(wbArgs, tlConfig); }); - return Bluebird.map(seriesLists, function(seriesList) { + return Bluebird.map(seriesLists, function (seriesList) { return seriesList.list[0]; - }).then(function(list) { + }).then(function (list) { return { type: 'seriesList', list: list, diff --git a/src/plugins/vis_type_timelion/server/series_functions/yaxis.js b/src/plugins/vis_type_timelion/server/series_functions/yaxis.js index 2653ea398aa14..7a249305ee76e 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/yaxis.js +++ b/src/plugins/vis_type_timelion/server/series_functions/yaxis.js @@ -89,7 +89,7 @@ export default new Chainable('yaxis', { formatters: _.values(tickFormatters).join(', '), }, }), - suggestions: _.keys(tickFormatters).map(key => { + suggestions: _.keys(tickFormatters).map((key) => { return { name: key, help: tickFormatters[key] }; }), }, @@ -106,7 +106,7 @@ export default new Chainable('yaxis', { 'Configures a variety of y-axis options, the most important likely being the ability to add an Nth (eg 2nd) y-axis', }), fn: function yaxisFn(args) { - return alter(args, function( + return alter(args, function ( eachSeries, yaxis, min, diff --git a/src/plugins/vis_type_timelion/server/series_functions/yaxis.test.js b/src/plugins/vis_type_timelion/server/series_functions/yaxis.test.js index 87001ce45fd39..53a0b4641e0f2 100644 --- a/src/plugins/vis_type_timelion/server/series_functions/yaxis.test.js +++ b/src/plugins/vis_type_timelion/server/series_functions/yaxis.test.js @@ -30,20 +30,20 @@ describe('yaxis.js', () => { it('creates the yaxes array', () => { expect(seriesList._global).to.equal(undefined); - return invoke(fn, [seriesList, 2]).then(r => { + return invoke(fn, [seriesList, 2]).then((r) => { expect(r.output.list[0]._global.yaxes).to.be.an('array'); }); }); it('puts odd numbers of the left, even on the right, by default', () => { return Bluebird.all([ - invoke(fn, [seriesList, 1]).then(r => { + invoke(fn, [seriesList, 1]).then((r) => { expect(r.output.list[0]._global.yaxes[0].position).to.equal('left'); }), - invoke(fn, [seriesList, 2]).then(r => { + invoke(fn, [seriesList, 2]).then((r) => { expect(r.output.list[0]._global.yaxes[1].position).to.equal('right'); }), - invoke(fn, [seriesList, 3]).then(r => { + invoke(fn, [seriesList, 3]).then((r) => { expect(r.output.list[0]._global.yaxes[2].position).to.equal('left'); }), ]); @@ -51,10 +51,10 @@ describe('yaxis.js', () => { it('it lets you override default positions', () => { return Bluebird.all([ - invoke(fn, [seriesList, 1, null, null, 'right']).then(r => { + invoke(fn, [seriesList, 1, null, null, 'right']).then((r) => { expect(r.output.list[0]._global.yaxes[0].position).to.equal('right'); }), - invoke(fn, [seriesList, 2, null, null, 'right']).then(r => { + invoke(fn, [seriesList, 2, null, null, 'right']).then((r) => { expect(r.output.list[0]._global.yaxes[1].position).to.equal('right'); }), ]); @@ -62,10 +62,10 @@ describe('yaxis.js', () => { it('sets the minimum (default: no min)', () => { return Bluebird.all([ - invoke(fn, [seriesList, 1, null]).then(r => { + invoke(fn, [seriesList, 1, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].min).to.equal(null); }), - invoke(fn, [seriesList, 2, 10]).then(r => { + invoke(fn, [seriesList, 2, 10]).then((r) => { expect(r.output.list[0]._global.yaxes[1].min).to.equal(10); }), ]); @@ -73,10 +73,10 @@ describe('yaxis.js', () => { it('sets the max (default: no max)', () => { return Bluebird.all([ - invoke(fn, [seriesList, 1, null]).then(r => { + invoke(fn, [seriesList, 1, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].max).to.equal(undefined); }), - invoke(fn, [seriesList, 2, null, 10]).then(r => { + invoke(fn, [seriesList, 2, null, 10]).then((r) => { expect(r.output.list[0]._global.yaxes[1].max).to.equal(10); }), ]); @@ -84,26 +84,26 @@ describe('yaxis.js', () => { it('sets the units (default: no unit', () => { return Bluebird.all([ - invoke(fn, [seriesList, 1, null, null, null, null, null, null]).then(r => { + invoke(fn, [seriesList, 1, null, null, null, null, null, null]).then((r) => { expect(r.output.list[0]._global.yaxes[0].units).to.equal(undefined); }), - invoke(fn, [seriesList, 2, null, null, null, null, null, 'bits']).then(r => { + invoke(fn, [seriesList, 2, null, null, null, null, null, 'bits']).then((r) => { expect(r.output.list[0]._global.yaxes[1].units).to.be.an('object'); }), ]); }); it('throws an error if currency is not three letter code', () => { - invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:abcde']).catch(e => { + invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:abcde']).catch((e) => { expect(e).to.be.an.instanceof(Error); }); - invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:12']).catch(e => { + invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:12']).catch((e) => { expect(e).to.be.an.instanceof(Error); }); - invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:$#']).catch(e => { + invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:$#']).catch((e) => { expect(e).to.be.an.instanceof(Error); }); - invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:ab']).catch(e => { + invoke(fn, [seriesList, 1, null, null, null, null, null, 'currency:ab']).catch((e) => { expect(e).to.be.an.instanceof(Error); }); }); diff --git a/src/plugins/vis_type_timeseries/common/calculate_label.js b/src/plugins/vis_type_timeseries/common/calculate_label.js index 71aa0aed7dc11..9f3030eeb6eae 100644 --- a/src/plugins/vis_type_timeseries/common/calculate_label.js +++ b/src/plugins/vis_type_timeseries/common/calculate_label.js @@ -84,7 +84,7 @@ export function calculateLabel(metric, metrics) { } if (includes(paths, metric.type)) { - const targetMetric = metrics.find(m => startsWith(metric.field, m.id)); + const targetMetric = metrics.find((m) => startsWith(metric.field, m.id)); const targetLabel = calculateLabel(targetMetric, metrics); // For percentiles we need to parse the field id to extract the percentile diff --git a/src/plugins/vis_type_timeseries/common/extract_index_patterns.js b/src/plugins/vis_type_timeseries/common/extract_index_patterns.js index 5c4b9709886b7..3fb005b477199 100644 --- a/src/plugins/vis_type_timeseries/common/extract_index_patterns.js +++ b/src/plugins/vis_type_timeseries/common/extract_index_patterns.js @@ -25,7 +25,7 @@ export function extractIndexPatterns(panel, excludedFields = {}) { patterns.push(panel.index_pattern); } - panel.series.forEach(series => { + panel.series.forEach((series) => { const indexPattern = series.series_index_pattern; if (indexPattern && series.override_index_pattern && !excludedFields[indexPattern]) { patterns.push(indexPattern); @@ -33,7 +33,7 @@ export function extractIndexPatterns(panel, excludedFields = {}) { }); if (panel.annotations) { - panel.annotations.forEach(item => { + panel.annotations.forEach((item) => { const indexPattern = item.index_pattern; if (indexPattern && !excludedFields[indexPattern]) { patterns.push(indexPattern); diff --git a/src/plugins/vis_type_timeseries/common/get_last_value.js b/src/plugins/vis_type_timeseries/common/get_last_value.js index fb5d4a0c7721d..4ee7d122b3c03 100644 --- a/src/plugins/vis_type_timeseries/common/get_last_value.js +++ b/src/plugins/vis_type_timeseries/common/get_last_value.js @@ -20,7 +20,7 @@ import { isArray, last } from 'lodash'; const DEFAULT_VALUE = 0; -const extractValue = data => (data && data[1]) || null; +const extractValue = (data) => (data && data[1]) || null; export const getLastValue = (data, defaultValue = DEFAULT_VALUE) => { if (!isArray(data)) { diff --git a/src/plugins/vis_type_timeseries/common/to_percentile_number.js b/src/plugins/vis_type_timeseries/common/to_percentile_number.js index 1b12592c514d5..b81133db8f084 100644 --- a/src/plugins/vis_type_timeseries/common/to_percentile_number.js +++ b/src/plugins/vis_type_timeseries/common/to_percentile_number.js @@ -18,5 +18,5 @@ */ const percentileNumberTest = /\d+\.\d+/; -export const toPercentileNumber = value => +export const toPercentileNumber = (value) => percentileNumberTest.test(`${value}`) ? value : `${value}.0`; diff --git a/src/plugins/vis_type_timeseries/public/application/components/add_delete_buttons.test.js b/src/plugins/vis_type_timeseries/public/application/components/add_delete_buttons.test.js index 01b4ed7efba35..7afa71d6ba38f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/add_delete_buttons.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/add_delete_buttons.test.js @@ -27,30 +27,21 @@ describe('AddDeleteButtons', () => { it('calls onAdd={handleAdd}', () => { const handleAdd = sinon.spy(); const wrapper = shallowWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(0).simulate('click'); expect(handleAdd.calledOnce).to.equal(true); }); it('calls onDelete={handleDelete}', () => { const handleDelete = sinon.spy(); const wrapper = shallowWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(1).simulate('click'); expect(handleDelete.calledOnce).to.equal(true); }); it('calls onClone={handleClone}', () => { const handleClone = sinon.spy(); const wrapper = shallowWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(0).simulate('click'); expect(handleClone.calledOnce).to.equal(true); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/agg_select.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/agg_select.js index 8607ff184dfaa..7ff6b6eb56692 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/agg_select.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/agg_select.js @@ -225,7 +225,7 @@ const specialAggs = [ const allAggOptions = [...metricAggs, ...pipelineAggs, ...siblingAggs, ...specialAggs]; function filterByPanelType(panelType) { - return agg => { + return (agg) => { if (panelType === 'table') return agg.value !== 'series_agg'; return true; }; @@ -234,11 +234,11 @@ function filterByPanelType(panelType) { function AggSelectUi(props) { const { siblings, panelType, value, onChange, uiRestrictions, ...rest } = props; - const selectedOptions = allAggOptions.filter(option => { + const selectedOptions = allAggOptions.filter((option) => { return value === option.value && isMetricEnabled(option.value, uiRestrictions); }); - let enablePipelines = siblings.some(s => !!metricAggs.find(m => m.value === s.type)); + let enablePipelines = siblings.some((s) => !!metricAggs.find((m) => m.value === s.type)); if (siblings.length <= 1) enablePipelines = false; @@ -246,7 +246,7 @@ function AggSelectUi(props) { if (panelType === 'metrics') { options = metricAggs; } else { - const disableSiblingAggs = agg => ({ + const disableSiblingAggs = (agg) => ({ ...agg, disabled: !enablePipelines || !isMetricEnabled(agg.value, uiRestrictions), }); @@ -256,7 +256,7 @@ function AggSelectUi(props) { label: i18n.translate('visTypeTimeseries.aggSelect.aggGroups.metricAggLabel', { defaultMessage: 'Metric Aggregations', }), - options: metricAggs.map(agg => ({ + options: metricAggs.map((agg) => ({ ...agg, disabled: !isMetricEnabled(agg.value, uiRestrictions), })), @@ -282,7 +282,7 @@ function AggSelectUi(props) { ]; } - const handleChange = selectedOptions => { + const handleChange = (selectedOptions) => { if (!selectedOptions || selectedOptions.length <= 0) return; onChange(selectedOptions); }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/aggs.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/aggs.js index 9c2f1c01f9648..772b62b14f811 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/aggs.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/aggs.js @@ -46,7 +46,7 @@ export class Aggs extends PureComponent { customDragHandle={true} draggableId={`${DROPPABLE_ID}:${model.id}:${row.id}`} > - {provided => ( + {(provided) => ( Array.isArray(model.variables) && model.script !== undefined; +const checkModel = (model) => Array.isArray(model.variables) && model.script !== undefined; export function CalculationAgg(props) { const htmlId = htmlIdGenerator(); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/derivative.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/derivative.js index f9800bac21886..faf1a59adc4aa 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/derivative.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/derivative.js @@ -36,7 +36,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export const DerivativeAgg = props => { +export const DerivativeAgg = (props) => { const { siblings } = props; const defaults = { unit: '' }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/filter_ratio.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/filter_ratio.js index 5bd7f6557e887..b5311e3832da4 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/filter_ratio.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/filter_ratio.js @@ -38,7 +38,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/public'; import { METRIC_TYPES } from '../../../../../../plugins/vis_type_timeseries/common/metric_types'; -export const FilterRatioAgg = props => { +export const FilterRatioAgg = (props) => { const { series, fields, panel } = props; const handleChange = createChangeHandler(props.onChange, props.model); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/math.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/math.js index 5ffcef12c3fcb..20fc88ba724bc 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/math.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/math.js @@ -39,7 +39,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -const checkModel = model => Array.isArray(model.variables) && model.script !== undefined; +const checkModel = (model) => Array.isArray(model.variables) && model.script !== undefined; export function MathAgg(props) { const { siblings, model } = props; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/metric_select.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/metric_select.js index 18daecd699903..83ddc23648ad3 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/metric_select.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/metric_select.js @@ -29,7 +29,7 @@ import { toPercentileNumber } from '../../../../../../plugins/vis_type_timeserie import { METRIC_TYPES } from '../../../../../../plugins/vis_type_timeseries/common/metric_types'; function createTypeFilter(restrict, exclude) { - return metric => { + return (metric) => { if (includes(exclude, metric.type)) return false; switch (restrict) { case 'basic': @@ -42,7 +42,7 @@ function createTypeFilter(restrict, exclude) { // This filters out sibling aggs, percentiles, and special aggs (like Series Agg) export function filterRows(includeSiblings) { - return row => { + return (row) => { if (includeSiblings) { return !/^series/.test(row.type) && !/^percentile/.test(row.type) && row.type !== 'math'; } @@ -78,13 +78,13 @@ function MetricSelectUi(props) { // could have multiple percentiles associated with it. So the user needs a way // to specify which percentile the want to use. const percentileOptions = siblings - .filter(row => /^percentile/.test(row.type)) + .filter((row) => /^percentile/.test(row.type)) .reduce((acc, row) => { const label = calculateLabel(row, calculatedMetrics); switch (row.type) { case METRIC_TYPES.PERCENTILE_RANK: - (row.values || []).forEach(p => { + (row.values || []).forEach((p) => { const value = toPercentileNumber(p); acc.push({ @@ -94,7 +94,7 @@ function MetricSelectUi(props) { }); case METRIC_TYPES.PERCENTILE: - (row.percentiles || []).forEach(p => { + (row.percentiles || []).forEach((p) => { if (p.value) { const value = toPercentileNumber(p.value); @@ -109,13 +109,13 @@ function MetricSelectUi(props) { return acc; }, []); - const options = siblings.filter(filterRows(includeSiblings)).map(row => { + const options = siblings.filter(filterRows(includeSiblings)).map((row) => { const label = calculateLabel(row, calculatedMetrics); return { value: row.id, label }; }); const allOptions = [...options, ...additionalOptions, ...percentileOptions]; - const selectedOption = allOptions.find(option => { + const selectedOption = allOptions.find((option) => { return value === option.value; }); const selectedOptions = selectedOption ? [selectedOption] : []; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/moving_average.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/moving_average.js index 5843eab3f4707..316e0f9af43bd 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/moving_average.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/moving_average.js @@ -51,7 +51,7 @@ const DEFAULTS = { const shouldShowHint = ({ model_type: type, window, period }) => type === MODEL_TYPES.WEIGHTED_EXPONENTIAL_TRIPLE && period * 2 > window; -export const MovingAverageAgg = props => { +export const MovingAverageAgg = (props) => { const { siblings } = props; const model = { ...DEFAULTS, ...props.model }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile.js index 500bba14d66c9..6a7bf1bffe83c 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile.js @@ -38,7 +38,7 @@ import { Percentiles, newPercentile } from './percentile_ui'; const RESTRICT_FIELDS = [KBN_FIELD_TYPES.NUMBER]; -const checkModel = model => Array.isArray(model.percentiles); +const checkModel = (model) => Array.isArray(model.percentiles); export function PercentileAgg(props) { const { series, model, panel, fields } = props; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/multi_value_row.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/multi_value_row.js index ee516329a9219..fd64559cc1ec2 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/multi_value_row.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/multi_value_row.js @@ -34,7 +34,7 @@ import { AddDeleteButtons } from '../../add_delete_buttons'; export const MultiValueRow = ({ model, onChange, onDelete, onAdd, disableAdd, disableDelete }) => { const htmlId = htmlIdGenerator(); - const onFieldNumberChange = event => + const onFieldNumberChange = (event) => onChange({ ...model, value: get(event, 'target.value'), diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank.js index 069ea9706e927..c8af4089ed783 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank.js @@ -40,7 +40,7 @@ import { KBN_FIELD_TYPES } from '../../../../../../../plugins/data/public'; const RESTRICT_FIELDS = [KBN_FIELD_TYPES.NUMBER]; -export const PercentileRankAgg = props => { +export const PercentileRankAgg = (props) => { const { series, panel, fields } = props; const defaults = { values: [''] }; const model = { ...defaults, ...props.model }; @@ -52,7 +52,7 @@ export const PercentileRankAgg = props => { const handleChange = createChangeHandler(props.onChange, model); const handleSelectChange = createSelectHandler(handleChange); - const handlePercentileRankValuesChange = values => { + const handlePercentileRankValuesChange = (values) => { handleChange( assign({}, model, { values, diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank_values.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank_values.js index 1e71098cfa1fa..6d52eb9e3515c 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank_values.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_rank/percentile_rank_values.js @@ -23,7 +23,7 @@ import { last } from 'lodash'; import { EuiFlexGroup } from '@elastic/eui'; import { MultiValueRow } from './multi_value_row'; -export const PercentileRankValues = props => { +export const PercentileRankValues = (props) => { const model = props.model || []; const { onChange, disableAdd, disableDelete, showOnlyLastRow } = props; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_ui.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_ui.js index f94c2f609da8f..bd421248a3607 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_ui.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/percentile_ui.js @@ -33,13 +33,13 @@ import { } from '@elastic/eui'; import { injectI18n, FormattedMessage } from '@kbn/i18n/react'; -export const newPercentile = opts => { +export const newPercentile = (opts) => { return _.assign({ id: uuid.v1(), mode: 'line', shade: 0.2 }, opts); }; class PercentilesUi extends Component { handleTextChange(item, name) { - return e => { + return (e) => { const handleChange = collectionActions.handleChange.bind(null, this.props); const part = {}; part[name] = _.get(e, '[0].value', _.get(e, 'target.value')); @@ -97,7 +97,7 @@ class PercentilesUi extends Component { } const labelStyle = { marginBottom: 0 }; const htmlId = htmlIdGenerator(model.id); - const selectedModeOption = modeOptions.find(option => { + const selectedModeOption = modeOptions.find((option) => { return model.mode === option.value; }); return ( diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_only.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_only.js index 2ddbedc92e536..1999862f7aa0e 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_only.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_only.js @@ -34,7 +34,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export const PositiveOnlyAgg = props => { +export const PositiveOnlyAgg = (props) => { const { siblings } = props; const defaults = { unit: '' }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_rate.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_rate.js index 39558fa3a9224..3ca89f7289d65 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_rate.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/positive_rate.js @@ -68,7 +68,7 @@ const UNIT_OPTIONS = [ }, ]; -export const PositiveRateAgg = props => { +export const PositiveRateAgg = (props) => { const defaults = { unit: '' }; const model = { ...defaults, ...props.model }; @@ -80,7 +80,7 @@ export const PositiveRateAgg = props => { (props.series.override_index_pattern && props.series.series_index_pattern) || props.panel.index_pattern; - const selectedUnitOptions = UNIT_OPTIONS.filter(o => o.value === model.unit); + const selectedUnitOptions = UNIT_OPTIONS.filter((o) => o.value === model.unit); return ( { +export const SerialDiffAgg = (props) => { const { siblings } = props; const defaults = { lag: '' }; const model = { ...defaults, ...props.model }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/series_agg.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/series_agg.js index 9e045ca1cc49c..19054f404382e 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/series_agg.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/series_agg.js @@ -108,7 +108,7 @@ function SeriesAggUi(props) { value: 'cumulative_sum', }, ]; - const selectedFunctionOption = functionOptions.find(option => { + const selectedFunctionOption = functionOptions.find((option) => { return model.function === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/static.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/static.js index 1cb829ec8e1f5..d96fa75c96b7e 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/static.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/static.js @@ -35,7 +35,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export const Static = props => { +export const Static = (props) => { const handleChange = createChangeHandler(props.onChange, props.model); const handleSelectChange = createSelectHandler(handleChange); const handleTextChange = createTextHandler(handleChange); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/std_deviation.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/std_deviation.js index 1f0347b210886..286a735be064b 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/std_deviation.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/std_deviation.js @@ -40,7 +40,7 @@ import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/public'; const RESTRICT_FIELDS = [KBN_FIELD_TYPES.NUMBER]; -const StandardDeviationAggUi = props => { +const StandardDeviationAggUi = (props) => { const { series, panel, fields, intl } = props; const defaults = { sigma: '' }; const model = { ...defaults, ...props.model }; @@ -86,7 +86,7 @@ const StandardDeviationAggUi = props => { const indexPattern = (series.override_index_pattern && series.series_index_pattern) || panel.index_pattern; const htmlId = htmlIdGenerator(); - const selectedModeOption = modeOptions.find(option => { + const selectedModeOption = modeOptions.find((option) => { return model.mode === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/std_sibling.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/std_sibling.js index 50b8840ab7101..30e5c57ac90ba 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/std_sibling.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/std_sibling.js @@ -37,7 +37,7 @@ import { } from '@elastic/eui'; import { injectI18n, FormattedMessage } from '@kbn/i18n/react'; -const StandardSiblingAggUi = props => { +const StandardSiblingAggUi = (props) => { const { siblings, intl } = props; const defaults = { sigma: '' }; const model = { ...defaults, ...props.model }; @@ -92,7 +92,7 @@ const StandardSiblingAggUi = props => { value: 'band', }, ]; - const selectedModeOption = modeOptions.find(option => { + const selectedModeOption = modeOptions.find((option) => { return model.mode === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/top_hit.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/top_hit.js index df13b94394061..c63beee222b17 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/top_hit.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/top_hit.js @@ -103,7 +103,7 @@ const getOrderOptions = () => [ const ORDER_DATE_RESTRICT_FIELDS = [KBN_FIELD_TYPES.DATE]; -const TopHitAggUi = props => { +const TopHitAggUi = (props) => { const { fields, series, panel } = props; const defaults = { size: 1, @@ -126,17 +126,17 @@ const TopHitAggUi = props => { const handleSelectChange = createSelectHandler(handleChange); const handleTextChange = createTextHandler(handleChange); - const field = fields[indexPattern].find(f => f.name === model.field); + const field = fields[indexPattern].find((f) => f.name === model.field); const aggWithOptions = getAggWithOptions(field, aggWithOptionsRestrictFields); const orderOptions = getOrderOptions(); const htmlId = htmlIdGenerator(); - const selectedAggWithOption = aggWithOptions.find(option => { + const selectedAggWithOption = aggWithOptions.find((option) => { return model.agg_with === option.value; }); - const selectedOrderOption = orderOptions.find(option => { + const selectedOrderOption = orderOptions.find((option) => { return model.order === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/aggs/vars.js b/src/plugins/vis_type_timeseries/public/application/components/aggs/vars.js index 3d4ce601c7244..004a378f5d86f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/aggs/vars.js +++ b/src/plugins/vis_type_timeseries/public/application/components/aggs/vars.js @@ -27,7 +27,7 @@ import { collectionActions } from '../lib/collection_actions'; import { MetricSelect } from './metric_select'; import { EuiFlexGroup, EuiFlexItem, EuiFieldText } from '@elastic/eui'; -export const newVariable = opts => ({ id: uuid.v1(), name: '', field: '', ...opts }); +export const newVariable = (opts) => ({ id: uuid.v1(), name: '', field: '', ...opts }); export class CalculationVars extends Component { constructor(props) { @@ -36,7 +36,7 @@ export class CalculationVars extends Component { } handleChange(item, name) { - return e => { + return (e) => { const handleChange = collectionActions.handleChange.bind(null, this.props); const part = {}; part[name] = _.get(e, '[0].value', _.get(e, 'target.value')); diff --git a/src/plugins/vis_type_timeseries/public/application/components/annotations_editor.js b/src/plugins/vis_type_timeseries/public/application/components/annotations_editor.js index 4357d4737fbef..34132e5f72716 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/annotations_editor.js +++ b/src/plugins/vis_type_timeseries/public/application/components/annotations_editor.js @@ -66,7 +66,7 @@ export class AnnotationsEditor extends Component { } handleChange(item, name) { - return e => { + return (e) => { const handleChange = collectionActions.handleChange.bind(null, this.props); const part = {}; part[name] = _.get(e, '[0].value', _.get(e, 'target.value')); @@ -88,7 +88,7 @@ export class AnnotationsEditor extends Component { query_string: { query: '', language: getDefaultQueryLanguage() }, }; const model = { ...defaults, ...row }; - const handleChange = part => { + const handleChange = (part) => { const fn = collectionActions.handleChange.bind(null, this.props); fn(_.assign({}, model, part)); }; @@ -174,7 +174,7 @@ export class AnnotationsEditor extends Component { language: model.query_string.language || getDefaultQueryLanguage(), query: model.query_string.query || '', }} - onChange={query => this.handleQueryChange(model, query)} + onChange={(query) => this.handleQueryChange(model, query)} indexPatterns={[model.index_pattern]} />
diff --git a/src/plugins/vis_type_timeseries/public/application/components/color_picker.js b/src/plugins/vis_type_timeseries/public/application/components/color_picker.js index 2dca6a7f90eb8..f12797518cd28 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/color_picker.js +++ b/src/plugins/vis_type_timeseries/public/application/components/color_picker.js @@ -35,7 +35,7 @@ export class ColorPicker extends Component { }; } - handleChange = color => { + handleChange = (color) => { const { rgb } = color; const part = {}; part[this.props.name] = `rgba(${rgb.r},${rgb.g},${rgb.b},${rgb.a})`; diff --git a/src/plugins/vis_type_timeseries/public/application/components/color_picker.test.js b/src/plugins/vis_type_timeseries/public/application/components/color_picker.test.js index 89e3a666dab47..8d3c65833bdda 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/color_picker.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/color_picker.test.js @@ -34,10 +34,7 @@ describe('ColorPicker', () => { const wrapper = mount(); const stateBefore = wrapper.state(); - wrapper - .find('button') - .at(0) - .simulate('click'); + wrapper.find('button').at(0).simulate('click'); const stateAfter = wrapper.state(); expect(stateBefore.displayPicker).toBe(!stateAfter.displayPicker); diff --git a/src/plugins/vis_type_timeseries/public/application/components/color_rules.js b/src/plugins/vis_type_timeseries/public/application/components/color_rules.js index 9257fc18fd75e..a0cd206822223 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/color_rules.js +++ b/src/plugins/vis_type_timeseries/public/application/components/color_rules.js @@ -41,7 +41,7 @@ class ColorRulesUI extends Component { } handleChange(item, name, cast = String) { - return e => { + return (e) => { const handleChange = collectionActions.handleChange.bind(null, this.props); const part = {}; part[name] = cast(_.get(e, '[0].value', _.get(e, 'target.value'))); @@ -87,12 +87,12 @@ class ColorRulesUI extends Component { value: 'lte', }, ]; - const handleColorChange = part => { + const handleColorChange = (part) => { const handleChange = collectionActions.handleChange.bind(null, this.props); handleChange(_.assign({}, model, part)); }; const htmlId = htmlIdGenerator(model.id); - const selectedOperatorOption = operatorOptions.find(option => { + const selectedOperatorOption = operatorOptions.find((option) => { return model.operator === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.js b/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.js index 63af98db57e8b..eae354f7cc8ec 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/color_rules.test.js @@ -49,10 +49,7 @@ describe('src/legacy/core_plugins/metrics/public/components/color_rules.test.js' onChange: jest.fn(), }; const wrapper = mountWithIntl(); - const isNode = wrapper - .find('div') - .children() - .exists(); + const isNode = wrapper.find('div').children().exists(); expect(isNode).toBeFalsy(); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/custom_color_picker.js b/src/plugins/vis_type_timeseries/public/application/components/custom_color_picker.js index 835628368efab..bb10c9f495f56 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/custom_color_picker.js +++ b/src/plugins/vis_type_timeseries/public/application/components/custom_color_picker.js @@ -61,7 +61,7 @@ class CustomColorPickerUI extends PureComponent { }, }; - const handleSwatchChange = data => { + const handleSwatchChange = (data) => { if (data.hex) { color.isValidHex(data.hex) && this.props.onChange({ @@ -73,7 +73,7 @@ class CustomColorPickerUI extends PureComponent { } }; - const swatches = this.props.colors.map(c => { + const swatches = this.props.colors.map((c) => { return ; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/data_format_picker.js b/src/plugins/vis_type_timeseries/public/application/components/data_format_picker.js index 8e250bbd45a22..dca82cdc0b6b6 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/data_format_picker.js +++ b/src/plugins/vis_type_timeseries/public/application/components/data_format_picker.js @@ -58,7 +58,7 @@ class DataFormatPickerUI extends Component { this.props.onChange([{ value: (this.custom && this.custom.value) || '' }]); }; - handleChange = selectedOptions => { + handleChange = (selectedOptions) => { if (selectedOptions.length < 1) { return; } @@ -78,7 +78,7 @@ class DataFormatPickerUI extends Component { }; handleDurationChange(name) { - return selectedOptions => { + return (selectedOptions) => { if (selectedOptions.length < 1) { return; } @@ -154,15 +154,15 @@ class DataFormatPickerUI extends Component { value: 'custom', }, ]; - const selectedOption = options.find(option => { + const selectedOption = options.find((option) => { return defaultValue === option.value; }); let custom; if (defaultValue === 'duration') { const [from, to, decimals] = value.split(','); - const selectedFrom = durationInputOptions.find(option => from === option.value); - const selectedTo = durationOutputOptions.find(option => to === option.value); + const selectedFrom = durationInputOptions.find((option) => from === option.value); + const selectedTo = durationOutputOptions.find((option) => to === option.value); return ( @@ -229,7 +229,7 @@ class DataFormatPickerUI extends Component { > (this.decimals = el)} + inputRef={(el) => (this.decimals = el)} placeholder={DEFAULT_OUTPUT_PRECISION} onChange={this.handleDurationChange('decimals')} /> @@ -267,7 +267,7 @@ class DataFormatPickerUI extends Component { > (this.custom = el)} + inputRef={(el) => (this.custom = el)} onChange={this.handleCustomChange} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/icon_select/icon_select.js b/src/plugins/vis_type_timeseries/public/application/components/icon_select/icon_select.js index 44077b8ffbdd1..eb2f115f25bbf 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/icon_select/icon_select.js +++ b/src/plugins/vis_type_timeseries/public/application/components/icon_select/icon_select.js @@ -108,7 +108,7 @@ export function IconView({ value: icon, label }) { } export function IconSelect({ value, onChange }) { - const selectedIcon = ICONS.find(option => value === option.value) || ICONS[0]; + const selectedIcon = ICONS.find((option) => value === option.value) || ICONS[0]; return ( { +const validateIntervalValue = (intervalValue) => { const isAutoOrGteInterval = isGteInterval(intervalValue) || isAutoInterval(intervalValue); if (isAutoOrGteInterval) { diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/calculate_siblings.js b/src/plugins/vis_type_timeseries/public/application/components/lib/calculate_siblings.js index 0cbe4e039322a..d813a3536f9d8 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/calculate_siblings.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/calculate_siblings.js @@ -21,7 +21,7 @@ import _ from 'lodash'; function getAncestors(siblings, item) { const ancestors = (item.id && [item.id]) || []; - siblings.forEach(sib => { + siblings.forEach((sib) => { if (_.includes(ancestors, sib.field)) { ancestors.push(sib.id); } @@ -31,5 +31,5 @@ function getAncestors(siblings, item) { export const calculateSiblings = (siblings, model) => { const ancestors = getAncestors(siblings, model); - return siblings.filter(row => !_.includes(ancestors, row.id)); + return siblings.filter((row) => !_.includes(ancestors, row.id)); }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/charts.js b/src/plugins/vis_type_timeseries/public/application/components/lib/charts.js index ab57e8bd8cf96..2495026304be8 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/charts.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/charts.js @@ -19,4 +19,4 @@ import { uniq, map, size, flow } from 'lodash'; -export const areFieldsDifferent = name => series => flow(uniq, size)(map(series, name)) > 1; +export const areFieldsDifferent = (name) => (series) => flow(uniq, size)(map(series, name)) > 1; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.js b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.js index 3eae18111bb4d..43e4734a9ed07 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/collection_actions.js @@ -25,7 +25,7 @@ export function handleChange(props, doc) { const { model, name } = props; const collection = model[name] || []; const part = {}; - part[name] = collection.map(row => { + part[name] = collection.map((row) => { if (row.id === doc.id) return doc; return row; }); @@ -36,7 +36,7 @@ export function handleDelete(props, doc) { const { model, name } = props; const collection = model[name] || []; const part = {}; - part[name] = collection.filter(row => row.id !== doc.id); + part[name] = collection.filter((row) => row.id !== doc.id); props.onChange?.({ ...model, ...part }); } diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js index 73fc8dac2b564..4d48095898b80 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js @@ -24,12 +24,12 @@ import moment from 'moment'; export const convertSeriesToVars = (series, model, dateFormat = 'lll', getConfig = null) => { const variables = {}; - model.series.forEach(seriesModel => { + model.series.forEach((seriesModel) => { series - .filter(row => _.startsWith(row.id, seriesModel.id)) - .forEach(row => { + .filter((row) => _.startsWith(row.id, seriesModel.id)) + .forEach((row) => { const varName = [_.snakeCase(row.label), _.snakeCase(seriesModel.var_name)] - .filter(v => v) + .filter((v) => v) .join('.'); const formatter = createTickFormatter( @@ -46,7 +46,7 @@ export const convertSeriesToVars = (series, model, dateFormat = 'lll', getConfig }, data: { raw: row.data, - formatted: row.data.map(point => { + formatted: row.data.map((point) => { return [moment(point[0]).format(dateFormat), formatter(point[1])]; }), }, diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_change_handler.js b/src/plugins/vis_type_timeseries/public/application/components/lib/create_change_handler.js index f7d4454e0e528..beee459c65458 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_change_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_change_handler.js @@ -19,7 +19,7 @@ import _ from 'lodash'; -export const createChangeHandler = (handleChange, model) => part => { +export const createChangeHandler = (handleChange, model) => (part) => { const doc = _.assign({}, model, part); handleChange(doc); }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.js b/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.js index 3bc8fd87f73dd..961f5e95a9f10 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_number_handler.js @@ -20,8 +20,8 @@ import _ from 'lodash'; import { detectIE } from './detect_ie'; -export const createNumberHandler = handleChange => { - return (name, defaultValue) => e => { +export const createNumberHandler = (handleChange) => { + return (name, defaultValue) => (e) => { if (!detectIE() || e.keyCode === 13) e.preventDefault(); const value = Number(_.get(e, 'target.value', defaultValue)); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.js b/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.js index cfc6a4dc57871..ff6c2cc0767f5 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_select_handler.js @@ -19,8 +19,8 @@ import _ from 'lodash'; -export const createSelectHandler = handleChange => { - return name => selectedOptions => { +export const createSelectHandler = (handleChange) => { + return (name) => (selectedOptions) => { return handleChange?.({ [name]: _.get(selectedOptions, '[0].value', null), }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.js b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.js index 82cc071b59d51..1dd5e02d74980 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_text_handler.js @@ -20,8 +20,8 @@ import _ from 'lodash'; import { detectIE } from './detect_ie'; -export const createTextHandler = handleChange => { - return (name, defaultValue) => e => { +export const createTextHandler = (handleChange) => { + return (name, defaultValue) => (e) => { // IE preventDefault breaks input, but we still need top prevent enter from being pressed if (!detectIE() || e.keyCode === 13) e.preventDefault(); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/create_xaxis_formatter.js b/src/plugins/vis_type_timeseries/public/application/components/lib/create_xaxis_formatter.js index 993cd9201336b..fdfb465ae3ffa 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/create_xaxis_formatter.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/create_xaxis_formatter.js @@ -29,7 +29,7 @@ export function getFormat(interval, rules, dateFormat) { } export function createXaxisFormatter(interval, rules, dateFormat) { - return val => { + return (val) => { return moment(val).format(getFormat(interval, rules, dateFormat)); }; } diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/durations.js b/src/plugins/vis_type_timeseries/public/application/components/lib/durations.js index 3d481f95986db..59f067a5e4dc3 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/durations.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/durations.js @@ -128,7 +128,7 @@ export const outputFormats = { Y: 'asYears', }; -export const isDuration = format => { +export const isDuration = (format) => { const splittedFormat = format.split(','); const [input, output] = splittedFormat; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/get_interval.js b/src/plugins/vis_type_timeseries/public/application/components/lib/get_interval.js index f6ea90a3891d8..86361afca3b12 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/get_interval.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/get_interval.js @@ -52,10 +52,10 @@ export const convertIntervalIntoUnit = (interval, hasTranslateUnitString = true) } }; -export const isGteInterval = interval => GTE_INTERVAL_RE.test(interval); -export const isAutoInterval = interval => !interval || interval === AUTO_INTERVAL; +export const isGteInterval = (interval) => GTE_INTERVAL_RE.test(interval); +export const isAutoInterval = (interval) => !interval || interval === AUTO_INTERVAL; -export const validateReInterval = intervalValue => { +export const validateReInterval = (intervalValue) => { const validationResult = {}; try { diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/re_id_series.js b/src/plugins/vis_type_timeseries/public/application/components/lib/re_id_series.js index a53ad24e83394..2c961b00b5ef9 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/re_id_series.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/re_id_series.js @@ -20,21 +20,21 @@ import uuid from 'uuid'; import _ from 'lodash'; -export const reIdSeries = source => { +export const reIdSeries = (source) => { const series = _.cloneDeep(source); series.id = uuid.v1(); - series.metrics.forEach(metric => { + series.metrics.forEach((metric) => { const id = uuid.v1(); const metricId = metric.id; metric.id = id; if (series.terms_order_by === metricId) series.terms_order_by = id; - series.metrics.filter(r => r.field === metricId).forEach(r => (r.field = id)); + series.metrics.filter((r) => r.field === metricId).forEach((r) => (r.field = id)); series.metrics - .filter(r => r.type === 'calculation' && r.variables.some(v => v.field === metricId)) - .forEach(r => { + .filter((r) => r.type === 'calculation' && r.variables.some((v) => v.field === metricId)) + .forEach((r) => { r.variables - .filter(v => v.field === metricId) - .forEach(v => { + .filter((v) => v.field === metricId) + .forEach((v) => { v.id = uuid.v1(); v.field = id; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/series_change_handler.js b/src/plugins/vis_type_timeseries/public/application/components/lib/series_change_handler.js index e773782969d16..beb691f4b7117 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/series_change_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/series_change_handler.js @@ -22,7 +22,7 @@ import { newMetricAggFn } from './new_metric_agg_fn'; import { isBasicAgg } from '../../../../../../plugins/vis_type_timeseries/common/agg_lookup'; import { handleAdd, handleChange } from './collection_actions'; -export const seriesChangeHandler = (props, items) => doc => { +export const seriesChangeHandler = (props, items) => (doc) => { // If we only have one sibling and the user changes to a pipeline // agg we are going to add the pipeline instead of changing the // current item. diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/stacked.js b/src/plugins/vis_type_timeseries/public/application/components/lib/stacked.js index f1cfcfbc05ba3..416caa7e0ec39 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/stacked.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/stacked.js @@ -17,4 +17,4 @@ * under the License. */ -export const isPercentDisabled = seriesQuantity => seriesQuantity < 2; +export const isPercentDisabled = (seriesQuantity) => seriesQuantity < 2; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.js b/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.js index fd316e66a16fb..e1f25fccf6369 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.js @@ -47,7 +47,7 @@ export const createTickFormatter = (format = '0,0.[00]', template, getConfig = n formatter = new FieldFormat({ pattern: format }, getConfig); } } - return val => { + return (val) => { let value; if (!isNumber(val)) { value = val; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.test.js b/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.test.js index ee10b254a9e15..71e82770bfa03 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/tick_formatter.test.js @@ -22,7 +22,7 @@ import { getFieldFormatsRegistry } from '../../../../../../test_utils/public/stu import { setFieldFormats } from '../../../services'; const mockUiSettings = { - get: item => { + get: (item) => { return mockUiSettings[item]; }, getUpdate$: () => ({ @@ -57,7 +57,7 @@ describe('createTickFormatter(format, template)', () => { const config = { 'format:percent:defaultPattern': '0.[00]%', }; - const fn = createTickFormatter('percent', null, key => config[key]); + const fn = createTickFormatter('percent', null, (key) => config[key]); expect(fn(0.5556)).toEqual('55.56%'); }); @@ -65,7 +65,7 @@ describe('createTickFormatter(format, template)', () => { const config = { 'format:bytes:defaultPattern': '0.0b', }; - const fn = createTickFormatter('bytes', null, key => config[key]); + const fn = createTickFormatter('bytes', null, (key) => config[key]); expect(fn(1500 ^ 10)).toEqual('1.5KB'); }); @@ -78,7 +78,7 @@ describe('createTickFormatter(format, template)', () => { const config = { 'format:number:defaultLocale': 'fr', }; - const fn = createTickFormatter('0,0.0', null, key => config[key]); + const fn = createTickFormatter('0,0.0', null, (key) => config[key]); expect(fn(1500)).toEqual('1 500,0'); }); @@ -101,7 +101,7 @@ describe('createTickFormatter(format, template)', () => { const config = { 'format:number:defaultPattern': '0,0.[00]', }; - const fn = createTickFormatter('number', '{{value', key => config[key]); + const fn = createTickFormatter('number', '{{value', (key) => config[key]); expect(fn(1.5556)).toEqual('1.56'); }); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/markdown_editor.js b/src/plugins/vis_type_timeseries/public/application/components/markdown_editor.js index 21fd9d530558c..1de58adc7e268 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/markdown_editor.js +++ b/src/plugins/vis_type_timeseries/public/application/components/markdown_editor.js @@ -34,11 +34,11 @@ import { EuiText, EuiCodeBlock, EuiSpacer, EuiTitle, EuiCodeEditor } from '@elas import { FormattedMessage } from '@kbn/i18n/react'; export class MarkdownEditor extends Component { - handleChange = value => { + handleChange = (value) => { this.props.onChange({ markdown: value }); }; - handleOnLoad = ace => { + handleOnLoad = (ace) => { this.ace = ace; }; @@ -60,7 +60,7 @@ export class MarkdownEditor extends Component { const rows = []; const rawFormatter = createTickFormatter('0.[0000]', null, this.props.getConfig); - const createPrimitiveRow = key => { + const createPrimitiveRow = (key) => { const snippet = `{{ ${key} }}`; let value = _.get(variables, key); if (/raw$/.test(key)) value = rawFormatter(value); @@ -76,7 +76,7 @@ export class MarkdownEditor extends Component { ); }; - const createArrayRow = key => { + const createArrayRow = (key) => { const snippet = `{{# ${key} }}{{/ ${key} }}`; const date = _.get(variables, `${key}[0][0]`); let value = _.get(variables, `${key}[0][1]`); diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config.js index 89e97627e8114..c950c39f06a66 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config.js @@ -38,8 +38,8 @@ const types = { markdown, }; -const checkModelValidity = validationResults => - Boolean(Object.values(validationResults).every(isValid => isValid)); +const checkModelValidity = (validationResults) => + Boolean(Object.values(validationResults).every((isValid) => isValid)); export function PanelConfig(props) { const { model } = props; diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.js index 19770519ef010..eda49ccdca178 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.js @@ -101,7 +101,7 @@ class GaugePanelConfigUi extends Component { }, ]; const htmlId = htmlIdGenerator(); - const selectedGaugeStyleOption = styleOptions.find(option => { + const selectedGaugeStyleOption = styleOptions.find((option) => { return model.gauge_style === option.value; }); let view; @@ -155,7 +155,7 @@ class GaugePanelConfigUi extends Component { language: model.filter.language || getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.js index 4509b669b0505..936cc000db8d9 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/gauge.test.js @@ -35,10 +35,7 @@ describe('GaugePanelConfig', () => { }; const wrapper = shallowWithIntl(); - wrapper - .find('EuiTab') - .first() - .simulate('onClick'); + wrapper.find('EuiTab').first().simulate('onClick'); expect(props.onChange).toBeCalled(); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/markdown.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/markdown.js index 4aa8856836fc6..03d84d67ea787 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/markdown.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/markdown.js @@ -105,14 +105,14 @@ class MarkdownPanelConfigUi extends Component { value: 'bottom', }, ]; - const selectedAlignOption = alignOptions.find(option => { + const selectedAlignOption = alignOptions.find((option) => { return model.markdown_vertical_align === option.value; }); let view; if (selectedTab === 'markdown') { view = ( - {visData => } + {(visData) => } ); } else if (selectedTab === 'data') { @@ -166,7 +166,7 @@ class MarkdownPanelConfigUi extends Component { : getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/metric.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/metric.js index d32500251a946..c25f7faffcd92 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/metric.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/metric.js @@ -120,7 +120,7 @@ export class MetricPanelConfig extends Component { language: model.filter.language || getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.js index 219fe42281d34..2b729e403898e 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/table.js @@ -64,10 +64,10 @@ export class TablePanelConfig extends Component { this.setState({ selectedTab }); } - handlePivotChange = selectedOption => { + handlePivotChange = (selectedOption) => { const { fields, model } = this.props; const pivotId = get(selectedOption, '[0].value', null); - const field = fields[model.index_pattern].find(field => field.name === pivotId); + const field = fields[model.index_pattern].find((field) => field.name === pivotId); const pivotType = get(field, 'type', model.pivot_type); this.props.onChange({ @@ -243,7 +243,7 @@ export class TablePanelConfig extends Component { : getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js index b534a261984ec..0b8b4be67b7a0 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/timeseries.js @@ -85,7 +85,7 @@ class TimeseriesPanelConfigUi extends Component { value: 'left', }, ]; - const selectedPositionOption = positionOptions.find(option => { + const selectedPositionOption = positionOptions.find((option) => { return model.axis_position === option.value; }); const scaleOptions = [ @@ -104,7 +104,7 @@ class TimeseriesPanelConfigUi extends Component { value: 'log', }, ]; - const selectedAxisScaleOption = scaleOptions.find(option => { + const selectedAxisScaleOption = scaleOptions.find((option) => { return model.axis_scale === option.value; }); const legendPositionOptions = [ @@ -130,7 +130,7 @@ class TimeseriesPanelConfigUi extends Component { value: 'bottom', }, ]; - const selectedLegendPosOption = legendPositionOptions.find(option => { + const selectedLegendPosOption = legendPositionOptions.find((option) => { return model.legend_position === option.value; }); @@ -192,7 +192,7 @@ class TimeseriesPanelConfigUi extends Component { language: model.filter.language || getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.js b/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.js index 7dbecb9e674b0..4752e0ee7de65 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.js +++ b/src/plugins/vis_type_timeseries/public/application/components/panel_config/top_n.js @@ -150,7 +150,7 @@ export class TopNPanelConfig extends Component { : getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[model.index_pattern || model.default_index_pattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/series.js b/src/plugins/vis_type_timeseries/public/application/components/series.js index 1dbbbc52ef3fb..565ddb53f2633 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/series.js +++ b/src/plugins/vis_type_timeseries/public/application/components/series.js @@ -45,11 +45,11 @@ export class Series extends Component { selectedTab: 'metrics', }; - switchTab = selectedTab => { + switchTab = (selectedTab) => { this.setState({ selectedTab }); }; - handleChange = part => { + handleChange = (part) => { if (this.props.onChange) { const { model } = this.props; const doc = assign({}, model, part); @@ -65,7 +65,7 @@ export class Series extends Component { }); }; - toggleVisible = e => { + toggleVisible = (e) => { e.preventDefault(); this.setState({ @@ -79,7 +79,7 @@ export class Series extends Component { return Boolean(Component) ? ( - {visData => { + {(visData) => { const series = get(visData, `${panel.id}.series`, []); const counter = {}; const seriesQuantity = series.reduce((acc, value) => { diff --git a/src/plugins/vis_type_timeseries/public/application/components/series_config.js b/src/plugins/vis_type_timeseries/public/application/components/series_config.js index 9e7cd6a14e053..c3e18ec202c0f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/series_config.js +++ b/src/plugins/vis_type_timeseries/public/application/components/series_config.js @@ -39,7 +39,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { getDefaultQueryLanguage } from './lib/get_default_query_language'; import { QueryBarWrapper } from './query_bar_wrapper'; -export const SeriesConfig = props => { +export const SeriesConfig = (props) => { const defaults = { offset_time: '', value_template: '' }; const model = { ...defaults, ...props.model }; const handleSelectChange = createSelectHandler(props.onChange); @@ -74,7 +74,7 @@ export const SeriesConfig = props => { : getDefaultQueryLanguage(), query: model.filter && model.filter.query ? model.filter.query : '', }} - onChange={filter => props.onChange({ filter })} + onChange={(filter) => props.onChange({ filter })} indexPatterns={[seriesIndexPattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/series_editor.js b/src/plugins/vis_type_timeseries/public/application/components/series_editor.js index 3d00993c531d7..7be10e42b9ca6 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/series_editor.js +++ b/src/plugins/vis_type_timeseries/public/application/components/series_editor.js @@ -30,7 +30,7 @@ import { reorder } from './lib/reorder'; const DROPPABLE_ID = 'series_editor_dnd'; export class SeriesEditor extends Component { - handleClone = series => { + handleClone = (series) => { const newSeries = reIdSeries(series); handleAdd.call(null, this.props, () => newSeries); @@ -90,7 +90,7 @@ export class SeriesEditor extends Component { draggableId={`${DROPPABLE_ID}:${row.id}`} disableInteractiveElementBlocking > - {provided => ( + {(provided) => ( handleAdd(this.props, newSeriesFn)} - onChange={doc => handleChange(this.props, doc)} + onChange={(doc) => handleChange(this.props, doc)} onClone={() => this.handleClone(row)} onDelete={() => handleDelete(this.props, row)} model={row} diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/everything.js b/src/plugins/vis_type_timeseries/public/application/components/splits/everything.js index 7140ec02d9950..600e913d3c325 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/everything.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/everything.js @@ -24,7 +24,7 @@ import React from 'react'; import { htmlIdGenerator, EuiFlexGroup, EuiFlexItem, EuiFormRow } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export const SplitByEverything = props => { +export const SplitByEverything = (props) => { const { onChange, model, uiRestrictions } = props; const htmlId = htmlIdGenerator(); const handleSelectChange = createSelectHandler(onChange); diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/filter.js b/src/plugins/vis_type_timeseries/public/application/components/splits/filter.js index 2bd41d8e3524d..047a81b65ac2b 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/filter.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/filter.js @@ -26,7 +26,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { getDefaultQueryLanguage } from '../lib/get_default_query_language'; import { QueryBarWrapper } from '../query_bar_wrapper'; -export const SplitByFilter = props => { +export const SplitByFilter = (props) => { const { onChange, uiRestrictions, indexPattern } = props; const defaults = { filter: { language: getDefaultQueryLanguage(), query: '' } }; const model = { ...defaults, ...props.model }; @@ -66,7 +66,7 @@ export const SplitByFilter = props => { language: model.filter.language || getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={filter => onChange({ filter })} + onChange={(filter) => onChange({ filter })} indexPatterns={[indexPattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/filter_items.js b/src/plugins/vis_type_timeseries/public/application/components/splits/filter_items.js index 1cf92d82adaf9..866c9f5ee2444 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/filter_items.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/filter_items.js @@ -35,7 +35,7 @@ class FilterItemsUi extends Component { } handleChange(item, name) { - return e => { + return (e) => { const handleChange = collectionActions.handleChange.bind(null, this.props); handleChange( _.assign({}, item, { @@ -52,7 +52,7 @@ class FilterItemsUi extends Component { const indexPatterns = this.props.indexPatterns; const defaults = { filter: '', label: '' }; const model = { ...defaults, ...row }; - const handleChange = part => { + const handleChange = (part) => { const fn = collectionActions.handleChange.bind(null, this.props); fn(_.assign({}, model, part)); }; @@ -82,7 +82,7 @@ class FilterItemsUi extends Component { language: model.filter.language || getDefaultQueryLanguage(), query: model.filter.query || '', }} - onChange={query => this.handleQueryChange(model, query)} + onChange={(query) => this.handleQueryChange(model, query)} indexPatterns={[indexPatterns]} />
diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/filters.js b/src/plugins/vis_type_timeseries/public/application/components/splits/filters.js index fc7d63af82a9b..0ee75be962b0f 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/filters.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/filters.js @@ -25,7 +25,7 @@ import React from 'react'; import { htmlIdGenerator, EuiFlexGroup, EuiFlexItem, EuiFormRow } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export const SplitByFilters = props => { +export const SplitByFilters = (props) => { const { onChange, model, uiRestrictions, indexPattern } = props; const htmlId = htmlIdGenerator(); const handleSelectChange = createSelectHandler(onChange); diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/group_by_select.js b/src/plugins/vis_type_timeseries/public/application/components/splits/group_by_select.js index 5f7704a7bcfbf..ad3a68deab9ad 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/group_by_select.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/group_by_select.js @@ -54,13 +54,13 @@ function GroupBySelectUi(props) { }), value: 'terms', }, - ].map(field => ({ + ].map((field) => ({ ...field, disabled: !isGroupByFieldsEnabled(field.value, uiRestrictions), })); const selectedValue = props.value || 'everything'; - const selectedOption = modeOptions.find(option => { + const selectedOption = modeOptions.find((option) => { return selectedValue === option.value; }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/terms.js b/src/plugins/vis_type_timeseries/public/application/components/splits/terms.js index 0fddc4f8c1d87..b71141f44f52d 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/terms.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/terms.js @@ -86,7 +86,7 @@ export const SplitByTermsUI = ({ }), }, ]; - const selectedDirectionOption = dirOptions.find(option => { + const selectedDirectionOption = dirOptions.find((option) => { return model.terms_direction === option.value; }); const selectedField = find(fields[indexPattern], ({ name }) => name === model.terms_field); diff --git a/src/plugins/vis_type_timeseries/public/application/components/splits/unsupported_split.js b/src/plugins/vis_type_timeseries/public/application/components/splits/unsupported_split.js index 378b160654635..da08469ba3daa 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/splits/unsupported_split.js +++ b/src/plugins/vis_type_timeseries/public/application/components/splits/unsupported_split.js @@ -32,7 +32,7 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; -export const SplitUnsupported = props => { +export const SplitUnsupported = (props) => { const { onChange, model, uiRestrictions } = props; const htmlId = htmlIdGenerator(); const handleSelectChange = createSelectHandler(onChange); diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_editor.js b/src/plugins/vis_type_timeseries/public/application/components/vis_editor.js index 62d8cf3297132..0c53ddd3f0ba8 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_editor.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_editor.js @@ -86,7 +86,7 @@ export class VisEditor extends Component { }); }, VIS_STATE_DEBOUNCE_DELAY); - isValidKueryQuery = filterQuery => { + isValidKueryQuery = (filterQuery) => { if (filterQuery && filterQuery.language === 'kuery') { try { const queryOptions = this.coreContext.uiSettings.get('query:allowLeadingWildcards'); @@ -98,7 +98,7 @@ export class VisEditor extends Component { return true; }; - handleChange = partialModel => { + handleChange = (partialModel) => { if (isEmpty(partialModel)) { return; } @@ -117,7 +117,7 @@ export class VisEditor extends Component { if (this.props.isEditorMode) { const extractedIndexPatterns = extractIndexPatterns(nextModel); if (!isEqual(this.state.extractedIndexPatterns, extractedIndexPatterns)) { - fetchFields(extractedIndexPatterns).then(visFields => + fetchFields(extractedIndexPatterns).then((visFields) => this.setState({ visFields, extractedIndexPatterns, @@ -137,7 +137,7 @@ export class VisEditor extends Component { this.setState({ dirty: false }); }; - handleAutoApplyToggle = event => { + handleAutoApplyToggle = (event) => { this.setState({ autoApply: event.target.checked }); }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js b/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js index fbd17d99be9bf..0ae1c86ae3117 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_editor_visualization.js @@ -55,9 +55,9 @@ class VisEditorVisualizationUI extends Component { this.setState({ dragging: false }); }; - handleMouseMove = event => { + handleMouseMove = (event) => { if (this.state.dragging) { - this.setState(prevState => ({ + this.setState((prevState) => ({ height: Math.max(MIN_CHART_HEIGHT, prevState.height + event.movementY), })); } @@ -74,7 +74,7 @@ class VisEditorVisualizationUI extends Component { this._handler = embeddableHandler; await this._handler.render(this._visEl.current); - this._subscription = this._handler.handler.data$.subscribe(data => { + this._subscription = this._handler.handler.data$.subscribe((data) => { this.setPanelInterval(data.value.visData); onDataChange(data.value); }); @@ -94,11 +94,11 @@ class VisEditorVisualizationUI extends Component { * We use 15px steps to do the scaling and make sure the chart has at least its * defined minimum width (MIN_CHART_HEIGHT). */ - onSizeHandleKeyDown = ev => { + onSizeHandleKeyDown = (ev) => { const { keyCode } = ev; if (keyCode === keyCodes.UP || keyCode === keyCodes.DOWN) { ev.preventDefault(); - this.setState(prevState => { + this.setState((prevState) => { const newHeight = prevState.height + (keyCode === keyCodes.UP ? -15 : 15); return { height: Math.max(MIN_CHART_HEIGHT, newHeight), diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_picker.js b/src/plugins/vis_type_timeseries/public/application/components/vis_picker.js index 2c4a11f8880ff..c33ed02eadebd 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_picker.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_picker.js @@ -46,8 +46,8 @@ VisPickerItem.propTypes = { selected: PropTypes.bool, }; -export const VisPicker = injectI18n(function(props) { - const handleChange = type => { +export const VisPicker = injectI18n(function (props) { + const handleChange = (type) => { props.onChange({ type }); }; @@ -89,7 +89,7 @@ export const VisPicker = injectI18n(function(props) { defaultMessage: 'Table', }), }, - ].map(item => { + ].map((item) => { return ( { it('should call toggleVisible function', () => { const wrapper = mountWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(0).simulate('click'); expect(defaultProps.toggleVisible).toBeCalled(); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/gauge/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/gauge/vis.js index 7d30a1f0c8df5..4c029f1c0d5b0 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/gauge/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/gauge/vis.js @@ -27,11 +27,11 @@ import { getLastValue } from '../../../../../../../plugins/vis_type_timeseries/c function getColors(props) { const { model, visData } = props; - const series = get(visData, `${model.id}.series`, []).filter(s => !isUndefined(s)); + const series = get(visData, `${model.id}.series`, []).filter((s) => !isUndefined(s)); let text; let gauge; if (model.gauge_color_rules) { - model.gauge_color_rules.forEach(rule => { + model.gauge_color_rules.forEach((rule) => { if (rule.operator && rule.value != null) { const value = (series[0] && getLastValue(series[0].data)) || 0; if (_[rule.operator](value, rule.value)) { @@ -49,9 +49,9 @@ function GaugeVisualization(props) { const colors = getColors(props); const series = get(visData, `${model.id}.series`, []) - .filter(row => row) + .filter((row) => row) .map((row, i) => { - const seriesDef = model.series.find(s => includes(row.id, s.id)); + const seriesDef = model.series.find((s) => includes(row.id, s.id)); const newProps = {}; if (seriesDef) { newProps.formatter = createTickFormatter( diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/markdown/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/markdown/vis.js index d8bcf56b48cb9..a4e7738e92318 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/markdown/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/markdown/vis.js @@ -28,7 +28,7 @@ import { replaceVars } from '../../lib/replace_vars'; import { convertSeriesToVars } from '../../lib/convert_series_to_vars'; import { isBackgroundInverted } from '../../../lib/set_is_reversed'; -const getMarkdownId = id => `markdown-${id}`; +const getMarkdownId = (id) => `markdown-${id}`; export function MarkdownVisualization(props) { const { backgroundColor, model, visData, dateFormat } = props; diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/series.test.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/series.test.js index 94a12266df3b3..cd4bca453d4d8 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/series.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/series.test.js @@ -48,19 +48,13 @@ describe('MetricSeries', () => { it('should call toggleVisible function', () => { const wrapper = mountWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(0).simulate('click'); expect(defaultProps.toggleVisible).toBeCalled(); }); it('should call onAdd function', () => { const wrapper = mountWithIntl(); - wrapper - .find('EuiButtonIcon') - .at(3) - .simulate('click'); + wrapper.find('EuiButtonIcon').at(3).simulate('click'); expect(defaultProps.onAdd).toBeCalled(); }); }); diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/vis.js index 4a907a7b2078d..f37971e990c96 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/metric/vis.js @@ -28,11 +28,11 @@ import { isBackgroundInverted } from '../../../lib/set_is_reversed'; function getColors(props) { const { model, visData } = props; - const series = get(visData, `${model.id}.series`, []).filter(s => !isUndefined(s)); + const series = get(visData, `${model.id}.series`, []).filter((s) => !isUndefined(s)); let color; let background; if (model.background_color_rules) { - model.background_color_rules.forEach(rule => { + model.background_color_rules.forEach((rule) => { if (rule.operator && rule.value != null) { const value = (series[0] && getLastValue(series[0].data)) || 0; if (_[rule.operator](value, rule.value)) { @@ -49,9 +49,9 @@ function MetricVisualization(props) { const { backgroundColor, model, visData } = props; const colors = getColors(props); const series = get(visData, `${model.id}.series`, []) - .filter(row => row) + .filter((row) => row) .map((row, i) => { - const seriesDef = model.series.find(s => includes(row.id, s.id)); + const seriesDef = model.series.find((s) => includes(row.id, s.id)); const newProps = {}; if (seriesDef) { newProps.formatter = createTickFormatter( diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/config.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/config.js index b395207d4e881..7637de260aa82 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/config.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/config.js @@ -126,7 +126,7 @@ class TableSeriesConfigUI extends Component { value: 'cumulative_sum', }, ]; - const selectedAggFuncOption = functionOptions.find(option => { + const selectedAggFuncOption = functionOptions.find((option) => { return model.aggregate_function === option.value; }); @@ -187,7 +187,7 @@ class TableSeriesConfigUI extends Component { : getDefaultQueryLanguage(), query: model.filter && model.filter.query ? model.filter.query : '', }} - onChange={filter => this.props.onChange({ filter })} + onChange={(filter) => this.props.onChange({ filter })} indexPatterns={[this.props.indexPatternForQuery]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/vis.js index c6f1db149928c..d55afeda62e70 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/table/vis.js @@ -34,7 +34,7 @@ import { METRIC_TYPES } from '../../../../../../../plugins/vis_type_timeseries/c function getColor(rules, colorKey, value) { let color; if (rules) { - rules.forEach(rule => { + rules.forEach((rule) => { if (rule.operator && rule.value != null) { if (_[rule.operator](value, rule.value)) { color = rule[colorKey]; @@ -56,10 +56,10 @@ export class TableVis extends Component { } get visibleSeries() { - return get(this.props, 'model.series', []).filter(series => !series.hidden); + return get(this.props, 'model.series', []).filter((series) => !series.hidden); } - renderRow = row => { + renderRow = (row) => { const { model } = this.props; let rowDisplay = model.pivot_type === 'date' ? this.dateFormatter.convert(row.key) : row.key; if (model.drilldown_url) { @@ -67,9 +67,9 @@ export class TableVis extends Component { rowDisplay = {rowDisplay}; } const columns = row.series - .filter(item => item) - .map(item => { - const column = this.visibleSeries.find(c => c.id === item.id); + .filter((item) => item) + .map((item) => { + const column = this.visibleSeries.find((c) => c.id === item.id); if (!column) return null; const formatter = createTickFormatter( column.formatter, @@ -128,7 +128,7 @@ export class TableVis extends Component { } }; - const columns = this.visibleSeries.map(item => { + const columns = this.visibleSeries.map((item) => { const metric = last(item.metrics); const label = calculateHeaderLabel(metric, item); diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/config.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/config.js index d29b795b10ec8..19938778d66e2 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/config.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/config.js @@ -44,7 +44,7 @@ import { QueryBarWrapper } from '../../query_bar_wrapper'; import { isPercentDisabled } from '../../lib/stacked'; import { STACKED_OPTIONS } from '../../../visualizations/constants/chart'; -export const TimeseriesConfig = injectI18n(function(props) { +export const TimeseriesConfig = injectI18n(function (props) { const handleSelectChange = createSelectHandler(props.onChange); const handleTextChange = createTextHandler(props.onChange); const defaults = { @@ -93,7 +93,7 @@ export const TimeseriesConfig = injectI18n(function(props) { disabled: isPercentDisabled(props.seriesQuantity[model.id]), }, ]; - const selectedStackedOption = stackedOptions.find(option => { + const selectedStackedOption = stackedOptions.find((option) => { return model.stacked === option.value; }); @@ -113,7 +113,7 @@ export const TimeseriesConfig = injectI18n(function(props) { value: 'left', }, ]; - const selectedAxisPosOption = positionOptions.find(option => { + const selectedAxisPosOption = positionOptions.find((option) => { return model.axis_position === option.value; }); @@ -133,7 +133,7 @@ export const TimeseriesConfig = injectI18n(function(props) { value: 'line', }, ]; - const selectedChartTypeOption = chartTypeOptions.find(option => { + const selectedChartTypeOption = chartTypeOptions.find((option) => { return model.chart_type === option.value; }); @@ -160,7 +160,7 @@ export const TimeseriesConfig = injectI18n(function(props) { value: 'gradient', }, ]; - const selectedSplitColorOption = splitColorOptions.find(option => { + const selectedSplitColorOption = splitColorOptions.find((option) => { return model.split_color_mode === option.value; }); @@ -410,7 +410,7 @@ export const TimeseriesConfig = injectI18n(function(props) { : getDefaultQueryLanguage(), query: model.filter && model.filter.query ? model.filter.query : '', }} - onChange={filter => props.onChange({ filter })} + onChange={(filter) => props.onChange({ filter })} indexPatterns={[seriesIndexPattern]} /> diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/series.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/series.js index 27a84d9ba40b9..06ad7e14bf358 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/series.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/series.js @@ -37,7 +37,7 @@ import { createTextHandler } from '../../lib/create_text_handler'; import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; import { PANEL_TYPES } from '../../../../../../../plugins/vis_type_timeseries/common/panel_types'; -const TimeseriesSeriesUI = injectI18n(function(props) { +const TimeseriesSeriesUI = injectI18n(function (props) { const { panel, fields, diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js index 1004f7ee96a54..b4c563f3c11fd 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js @@ -45,7 +45,7 @@ export class TimeseriesVisualization extends Component { getConfig: PropTypes.func, }; - xAxisFormatter = interval => val => { + xAxisFormatter = (interval) => (val) => { const { scaledDataFormat, dateFormat } = this.props.visData; if (!scaledDataFormat || !dateFormat) { @@ -57,13 +57,13 @@ export class TimeseriesVisualization extends Component { return formatter(val); }; - yAxisStackedByPercentFormatter = val => { + yAxisStackedByPercentFormatter = (val) => { const n = Number(val) * 100; return `${(Number.isNaN(n) ? 0 : n).toFixed(0)}%`; }; - applyDocTo = template => doc => { + applyDocTo = (template) => (doc) => { const vars = replaceVars(template, null, doc); if (vars instanceof Error) { @@ -75,7 +75,7 @@ export class TimeseriesVisualization extends Component { return vars; }; - static getYAxisDomain = model => { + static getYAxisDomain = (model) => { const axisMin = get(model, 'axis_min', '').toString(); const axisMax = get(model, 'axis_max', '').toString(); const fit = model.series @@ -100,7 +100,7 @@ export class TimeseriesVisualization extends Component { }); }; - static getAxisScaleType = model => + static getAxisScaleType = (model) => get(model, 'axis_scale') === 'log' ? ScaleType.Log : ScaleType.Linear; static getTickFormatter = (model, getConfig) => @@ -163,9 +163,9 @@ export class TimeseriesVisualization extends Component { const yAxisIdGenerator = htmlIdGenerator('yaxis'); const mainAxisGroupId = yAxisIdGenerator('main_group'); - const seriesModel = model.series.filter(s => !s.hidden).map(s => cloneDeep(s)); + const seriesModel = model.series.filter((s) => !s.hidden).map((s) => cloneDeep(s)); const enableHistogramMode = areFieldsDifferent('chart_type')(seriesModel); - const firstSeries = seriesModel.find(s => s.formatter && !s.separate_axis); + const firstSeries = seriesModel.find((s) => s.formatter && !s.separate_axis); const mainAxisScaleType = TimeseriesVisualization.getAxisScaleType(model); const mainAxisDomain = TimeseriesVisualization.getYAxisDomain(model); @@ -178,7 +178,7 @@ export class TimeseriesVisualization extends Component { this.showToastNotification = null; - seriesModel.forEach(seriesGroup => { + seriesModel.forEach((seriesGroup) => { const isStackedWithinSeries = seriesGroup.stacked === STACKED_OPTIONS.STACKED_WITHIN_SERIES; const hasSeparateAxis = Boolean(seriesGroup.separate_axis); const groupId = hasSeparateAxis || isStackedWithinSeries ? seriesGroup.id : mainAxisGroupId; @@ -203,8 +203,8 @@ export class TimeseriesVisualization extends Component { } series - .filter(r => startsWith(r.id, seriesGroup.id)) - .forEach(seriesDataRow => { + .filter((r) => startsWith(r.id, seriesGroup.id)) + .forEach((seriesDataRow) => { seriesDataRow.tickFormatter = seriesGroupTickFormatter; seriesDataRow.groupId = groupId; seriesDataRow.yScaleType = yScaleType; diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/series.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/series.js index 173048f210528..3f71955839963 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/series.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/series.js @@ -36,7 +36,7 @@ import { createTextHandler } from '../../lib/create_text_handler'; import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; import { Aggs } from '../../aggs/aggs'; -export const TopNSeries = injectI18n(function(props) { +export const TopNSeries = injectI18n(function (props) { const { panel, model, diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/vis.js index 2ebc60325a425..a4fe6f796bc0b 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/top_n/vis.js @@ -37,22 +37,22 @@ function sortByDirection(data, direction, fn) { function sortSeries(visData, model) { const series = get(visData, `${model.id}.series`, []); return model.series.reduce((acc, item) => { - const itemSeries = series.filter(s => { + const itemSeries = series.filter((s) => { const id = first(s.id.split(/:/)); return id === item.id; }); const direction = item.terms_direction || 'desc'; if (item.terms_order_by === '_key') return acc.concat(itemSeries); - return acc.concat(sortByDirection(itemSeries, direction, s => getLastValue(s.data))); + return acc.concat(sortByDirection(itemSeries, direction, (s) => getLastValue(s.data))); }, []); } export function TopNVisualization(props) { const { backgroundColor, model, visData } = props; - const series = sortSeries(visData, model).map(item => { + const series = sortSeries(visData, model).map((item) => { const id = first(item.id.split(/:/)); - const seriesConfig = model.series.find(s => s.id === id); + const seriesConfig = model.series.find((s) => s.id === id); if (seriesConfig) { const tickFormatter = createTickFormatter( seriesConfig.formatter, @@ -62,7 +62,7 @@ export function TopNVisualization(props) { const value = getLastValue(item.data); let color = item.color || seriesConfig.color; if (model.bar_color_rules) { - model.bar_color_rules.forEach(rule => { + model.bar_color_rules.forEach((rule) => { if (rule.operator && rule.value != null && rule.bar_color) { if (OPERATORS[rule.operator](value, rule.value)) { color = rule.bar_color; @@ -88,7 +88,7 @@ export function TopNVisualization(props) { }; if (model.drilldown_url) { - params.onClick = item => { + params.onClick = (item) => { window.location = replaceVars(model.drilldown_url, {}, { key: item.label }); }; } diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_with_splits.js b/src/plugins/vis_type_timeseries/public/application/components/vis_with_splits.js index e36910d9081b3..8b63d1b5043f5 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_with_splits.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_with_splits.js @@ -26,13 +26,13 @@ export function visWithSplits(WrappedComponent) { function SplitVisComponent(props) { const { model, visData } = props; if (!model || !visData || !visData[model.id]) return ; - if (visData[model.id].series.every(s => s.id.split(':').length === 1)) { + if (visData[model.id].series.every((s) => s.id.split(':').length === 1)) { return ; } const splitsVisData = visData[model.id].series.reduce((acc, series) => { const [seriesId, splitId] = series.id.split(':'); - const seriesModel = model.series.find(s => s.id === seriesId); + const seriesModel = model.series.find((s) => s.id === seriesId); if (!seriesModel || !splitId) return acc; const metric = last(seriesModel.metrics); const label = calculateLabel(metric, seriesModel.metrics); @@ -54,18 +54,18 @@ export function visWithSplits(WrappedComponent) { }, {}); const nonSplitSeries = first( - visData[model.id].series.filter(series => { - const seriesModel = model.series.find(s => s.id === series.id); + visData[model.id].series.filter((series) => { + const seriesModel = model.series.find((s) => s.id === series.id); if (!seriesModel) return false; return ['everything', 'filter'].includes(seriesModel.split_mode); }) ); const indexOfNonSplit = nonSplitSeries - ? findIndex(model.series, s => s.id === nonSplitSeries.id) + ? findIndex(model.series, (s) => s.id === nonSplitSeries.id) : null; - const rows = Object.keys(splitsVisData).map(key => { + const rows = Object.keys(splitsVisData).map((key) => { const splitData = splitsVisData[key]; const { series, label } = splitData; const newSeries = diff --git a/src/plugins/vis_type_timeseries/public/application/components/yes_no.js b/src/plugins/vis_type_timeseries/public/application/components/yes_no.js index 59c0366e3b980..7834de0b8fa06 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/yes_no.js +++ b/src/plugins/vis_type_timeseries/public/application/components/yes_no.js @@ -25,7 +25,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; export function YesNo(props) { const { name, value, disabled, 'data-test-subj': dataTestSubj } = props; - const handleChange = value => { + const handleChange = (value) => { const { name } = props; return () => { const parts = { [name]: value }; diff --git a/src/plugins/vis_type_timeseries/public/application/components/yes_no.test.js b/src/plugins/vis_type_timeseries/public/application/components/yes_no.test.js index 3e12f7ec0777a..39ae94b7489a2 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/yes_no.test.js +++ b/src/plugins/vis_type_timeseries/public/application/components/yes_no.test.js @@ -27,10 +27,7 @@ describe('YesNo', () => { it('call onChange={handleChange} on yes', () => { const handleChange = sinon.spy(); const wrapper = shallowWithIntl(); - wrapper - .find('EuiRadio') - .first() - .simulate('change'); + wrapper.find('EuiRadio').first().simulate('change'); expect(handleChange.calledOnce).to.equal(true); expect(handleChange.firstCall.args[0]).to.eql({ test: 1, @@ -40,10 +37,7 @@ describe('YesNo', () => { it('call onChange={handleChange} on no', () => { const handleChange = sinon.spy(); const wrapper = shallowWithIntl(); - wrapper - .find('EuiRadio') - .last() - .simulate('change'); + wrapper.find('EuiRadio').last().simulate('change'); expect(handleChange.calledOnce).to.equal(true); expect(handleChange.firstCall.args[0]).to.eql({ test: 0, diff --git a/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.js b/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.js index 0a7b10ff1aabb..452e85c6405fe 100644 --- a/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.js +++ b/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.js @@ -21,7 +21,7 @@ import moment from 'moment'; const TIME_MODE = 'absolute'; -export const createBrushHandler = timefilter => (from, to) => { +export const createBrushHandler = (timefilter) => (from, to) => { timefilter.setTime({ from: moment(from).toISOString(), to: moment(to).toISOString(), diff --git a/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.test.js b/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.test.js index 76d88b6b8dfb9..6ae01a384e7ca 100644 --- a/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.test.js +++ b/src/plugins/vis_type_timeseries/public/application/lib/create_brush_handler.test.js @@ -27,7 +27,7 @@ describe('brushHandler', () => { beforeEach(() => { mockTimefilter = { time: {}, - setTime: function(time) { + setTime: function (time) { this.time = time; }, }; diff --git a/src/plugins/vis_type_timeseries/public/application/lib/fetch_fields.js b/src/plugins/vis_type_timeseries/public/application/lib/fetch_fields.js index f986e300ac5a5..6dd56a58418c5 100644 --- a/src/plugins/vis_type_timeseries/public/application/lib/fetch_fields.js +++ b/src/plugins/vis_type_timeseries/public/application/lib/fetch_fields.js @@ -24,7 +24,7 @@ export async function fetchFields(indexPatterns = ['*']) { const patterns = Array.isArray(indexPatterns) ? indexPatterns : [indexPatterns]; try { const indexFields = await Promise.all( - patterns.map(pattern => { + patterns.map((pattern) => { return getCoreStart().http.get('/api/metrics/fields', { query: { index: pattern, diff --git a/src/plugins/vis_type_timeseries/public/application/lib/set_is_reversed.js b/src/plugins/vis_type_timeseries/public/application/lib/set_is_reversed.js index 070cf34c879d2..57d6e45ceb889 100644 --- a/src/plugins/vis_type_timeseries/public/application/lib/set_is_reversed.js +++ b/src/plugins/vis_type_timeseries/public/application/lib/set_is_reversed.js @@ -25,7 +25,7 @@ const isDarkTheme = () => getUISettings().get('theme:darkMode'); /** * Returns true if the color that is passed has low luminosity */ -const isColorDark = c => { +const isColorDark = (c) => { return color(c).luminosity() < 0.45; }; @@ -33,7 +33,7 @@ const isColorDark = c => { * Checks to see if the `currentTheme` is dark in luminosity. * Defaults to checking `theme:darkMode`. */ -export const isThemeDark = currentTheme => { +export const isThemeDark = (currentTheme) => { let themeIsDark = currentTheme || isDarkTheme(); // If passing a string, check the luminosity diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/lib/get_value_by.js b/src/plugins/vis_type_timeseries/public/application/visualizations/lib/get_value_by.js index e5453102bfbe3..e6a89ee2e621c 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/lib/get_value_by.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/lib/get_value_by.js @@ -22,6 +22,6 @@ import _ from 'lodash'; export const getValueBy = (fn, data) => { if (_.isNumber(data)) return data; if (!Array.isArray(data)) return 0; - const values = data.map(v => v[1]); + const values = data.map((v) => v[1]); return _[fn](values); }; diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge.js index b518665e5ece4..50a2042425438 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge.js @@ -77,7 +77,7 @@ export class Gauge extends Component { const formatter = (metric && (metric.tickFormatter || metric.formatter)) || this.props.tickFormatter || - (v => v); + ((v) => v); const title = (metric && metric.label) || ''; const styles = reactcss( { @@ -119,7 +119,7 @@ export class Gauge extends Component { metrics = (
(this.inner = el)} + ref={(el) => (this.inner = el)} style={styles.inner} >
@@ -135,7 +135,7 @@ export class Gauge extends Component { metrics = (
(this.inner = el)} + ref={(el) => (this.inner = el)} style={styles.inner} >
@@ -158,7 +158,7 @@ export class Gauge extends Component { return (
(this.resize = el)} + ref={(el) => (this.resize = el)} className={`tvbVisGauge__resize`} data-test-subj="tvbVisGaugeContainer" > diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge_vis.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge_vis.js index d66eddae253a1..7a0ef67ee24f6 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge_vis.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/gauge_vis.js @@ -150,8 +150,8 @@ export class GaugeVis extends Component { ); } return ( -
(this.resize = el)} style={styles.resize}> -
(this.inner = el)}> +
(this.resize = el)} style={styles.resize}> +
(this.inner = el)}> {svg}
diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/metric.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/metric.js index 5524e17d106e4..4c286f61720ac 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/metric.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/metric.js @@ -67,7 +67,7 @@ export class Metric extends Component { render() { const { metric, secondary } = this.props; const { scale, translateX, translateY } = this.state; - const primaryFormatter = (metric && (metric.tickFormatter || metric.formatter)) || (n => n); + const primaryFormatter = (metric && (metric.tickFormatter || metric.formatter)) || ((n) => n); const primaryValue = primaryFormatter(getLastValue((metric && metric.data) || 0)); const styles = reactcss( { @@ -99,7 +99,7 @@ export class Metric extends Component { let secondarySnippet; if (secondary) { - const secondaryFormatter = secondary.formatter || (n => n); + const secondaryFormatter = secondary.formatter || ((n) => n); const secondaryValue = secondaryFormatter(getLastValue(secondary.data)); if (secondary.color) styles.secondary_value.color = secondary.color; let secondaryLabel; @@ -133,8 +133,8 @@ export class Metric extends Component { return (
-
(this.resize = el)} className="tvbVisMetric__resize"> -
(this.inner = el)} className="tvbVisMetric__inner" style={styles.inner}> +
(this.resize = el)} className="tvbVisMetric__resize"> +
(this.inner = el)} className="tvbVisMetric__inner" style={styles.inner}>
{primaryLabel}
}), })); -const decorateFormatter = formatter => ({ value }) => formatter(value); +const decorateFormatter = (formatter) => ({ value }) => formatter(value); -const handleCursorUpdate = cursor => { +const handleCursorUpdate = (cursor) => { eventBus.trigger(ACTIVE_CURSOR, cursor); }; diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/utils/stack_format.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/utils/stack_format.js index 20c655c995a5e..711f1f7ac328e 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/utils/stack_format.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/timeseries/utils/stack_format.js @@ -19,7 +19,7 @@ import { STACK_ACCESSORS, STACKED_OPTIONS } from '../../../constants'; -export const getStackAccessors = stack => { +export const getStackAccessors = (stack) => { switch (stack) { case STACKED_OPTIONS.STACKED: case STACKED_OPTIONS.STACKED_WITHIN_SERIES: diff --git a/src/plugins/vis_type_timeseries/public/application/visualizations/views/top_n.js b/src/plugins/vis_type_timeseries/public/application/visualizations/views/top_n.js index 99e9cc0b1c218..b595979130d3a 100644 --- a/src/plugins/vis_type_timeseries/public/application/visualizations/views/top_n.js +++ b/src/plugins/vis_type_timeseries/public/application/visualizations/views/top_n.js @@ -102,7 +102,7 @@ export class TopN extends Component { }; renderRow({ min, max }) { - return item => { + return (item) => { const renderMode = TopN.getRenderMode(min, max); const key = `${item.id || item.label}`; const lastValue = getLastValue(item.data); @@ -183,8 +183,8 @@ export class TopN extends Component { } TopN.defaultProps = { - tickFormatter: n => n, - onClick: i => i, + tickFormatter: (n) => n, + onClick: (i) => i, direction: 'desc', }; diff --git a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts index 33b88c9385ecb..a120b8ed2b0d4 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts @@ -68,7 +68,7 @@ export async function getFields( return await framework.globalConfig$ .pipe( first(), - map(config => config.elasticsearch.shardTimeout.asMilliseconds()) + map((config) => config.elasticsearch.shardTimeout.asMilliseconds()) ) .toPromise(); }, @@ -84,8 +84,8 @@ export async function getFields( indexPatternString, capabilities )) as IndexPatternFieldDescriptor[]).filter( - field => field.aggregatable && !indexPatterns.isNestedField(field) + (field) => field.aggregatable && !indexPatterns.isNestedField(field) ); - return uniq(fields, field => field.name); + return uniq(fields, (field) => field.name); } diff --git a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts index aef831eaad430..8ad87c9ad7f9b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts @@ -91,13 +91,13 @@ export function getVisData( return await framework.globalConfig$ .pipe( first(), - map(config => config.elasticsearch.shardTimeout.asMilliseconds()) + map((config) => config.elasticsearch.shardTimeout.asMilliseconds()) ) .toPromise(); }, }; const promises = (reqFacade.payload as GetVisDataOptions).panels.map(getPanelData(reqFacade)); - return Promise.all(promises).then(res => { + return Promise.all(promises).then((res) => { return res.reduce((acc, data) => { return _.assign(acc as any, data); }, {}); diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js index 1e693ae287b27..02a710fef897f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js @@ -23,7 +23,7 @@ import { } from '../vis_data/helpers/unit_to_seconds'; import { RESTRICTIONS_KEYS } from '../../../common/ui_restrictions'; -const getTimezoneFromRequest = request => { +const getTimezoneFromRequest = (request) => { return request.payload.timerange.timezone; }; diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts index 4fd4ac251fa3e..a2146e493d4ed 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts @@ -61,9 +61,9 @@ export class AbstractSearchStrategy { callWithRequestFactory: (server: any, req: ReqFacade) => APICaller, SearchRequest: any ) { - this.getCallWithRequestInstance = req => callWithRequestFactory(server, req); + this.getCallWithRequestInstance = (req) => callWithRequestFactory(server, req); - this.getSearchRequest = req => { + this.getSearchRequest = (req) => { const callWithRequest = this.getCallWithRequestInstance(req); return new SearchRequest(req, callWithRequest); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_annotations.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_annotations.js index 8b8c31912f168..b015aaf0ef8db 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_annotations.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_annotations.js @@ -44,7 +44,7 @@ export async function getAnnotations({ const lastSeriesTimestamp = getLastSeriesTimestamp(series); const handleAnnotationResponseBy = handleAnnotationResponse(lastSeriesTimestamp); - const bodiesPromises = annotations.map(annotation => + const bodiesPromises = annotations.map((annotation) => getAnnotationRequestParams(req, panel, annotation, esQueryConfig, capabilities) ); const searches = (await Promise.all(bodiesPromises)).reduce( diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_panel_data.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_panel_data.js index eefb192e626f7..da4c723a55770 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_panel_data.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_panel_data.js @@ -21,7 +21,7 @@ import { getTableData } from './get_table_data'; import { getSeriesData } from './get_series_data'; export function getPanelData(req) { - return panel => { + return (panel) => { if (panel.type === 'table') { return getTableData(req, panel); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_series_data.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_series_data.js index 1efeccb4b5701..ee48816c6a8af 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/get_series_data.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/get_series_data.js @@ -36,7 +36,7 @@ export async function getSeriesData(req, panel) { }; try { - const bodiesPromises = getActiveSeries(panel).map(series => + const bodiesPromises = getActiveSeries(panel).map((series) => getSeriesRequestParams(req, panel, series, esQueryConfig, capabilities) ); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.js index ce18f5e96f8b3..0a842bc1c0470 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/handle_error_response.js @@ -17,7 +17,7 @@ * under the License. */ -export const handleErrorResponse = panel => error => { +export const handleErrorResponse = (panel) => (error) => { if (error.isBoom && error.status === 401) throw error; const result = {}; let errorResponse; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js index f5ca1f1ccdf1c..0e4d2ce2a926c 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js @@ -24,7 +24,7 @@ import { i18n } from '@kbn/i18n'; import { MODEL_SCRIPTS } from './moving_fn_scripts'; function checkMetric(metric, fields) { - fields.forEach(field => { + fields.forEach((field) => { if (!metric[field]) { throw new Error( i18n.translate('visTypeTimeseries.metricMissingErrorMessage', { @@ -76,7 +76,7 @@ export const bucketTransform = { }, }; }, - static: bucket => { + static: (bucket) => { checkMetric(bucket, ['value']); // Anything containing a decimal point or an exponent is considered decimal value const isDecimalValue = Boolean(bucket.value.match(/[.e]/i)); @@ -101,7 +101,7 @@ export const bucketTransform = { variance: extendStats, std_deviation: extendStats, - top_hit: bucket => { + top_hit: (bucket) => { checkMetric(bucket, ['type', 'field', 'size']); const body = { filter: { @@ -130,12 +130,12 @@ export const bucketTransform = { std_deviation_bucket: extendStatsBucket, variance_bucket: extendStatsBucket, - percentile: bucket => { + percentile: (bucket) => { checkMetric(bucket, ['type', 'field', 'percentiles']); - let percents = bucket.percentiles.map(p => (p.value ? Number(p.value) : 0)); - if (bucket.percentiles.some(p => p.mode === 'band')) { + let percents = bucket.percentiles.map((p) => (p.value ? Number(p.value) : 0)); + if (bucket.percentiles.some((p) => p.mode === 'band')) { percents = percents.concat( - bucket.percentiles.filter(p => p.percentile).map(p => p.percentile) + bucket.percentiles.filter((p) => p.percentile).map((p) => p.percentile) ); } const agg = { @@ -147,13 +147,13 @@ export const bucketTransform = { return agg; }, - percentile_rank: bucket => { + percentile_rank: (bucket) => { checkMetric(bucket, ['type', 'field', 'values']); return { percentile_ranks: { field: bucket.field, - values: (bucket.values || []).map(value => (isEmpty(value) ? 0 : value)), + values: (bucket.values || []).map((value) => (isEmpty(value) ? 0 : value)), }, }; }, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.test.js index db0e8fa3d6bb9..1f0b574933f8a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.test.js @@ -111,7 +111,7 @@ describe('src/legacy/core_plugins/metrics/server/lib/vis_data/helpers/bucket_tra }); describe('std metric', () => { - ['avg', 'max', 'min', 'sum', 'cardinality', 'value_count'].forEach(type => { + ['avg', 'max', 'min', 'sum', 'cardinality', 'value_count'].forEach((type) => { test(`returns ${type} agg`, () => { const metric = { id: 'test', type: type, field: 'cpu.pct' }; const fn = bucketTransform[type]; @@ -133,7 +133,7 @@ describe('src/legacy/core_plugins/metrics/server/lib/vis_data/helpers/bucket_tra }); describe('extended stats', () => { - ['std_deviation', 'variance', 'sum_of_squares'].forEach(type => { + ['std_deviation', 'variance', 'sum_of_squares'].forEach((type) => { test(`returns ${type} agg`, () => { const fn = bucketTransform[type]; const metric = { id: 'test', type: type, field: 'cpu.pct' }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_active_series.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_active_series.js index c4ac2083fcbc9..10b60df0aa35c 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_active_series.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_active_series.js @@ -16,8 +16,8 @@ * specific language governing permissions and limitations * under the License. */ -export const getActiveSeries = panel => { +export const getActiveSeries = (panel) => { const shouldNotApplyFilter = ['gauge', 'markdown'].includes(panel.type); - return (panel.series || []).filter(series => !series.hidden || shouldNotApplyFilter); + return (panel.series || []).filter((series) => !series.hidden || shouldNotApplyFilter); }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_agg_value.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_agg_value.js index 149b3278c5345..c9363f32b50aa 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_agg_value.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_agg_value.js @@ -26,8 +26,8 @@ const aggFns = { min, sum, noop, - concat: values => values.join(', '), - avg: values => sum(values) / values.length, + concat: (values) => values.join(', '), + avg: (values) => sum(values) / values.length, }; export const getAggValue = (row, metric) => { @@ -56,7 +56,7 @@ export const getAggValue = (row, metric) => { } const hits = get(row, [metric.id, 'docs', 'hits', 'hits'], []); - const values = hits.map(doc => get(doc, `_source.${metric.field}`)); + const values = hits.map((doc) => get(doc, `_source.${metric.field}`)); const aggWith = (metric.agg_with && aggFns[metric.agg_with]) || aggFns.noop; return aggWith(values); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js index 3ec5454fcee77..53f0b84b8ec3b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js @@ -61,7 +61,7 @@ const calculateBucketData = (timeInterval, capabilities) => { }; }; -const calculateBucketSizeForAutoInterval = req => { +const calculateBucketSizeForAutoInterval = (req) => { const duration = getTimerangeDuration(req); return calculateAuto.near(100, duration).asSeconds(); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.js index 03f4728d9bf00..6855f50f956f2 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_buckets_path.js @@ -24,7 +24,7 @@ import { METRIC_TYPES } from '../../../../common/metric_types'; const percentileTest = /\[[0-9\.]+\]$/; export const getBucketsPath = (id, metrics) => { - const metric = metrics.find(m => startsWith(id, m.id)); + const metric = metrics.find((m) => startsWith(id, m.id)); let bucketsPath = String(id); switch (metric.type) { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_default_decoration.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_default_decoration.js index b63eb5488a755..282f6b073dc16 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_default_decoration.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_default_decoration.js @@ -17,7 +17,7 @@ * under the License. */ -export const getDefaultDecoration = series => { +export const getDefaultDecoration = (series) => { const pointSize = series.point_size != null ? Number(series.point_size) : Number(series.line_width); const showPoints = series.chart_type === 'line' && pointSize !== 0; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_index_pattern.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_index_pattern.js index 285582226483b..f37f0da4bbe93 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_index_pattern.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_index_pattern.js @@ -37,10 +37,10 @@ export async function getIndexPatternObject(req, indexPatternString) { // getting the index pattern fields const indexPatterns = indexPatternObjects.saved_objects .filter( - obj => + (obj) => obj.attributes.title === indexPatternString || (defaultIndex && obj.id === defaultIndex) ) - .map(indexPattern => { + .map((indexPattern) => { const { title, fields, timeFieldName } = indexPattern.attributes; return { title, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.js index a683c0f65f6a8..113fca37de111 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_last_metric.js @@ -20,5 +20,5 @@ import _ from 'lodash'; export function getLastMetric(series) { - return _.last(series.metrics.filter(s => s.type !== 'series_agg')); + return _.last(series.metrics.filter((s) => s.type !== 'series_agg')); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_splits.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_splits.js index ee168d6216b8c..54139a7c27e3f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_splits.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_splits.js @@ -39,7 +39,7 @@ export function getSplits(resp, panel, series, meta) { if (Array.isArray(buckets)) { const size = buckets.length; const colors = getSplitColors(series.color, size, series.split_color_mode); - return buckets.map(bucket => { + return buckets.map((bucket) => { bucket.id = `${series.id}:${bucket.key}`; bucket.label = formatKey(bucket.key, series); bucket.color = panel.type === 'top_n' ? color.string() : colors.shift(); @@ -49,7 +49,7 @@ export function getSplits(resp, panel, series, meta) { } if (series.split_mode === 'filters' && _.isPlainObject(buckets)) { - return series.split_filters.map(filter => { + return series.split_filters.map((filter) => { const bucket = _.get(resp, `aggregations.${series.id}.buckets.${filter.id}`); bucket.id = `${series.id}:${filter.id}`; bucket.key = filter.id; @@ -67,8 +67,8 @@ export function getSplits(resp, panel, series, meta) { timeseries, }; series.metrics - .filter(m => /_bucket/.test(m.type)) - .forEach(m => { + .filter((m) => /_bucket/.test(m.type)) + .forEach((m) => { mergeObj[m.id] = _.get(resp, `aggregations.${series.id}.${m.id}`); }); return [ diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.js index 4141c76f02464..682befe9ab050 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange.js @@ -19,7 +19,7 @@ import moment from 'moment'; -export const getTimerange = req => { +export const getTimerange = (req) => { const { min, max } = req.payload.timerange; return { @@ -28,7 +28,7 @@ export const getTimerange = req => { }; }; -export const getTimerangeDuration = req => { +export const getTimerangeDuration = (req) => { const { from, to } = getTimerange(req); return moment.duration(to.valueOf() - from.valueOf(), 'ms'); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange_mode.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange_mode.js index 8a83116b032b4..27f4b5ab5bf02 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange_mode.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_timerange_mode.js @@ -31,7 +31,7 @@ const OVERRIDE_INDEX_PATTERN_KEY = 'override_index_pattern'; * @param series - specific series * @return {boolean} */ -const hasOverriddenIndexPattern = series => Boolean(series[OVERRIDE_INDEX_PATTERN_KEY]); +const hasOverriddenIndexPattern = (series) => Boolean(series[OVERRIDE_INDEX_PATTERN_KEY]); /** * Get value of Time Range Mode for panel @@ -39,7 +39,7 @@ const hasOverriddenIndexPattern = series => Boolean(series[OVERRIDE_INDEX_PATTER * @param panel - panel configuration * @return {string} - value of TIME_RANGE_DATA_MODES type */ -const getPanelTimeRangeMode = panel => panel[TIME_RANGE_MODE_KEY]; +const getPanelTimeRangeMode = (panel) => panel[TIME_RANGE_MODE_KEY]; /** * Get value of Time Range Mode for series @@ -47,7 +47,7 @@ const getPanelTimeRangeMode = panel => panel[TIME_RANGE_MODE_KEY]; * @param series - specific series * @return {string} - value of TIME_RANGE_DATA_MODES type */ -const getSeriesTimeRangeMode = series => series[TIME_RANGE_MODE_KEY]; +const getSeriesTimeRangeMode = (series) => series[TIME_RANGE_MODE_KEY]; /** * Check if 'Entire Time Range' mode active or not. diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/map_bucket.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/map_bucket.js index 2ae116ad60847..72c759e9486f1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/map_bucket.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/map_bucket.js @@ -20,5 +20,5 @@ import { getAggValue } from './get_agg_value'; export function mapBucket(metric) { - return bucket => [bucket.key, getAggValue(bucket, metric)]; + return (bucket) => [bucket.key, getAggValue(bucket, metric)]; } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_interval.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_interval.js index c94ddbf13c1a8..00cef3b0eaced 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_interval.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_interval.js @@ -25,9 +25,7 @@ import dateMath from '@elastic/datemath'; const INTERVAL_STRING_RE = new RegExp('^([0-9\\.]*)\\s*(' + dateMath.units.join('|') + ')$'); export function parseInterval(interval) { - const matches = String(interval) - .trim() - .match(INTERVAL_STRING_RE); + const matches = String(interval).trim().match(INTERVAL_STRING_RE); if (!matches) return null; @@ -44,7 +42,7 @@ export function parseInterval(interval) { // adding 0.5 days until we hit the end date. However, since there is a bug in moment, when you add 0.5 days to // the start date, you get the same exact date (instead of being ahead by 12 hours). So instead of returning // a duration corresponding to 0.5 hours, we return a duration corresponding to 12 hours. - const selectedUnit = _.find(dateMath.units, unit => { + const selectedUnit = _.find(dateMath.units, (unit) => { return Math.abs(duration.as(unit)) >= 1; }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_settings.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_settings.js index 4dc0d020bf6a8..c416a3e545c3a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_settings.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/parse_settings.js @@ -33,7 +33,7 @@ function castBasedOnKey(key, val) { } return val; } -export const parseSettings = settingsStr => { +export const parseSettings = (settingsStr) => { return settingsStr.split(/\s/).reduce((acc, value) => { const [key, val] = value.split(/=/); acc[key] = castBasedOnKey(key, val); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/timestamp.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/timestamp.js index b0eb880cc7427..533d4ef8d30cc 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/timestamp.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/timestamp.js @@ -41,7 +41,7 @@ import { last } from 'lodash'; export function getLastSeriesTimestamp(seriesGroup = []) { let lastTimestamp = null; - seriesGroup.forEach(series => { + seriesGroup.forEach((series) => { series.forEach(({ data }) => { const [dataLastTimestamp] = last(data); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js index 4dd67d60f2328..be8f1741627ba 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js @@ -32,9 +32,9 @@ const units = { y: 86400 * 7 * 4 * 12, // Leap year? }; -const sortedUnits = sortBy(Object.keys(units), key => units[key]); +const sortedUnits = sortBy(Object.keys(units), (key) => units[key]); -export const parseInterval = intervalString => { +export const parseInterval = (intervalString) => { let value; let unit; @@ -65,7 +65,7 @@ export const convertIntervalToUnit = (intervalString, newUnit) => { return { value, unit }; }; -export const getSuitableUnit = intervalInSeconds => +export const getSuitableUnit = (intervalInSeconds) => sortedUnits.find((key, index, array) => { const nextUnit = array[index + 1]; const isValidInput = isNumber(intervalInSeconds) && intervalInSeconds > 0; @@ -77,4 +77,4 @@ export const getSuitableUnit = intervalInSeconds => ); }); -export const getUnitValue = unit => units[unit]; +export const getUnitValue = (unit) => units[unit]; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/offset_time.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/offset_time.test.js index b9b73002bafb3..f722bc7360db9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/offset_time.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/offset_time.test.js @@ -49,18 +49,8 @@ describe('offsetTime(req, by)', () => { const { from, to } = offsetTime(req, '1h'); expect(moment.isMoment(from)).toBeTruthy(); expect(moment.isMoment(to)).toBeTruthy(); - expect( - moment - .utc('2017-01-01T00:00:00Z') - .subtract(1, 'h') - .isSame(from) - ).toBeTruthy(); - expect( - moment - .utc('2017-01-01T01:00:00Z') - .subtract(1, 'h') - .isSame(to) - ).toBeTruthy(); + expect(moment.utc('2017-01-01T00:00:00Z').subtract(1, 'h').isSame(from)).toBeTruthy(); + expect(moment.utc('2017-01-01T01:00:00Z').subtract(1, 'h').isSame(to)).toBeTruthy(); }); test('should return a moment object for to and from offset by -2 minute', () => { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/date_histogram.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/date_histogram.js index f7b5cc9131ac4..4b611e46f1588 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/date_histogram.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/date_histogram.js @@ -31,7 +31,7 @@ export function dateHistogram( indexPatternObject, capabilities ) { - return next => doc => { + return (next) => (doc) => { const timeField = annotation.time_field; const { bucketSize, intervalString } = getBucketSize(req, 'auto', capabilities); const { from, to } = getTimerange(req); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/query.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/query.js index a4817dac9bd18..127687bf11fe9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/query.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/query.js @@ -22,7 +22,7 @@ import { getTimerange } from '../../helpers/get_timerange'; import { esQuery } from '../../../../../../data/server'; export function query(req, panel, annotation, esQueryConfig, indexPattern, capabilities) { - return next => doc => { + return (next) => (doc) => { const timeField = annotation.time_field; const { bucketSize } = getBucketSize(req, 'auto', capabilities); const { from, to } = getTimerange(req); @@ -56,7 +56,7 @@ export function query(req, panel, annotation, esQueryConfig, indexPattern, capab if (annotation.fields) { const fields = annotation.fields.split(/[,\s]+/) || []; - fields.forEach(field => { + fields.forEach((field) => { doc.query.bool.must.push({ exists: { field } }); }); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/top_hits.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/top_hits.js index 4cc3fd094cc13..bdf2aac943b1b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/top_hits.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/annotations/top_hits.js @@ -20,7 +20,7 @@ import { overwrite } from '../../helpers'; export function topHits(req, panel, annotation) { - return next => doc => { + return (next) => (doc) => { const fields = (annotation.fields && annotation.fields.split(/[,\s]+/)) || []; const timeField = annotation.time_field; overwrite(doc, `aggs.${annotation.id}.aggs.hits.top_hits`, { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.js index cc6466145dcdf..f1e58b8e4af2a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.js @@ -26,7 +26,7 @@ import { search } from '../../../../../../../plugins/data/server'; const { dateHistogramInterval } = search.aggs; export function dateHistogram(req, panel, series, esQueryConfig, indexPatternObject, capabilities) { - return next => doc => { + return (next) => (doc) => { const { timeField, interval } = getIntervalAndTimefield(panel, series, indexPatternObject); const { bucketSize, intervalString } = getBucketSize(req, interval, capabilities); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.test.js index 7f309b44d13f4..45cad1195fc78 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/date_histogram.test.js @@ -59,7 +59,7 @@ describe('dateHistogram(req, panel, series)', () => { }); test('returns valid date histogram', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = dateHistogram(req, panel, series, config, indexPatternObject, capabilities)(next)( {} ); @@ -93,7 +93,7 @@ describe('dateHistogram(req, panel, series)', () => { test('returns valid date histogram (offset by 1h)', () => { series.offset_time = '1h'; - const next = doc => doc; + const next = (doc) => doc; const doc = dateHistogram(req, panel, series, config, indexPatternObject, capabilities)(next)( {} ); @@ -130,7 +130,7 @@ describe('dateHistogram(req, panel, series)', () => { series.series_index_pattern = '*'; series.series_time_field = 'timestamp'; series.series_interval = '20s'; - const next = doc => doc; + const next = (doc) => doc; const doc = dateHistogram(req, panel, series, config, indexPatternObject, capabilities)(next)( {} ); @@ -167,7 +167,7 @@ describe('dateHistogram(req, panel, series)', () => { panel.time_range_mode = 'entire_time_range'; panel.type = 'timeseries'; - const next = doc => doc; + const next = (doc) => doc; const doc = dateHistogram(req, panel, series, config, indexPatternObject, capabilities)(next)( {} ); @@ -179,7 +179,7 @@ describe('dateHistogram(req, panel, series)', () => { test('should returns valid date histogram for entire range mode', () => { panel.time_range_mode = 'entire_time_range'; - const next = doc => doc; + const next = (doc) => doc; const doc = dateHistogram(req, panel, series, config, indexPatternObject, capabilities)(next)( {} ); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.js index 0ca562c49b4c7..0706ab6be96ea 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.js @@ -17,14 +17,14 @@ * under the License. */ -const filter = metric => metric.type === 'filter_ratio'; +const filter = (metric) => metric.type === 'filter_ratio'; import { bucketTransform } from '../../helpers/bucket_transform'; import { overwrite } from '../../helpers'; export function ratios(req, panel, series) { - return next => doc => { + return (next) => (doc) => { if (series.metrics.some(filter)) { - series.metrics.filter(filter).forEach(metric => { + series.metrics.filter(filter).forEach((metric) => { overwrite(doc, `aggs.${series.id}.aggs.timeseries.aggs.${metric.id}-numerator.filter`, { query_string: { query: metric.numerator || '*', analyze_wildcard: true }, }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js index f3d25a8e44ba7..e15f045989839 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/filter_ratios.test.js @@ -60,7 +60,7 @@ describe('ratios(req, panel, series)', () => { }); test('returns filter ratio aggs', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = ratios(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -119,7 +119,7 @@ describe('ratios(req, panel, series)', () => { test('returns empty object when field is not set', () => { delete series.metrics[0].field; - const next = doc => doc; + const next = (doc) => doc; const doc = ratios(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.js index d390821f9ad98..800145dac5468 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.js @@ -22,12 +22,12 @@ import { bucketTransform } from '../../helpers/bucket_transform'; import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; export function metricBuckets(req, panel, series, esQueryConfig, indexPatternObject, capabilities) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, series, indexPatternObject); const { intervalString } = getBucketSize(req, interval, capabilities); series.metrics - .filter(row => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) - .forEach(metric => { + .filter((row) => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) + .forEach((metric) => { const fn = bucketTransform[metric.type]; if (fn) { try { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js index eaf8ee1549f0b..1ac4329b60f82 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/metric_buckets.test.js @@ -68,7 +68,7 @@ describe('metricBuckets(req, panel, series)', () => { }); test('returns metric aggs', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = metricBuckets(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.js index f76f3a531a37d..d07d343d1b1eb 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.js @@ -46,7 +46,7 @@ function removeEmptyTopLevelAggregation(doc, series) { * as the last place where you can modify the "doc" (request body) object before sending it to ES. */ export function normalizeQuery(req, panel, series) { - return next => doc => { + return (next) => (doc) => { return next(removeEmptyTopLevelAggregation(doc, series)); }; } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.test.js index 3c837a212ce92..169e1827792c1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/normalize_query.test.js @@ -65,7 +65,7 @@ describe('normalizeQuery', () => { }); beforeEach(() => { - next = jest.fn(x => x); + next = jest.fn((x) => x); panel = {}; series = { id: seriesId, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.js index 45db28fa98f5e..4a79ec2295877 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.js @@ -22,9 +22,9 @@ import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; import { bucketTransform } from '../../helpers/bucket_transform'; import { overwrite } from '../../helpers'; -export const filter = metric => metric.type === 'positive_rate'; +export const filter = (metric) => metric.type === 'positive_rate'; -export const createPositiveRate = (doc, intervalString, aggRoot) => metric => { +export const createPositiveRate = (doc, intervalString, aggRoot) => (metric) => { const maxFn = bucketTransform.max; const derivativeFn = bucketTransform.derivative; const positiveOnlyFn = bucketTransform.positive_only; @@ -58,7 +58,7 @@ export const createPositiveRate = (doc, intervalString, aggRoot) => metric => { }; export function positiveRate(req, panel, series, esQueryConfig, indexPatternObject, capabilities) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, series, indexPatternObject); const { intervalString } = getBucketSize(req, interval, capabilities); if (series.metrics.some(filter)) { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.test.js index 946884c05c722..7c0f43adf02f5 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/positive_rate.test.js @@ -57,7 +57,7 @@ describe('positiveRate(req, panel, series)', () => { }); test('returns positive rate aggs', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = positiveRate(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.js index e5b81912f286e..906b3e71c7cb9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.js @@ -22,7 +22,7 @@ import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; import { esQuery } from '../../../../../../data/server'; export function query(req, panel, series, esQueryConfig, indexPatternObject) { - return next => doc => { + return (next) => (doc) => { const { timeField } = getIntervalAndTimefield(panel, series, indexPatternObject); const { from, to } = offsetTime(req, series.offset_time); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.test.js index 06da636f818d5..daf89b08fab4b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/query.test.js @@ -52,7 +52,7 @@ describe('query(req, panel, series)', () => { }); test('returns doc with query for timerange', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, @@ -79,7 +79,7 @@ describe('query(req, panel, series)', () => { test('returns doc with query for timerange (offset by 1h)', () => { series.offset_time = '1h'; - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, @@ -118,7 +118,7 @@ describe('query(req, panel, series)', () => { }, }, ]; - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, @@ -157,7 +157,7 @@ describe('query(req, panel, series)', () => { test('returns doc with series filter', () => { series.filter = { query: 'host:web-server', language: 'lucene' }; - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, @@ -211,7 +211,7 @@ describe('query(req, panel, series)', () => { }, ]; panel.filter = { query: 'host:web-server', language: 'lucene' }; - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, @@ -279,7 +279,7 @@ describe('query(req, panel, series)', () => { ]; panel.filter = { query: 'host:web-server', language: 'lucene' }; panel.ignore_global_filter = true; - const next = doc => doc; + const next = (doc) => doc; const doc = query(req, panel, series, config)(next)({}); expect(doc).toEqual({ size: 0, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.js index d677b2564c940..f2b58822e68b6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.js @@ -30,12 +30,12 @@ export function siblingBuckets( indexPatternObject, capabilities ) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, series, indexPatternObject); const { bucketSize } = getBucketSize(req, interval, capabilities); series.metrics - .filter(row => /_bucket$/.test(row.type)) - .forEach(metric => { + .filter((row) => /_bucket$/.test(row.type)) + .forEach((metric) => { const fn = bucketTransform[metric.type]; if (fn) { try { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js index 8e1c9b0f9ecd9..8f84023ce0c75 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/sibling_buckets.test.js @@ -62,7 +62,7 @@ describe('siblingBuckets(req, panel, series)', () => { }); test('returns sibling aggs', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = siblingBuckets(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.js index c567e8ded0e61..a538cb4d8df73 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.js @@ -20,7 +20,7 @@ import { overwrite } from '../../helpers'; export function splitByEverything(req, panel, series) { - return next => doc => { + return (next) => (doc) => { if ( series.split_mode === 'everything' || (series.split_mode === 'terms' && !series.terms_field) diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js index 5c2468f6b7c35..2ec51e0067eb7 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_everything.test.js @@ -43,7 +43,7 @@ describe('splitByEverything(req, panel, series)', () => { }); it('returns a valid filter with match_all', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = splitByEverything(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -59,7 +59,7 @@ describe('splitByEverything(req, panel, series)', () => { it('calls next and does not add a filter', () => { series.split_mode = 'terms'; series.terms_field = 'host'; - const next = jest.fn(doc => doc); + const next = jest.fn((doc) => doc); const doc = splitByEverything(req, panel, series)(next)({}); expect(next.mock.calls.length).toEqual(1); expect(doc).toEqual({}); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.js index 0822878aa9178..c1d86622ce6cc 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.js @@ -21,7 +21,7 @@ import { overwrite } from '../../helpers'; import { esQuery } from '../../../../../../data/server'; export function splitByFilter(req, panel, series, esQueryConfig, indexPattern) { - return next => doc => { + return (next) => (doc) => { if (series.split_mode !== 'filter') { return next(doc); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js index 75ca782a6d7e7..2458635a75dbe 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filter.test.js @@ -47,7 +47,7 @@ describe('splitByFilter(req, panel, series)', () => { }); test('returns a valid filter with a query_string', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = splitByFilter(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -73,7 +73,7 @@ describe('splitByFilter(req, panel, series)', () => { test('calls next and does not add a filter', () => { series.split_mode = 'terms'; - const next = jest.fn(doc => doc); + const next = jest.fn((doc) => doc); const doc = splitByFilter(req, panel, series)(next)({}); expect(next.mock.calls.length).toEqual(1); expect(doc).toEqual({}); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.js index a3d2725ef58b5..6950ef9ffb9e6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.js @@ -21,9 +21,9 @@ import { overwrite } from '../../helpers'; import { esQuery } from '../../../../../../data/server'; export function splitByFilters(req, panel, series, esQueryConfig, indexPattern) { - return next => doc => { + return (next) => (doc) => { if (series.split_mode === 'filters' && series.split_filters) { - series.split_filters.forEach(filter => { + series.split_filters.forEach((filter) => { const builtEsQuery = esQuery.buildEsQuery(indexPattern, [filter.filter], [], esQueryConfig); overwrite(doc, `aggs.${series.id}.filters.filters.${filter.id}`, builtEsQuery); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js index 6108b2bf2cf2b..90eb5179ec40f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_filters.test.js @@ -63,7 +63,7 @@ describe('splitByFilters(req, panel, series)', () => { }); test('returns a valid terms agg', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = splitByFilters(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -107,7 +107,7 @@ describe('splitByFilters(req, panel, series)', () => { test('calls next and does not add a terms agg', () => { series.split_mode = 'everything'; - const next = jest.fn(doc => doc); + const next = jest.fn((doc) => doc); const doc = splitByFilters(req, panel, series)(next)({}); expect(next.mock.calls.length).toEqual(1); expect(doc).toEqual({}); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.js index db5a3f50f2e62..240a5d76b7c6a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.js @@ -23,10 +23,10 @@ import { getBucketsPath } from '../../helpers/get_buckets_path'; import { bucketTransform } from '../../helpers/bucket_transform'; export function splitByTerms(req, panel, series) { - return next => doc => { + return (next) => (doc) => { if (series.split_mode === 'terms' && series.terms_field) { const direction = series.terms_direction || 'desc'; - const metric = series.metrics.find(item => item.id === series.terms_order_by); + const metric = series.metrics.find((item) => item.id === series.terms_order_by); overwrite(doc, `aggs.${series.id}.terms.field`, series.terms_field); overwrite(doc, `aggs.${series.id}.terms.size`, series.terms_size); if (series.terms_include) { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js index ff7139c380af9..556a544cd1b0b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/series/split_by_terms.test.js @@ -51,7 +51,7 @@ describe('splitByTerms(req, panel, series)', () => { }); test('returns a valid terms agg', () => { - const next = doc => doc; + const next = (doc) => doc; const doc = splitByTerms(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -69,7 +69,7 @@ describe('splitByTerms(req, panel, series)', () => { }); test('returns a valid terms agg sort by terms', () => { - const next = doc => doc; + const next = (doc) => doc; series.terms_order_by = '_key'; series.terms_direction = 'asc'; const doc = splitByTerms(req, panel, series)(next)({}); @@ -90,7 +90,7 @@ describe('splitByTerms(req, panel, series)', () => { test('returns a valid terms agg with custom sort', () => { series.terms_order_by = 'avgmetric'; - const next = doc => doc; + const next = (doc) => doc; const doc = splitByTerms(req, panel, series)(next)({}); expect(doc).toEqual({ aggs: { @@ -116,7 +116,7 @@ describe('splitByTerms(req, panel, series)', () => { test('calls next and does not add a terms agg', () => { series.split_mode = 'everything'; - const next = jest.fn(doc => doc); + const next = jest.fn((doc) => doc); const doc = splitByTerms(req, panel, series)(next)({}); expect(next.mock.calls.length).toEqual(1); expect(doc).toEqual({}); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.js index 6b51415627fe9..947e48ed2cab2 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/date_histogram.js @@ -27,7 +27,7 @@ import { search } from '../../../../../../../plugins/data/server'; const { dateHistogramInterval } = search.aggs; export function dateHistogram(req, panel, esQueryConfig, indexPatternObject, capabilities) { - return next => doc => { + return (next) => (doc) => { const { timeField, interval } = getIntervalAndTimefield(panel, {}, indexPatternObject); const meta = { timeField, @@ -38,7 +38,7 @@ export function dateHistogram(req, panel, esQueryConfig, indexPatternObject, cap const { from, to } = getTimerange(req); const timezone = capabilities.searchTimezone; - panel.series.forEach(column => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); overwrite(doc, `${aggRoot}.timeseries.date_histogram`, { @@ -61,7 +61,7 @@ export function dateHistogram(req, panel, esQueryConfig, indexPatternObject, cap }; const getDateHistogramForEntireTimerangeMode = () => { - panel.series.forEach(column => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); overwrite(doc, `${aggRoot}.timeseries.auto_date_histogram`, { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/filter_ratios.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/filter_ratios.js index 8bce521e742d8..707ccd1e55bb0 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/filter_ratios.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/filter_ratios.js @@ -17,17 +17,17 @@ * under the License. */ -const filter = metric => metric.type === 'filter_ratio'; +const filter = (metric) => metric.type === 'filter_ratio'; import { bucketTransform } from '../../helpers/bucket_transform'; import { overwrite } from '../../helpers'; import { calculateAggRoot } from './calculate_agg_root'; export function ratios(req, panel) { - return next => doc => { - panel.series.forEach(column => { + return (next) => (doc) => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); if (column.metrics.some(filter)) { - column.metrics.filter(filter).forEach(metric => { + column.metrics.filter(filter).forEach((metric) => { overwrite(doc, `${aggRoot}.timeseries.aggs.${metric.id}-numerator.filter`, { query_string: { query: metric.numerator || '*', analyze_wildcard: true }, }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.js index d38282ed3e9aa..ba2c09e93e7e6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/metric_buckets.js @@ -24,14 +24,14 @@ import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; import { calculateAggRoot } from './calculate_agg_root'; export function metricBuckets(req, panel, esQueryConfig, indexPatternObject) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, {}, indexPatternObject); const { intervalString } = getBucketSize(req, interval); - panel.series.forEach(column => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); column.metrics - .filter(row => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) - .forEach(metric => { + .filter((row) => !/_bucket$/.test(row.type) && !/^series/.test(row.type)) + .forEach((metric) => { const fn = bucketTransform[metric.type]; if (fn) { try { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.js index c38351e37dc31..9fdb96fa31481 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.js @@ -28,7 +28,7 @@ const hasSiblingPipelineAggregation = (aggs = {}) => Object.keys(aggs).length > * */ export function normalizeQuery() { - return () => doc => { + return () => (doc) => { const series = _.get(doc, 'aggs.pivot.aggs'); const normalizedSeries = {}; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.js index c212e0bb78cf6..217d9b1570348 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/normalize_query.test.js @@ -75,7 +75,7 @@ describe('normalizeQuery', () => { }); beforeEach(() => { - next = jest.fn(x => x); + next = jest.fn((x) => x); panel = {}; series = { id: seriesId, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.js index 6597973c28cf0..ad085f25cf451 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/pivot.js @@ -25,13 +25,13 @@ import { getBucketsPath } from '../../helpers/get_buckets_path'; import { bucketTransform } from '../../helpers/bucket_transform'; export function pivot(req, panel) { - return next => doc => { + return (next) => (doc) => { const { sort } = req.payload.state; if (panel.pivot_id) { overwrite(doc, 'aggs.pivot.terms.field', panel.pivot_id); overwrite(doc, 'aggs.pivot.terms.size', panel.pivot_rows); if (sort) { - const series = panel.series.find(item => item.id === sort.column); + const series = panel.series.find((item) => item.id === sort.column); const metric = series && last(series.metrics); if (metric && metric.type === 'count') { overwrite(doc, 'aggs.pivot.terms.order', { _count: sort.order }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.js index da4b834822d70..b219f84deef80 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/positive_rate.js @@ -23,10 +23,10 @@ import { calculateAggRoot } from './calculate_agg_root'; import { createPositiveRate, filter } from '../series/positive_rate'; export function positiveRate(req, panel, esQueryConfig, indexPatternObject) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, {}, indexPatternObject); const { intervalString } = getBucketSize(req, interval); - panel.series.forEach(column => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); column.metrics.filter(filter).forEach(createPositiveRate(doc, intervalString, aggRoot)); }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.js index d8d948e01cccd..5ceef6e20ae7c 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/query.js @@ -21,7 +21,7 @@ import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; import { esQuery } from '../../../../../../data/server'; export function query(req, panel, esQueryConfig, indexPatternObject) { - return next => doc => { + return (next) => (doc) => { const { timeField } = getIntervalAndTimefield(panel, {}, indexPatternObject); const { from, to } = getTimerange(req); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.js index b7ffbaa65619c..1b14ffe34a947 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/sibling_buckets.js @@ -24,14 +24,14 @@ import { getIntervalAndTimefield } from '../../get_interval_and_timefield'; import { calculateAggRoot } from './calculate_agg_root'; export function siblingBuckets(req, panel, esQueryConfig, indexPatternObject) { - return next => doc => { + return (next) => (doc) => { const { interval } = getIntervalAndTimefield(panel, {}, indexPatternObject); const { bucketSize } = getBucketSize(req, interval); - panel.series.forEach(column => { + panel.series.forEach((column) => { const aggRoot = calculateAggRoot(doc, column); column.metrics - .filter(row => /_bucket$/.test(row.type)) - .forEach(metric => { + .filter((row) => /_bucket$/.test(row.type)) + .forEach((metric) => { const fn = bucketTransform[metric.type]; if (fn) { try { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.js index fd03921346fb8..bc868f6a542f1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_everything.js @@ -21,10 +21,10 @@ import { overwrite } from '../../helpers'; import { esQuery } from '../../../../../../data/server'; export function splitByEverything(req, panel, esQueryConfig, indexPattern) { - return next => doc => { + return (next) => (doc) => { panel.series - .filter(c => !(c.aggregate_by && c.aggregate_function)) - .forEach(column => { + .filter((c) => !(c.aggregate_by && c.aggregate_function)) + .forEach((column) => { if (column.filter) { overwrite( doc, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_terms.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_terms.js index a34d53a6bc975..47b7d8604a1b6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_terms.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/request_processors/table/split_by_terms.js @@ -21,10 +21,10 @@ import { overwrite } from '../../helpers'; import { esQuery } from '../../../../../../data/server'; export function splitByTerms(req, panel, esQueryConfig, indexPattern) { - return next => doc => { + return (next) => (doc) => { panel.series - .filter(c => c.aggregate_by && c.aggregate_function) - .forEach(column => { + .filter((c) => c.aggregate_by && c.aggregate_function) + .forEach((column) => { overwrite(doc, `aggs.pivot.aggs.${column.id}.terms.field`, column.aggregate_by); overwrite(doc, `aggs.pivot.aggs.${column.id}.terms.size`, 100); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/buckets.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/buckets.js index 6170f9b7e4f63..fc7acc7fc35c0 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/buckets.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/buckets.js @@ -21,9 +21,9 @@ import { get, isEmpty } from 'lodash'; export function getAnnotationBuckets(resp, annotation) { return get(resp, `aggregations.${annotation.id}.buckets`, []) - .filter(bucket => !isEmpty(bucket.hits.hits.hits)) - .map(bucket => ({ + .filter((bucket) => !isEmpty(bucket.hits.hits.hits)) + .map((bucket) => ({ key: bucket.key, - docs: bucket.hits.hits.hits.map(doc => doc._source), + docs: bucket.hits.hits.hits.map((doc) => doc._source), })); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/filter.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/filter.js index 32bce3b2f0262..e3a4fde2fa4bf 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/filter.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/filter.js @@ -21,17 +21,17 @@ * @param {Function} by - it's a callback which determines how data will be mapped. * @return {Function} function - a predefined filter function */ -export const makeFilter = by => +export const makeFilter = (by) => /** * @param {*} value * @return {Function} function - the predefined filter function with a filter value */ - value => + (value) => /** * @param {Array|Object} data * @return {*} result - it depends on "by" outcome. */ - data => by(data, value); + (data) => by(data, value); /** * @param {Array} annotations diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/index.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/index.js index 09c30c6d4f8e5..dab7e94a8194e 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/index.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/annotations/index.js @@ -21,5 +21,5 @@ import { flow } from 'lodash'; import { filterAnnotations } from './filter'; import { getAnnotationBuckets } from './buckets'; -export const handleAnnotationResponse = timestamp => +export const handleAnnotationResponse = (timestamp) => flow(getAnnotationBuckets, filterAnnotations(timestamp)); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/_series_agg.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/_series_agg.js index a37fbd066bca2..63b77f8ad60f4 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/_series_agg.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/_series_agg.js @@ -23,11 +23,11 @@ function mean(values) { return _.sum(values) / values.length; } -const extractValue = r => (r && r[1]) || 0; +const extractValue = (r) => (r && r[1]) || 0; -const basic = fnName => targetSeries => { +const basic = (fnName) => (targetSeries) => { const data = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; const values = row.map(extractValue); const fn = _[fnName] || (() => null); @@ -36,15 +36,15 @@ const basic = fnName => targetSeries => { return [data]; }; -const overall = fnName => targetSeries => { +const overall = (fnName) => (targetSeries) => { const fn = _[fnName]; const keys = []; const values = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { keys.push(row[0][0]); values.push(fn(row.map(extractValue))); }); - return [keys.map(k => [k, fn(values)])]; + return [keys.map((k) => [k, fn(values)])]; }; export const SeriesAgg = { @@ -53,7 +53,7 @@ export const SeriesAgg = { min: basic('min'), mean(targetSeries) { const data = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; const values = row.map(extractValue); data.push([key, mean(values)]); @@ -69,17 +69,17 @@ export const SeriesAgg = { const fn = mean; const keys = []; const values = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { keys.push(row[0][0]); values.push(_.sum(row.map(extractValue))); }); - return [keys.map(k => [k, fn(values)])]; + return [keys.map((k) => [k, fn(values)])]; }, cumulative_sum(targetSeries) { const data = []; let sum = 0; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; sum += _.sum(row.map(extractValue)); data.push([key, sum]); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/drop_last_bucket.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/drop_last_bucket.js index a4a7b01fa6f5e..9b3d8c16a1121 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/drop_last_bucket.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/drop_last_bucket.js @@ -21,7 +21,7 @@ import { get } from 'lodash'; import { isLastValueTimerangeMode } from '../../helpers/get_timerange_mode'; export function dropLastBucket(resp, panel, series) { - return next => results => { + return (next) => (results) => { const shouldDropLastBucket = isLastValueTimerangeMode(panel, series); if (shouldDropLastBucket) { @@ -29,7 +29,7 @@ export function dropLastBucket(resp, panel, series) { const dropLastBucket = get(panel, 'drop_last_bucket', seriesDropLastBucket); if (dropLastBucket) { - results.forEach(item => { + results.forEach((item) => { item.data = item.data.slice(0, item.data.length - 1); }); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/math.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/math.js index 0e93e963ce1bb..6c8fe7ca16619 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/math.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/math.js @@ -26,12 +26,12 @@ import { mapBucket } from '../../helpers/map_bucket'; import { evaluate } from 'tinymath'; export function mathAgg(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const mathMetric = last(series.metrics); if (mathMetric.type !== 'math') return next(results); // Filter the results down to only the ones that match the series.id. Sometimes // there will be data from other series mixed in. - results = results.filter(s => { + results = results.filter((s) => { if (s.id.split(/:/)[0] === series.id) { return false; } @@ -39,15 +39,15 @@ export function mathAgg(resp, panel, series, meta) { }); const decoration = getDefaultDecoration(series); const splits = getSplits(resp, panel, series, meta); - const mathSeries = splits.map(split => { + const mathSeries = splits.map((split) => { if (mathMetric.variables.length) { // Gather the data for the splits. The data will either be a sibling agg or // a standard metric/pipeline agg const splitData = mathMetric.variables.reduce((acc, v) => { - const metric = series.metrics.find(m => startsWith(v.field, m.id)); + const metric = series.metrics.find((m) => startsWith(v.field, m.id)); if (!metric) return acc; if (/_bucket$/.test(metric.type)) { - acc[v.name] = split.timeseries.buckets.map(bucket => { + acc[v.name] = split.timeseries.buckets.map((bucket) => { return [bucket.key, getSiblingAggValue(split, metric)]; }); } else { @@ -61,8 +61,8 @@ export function mathAgg(resp, panel, series, meta) { // in the Math.js equation const all = Object.keys(splitData).reduce((acc, key) => { acc[key] = { - values: splitData[key].map(x => x[1]), - timestamps: splitData[key].map(x => x[0]), + values: splitData[key].map((x) => x[1]), + timestamps: splitData[key].map((x) => x[0]), }; return acc; }, {}); @@ -80,16 +80,16 @@ export function mathAgg(resp, panel, series, meta) { }; } // Use the first var to collect all the timestamps - const timestamps = splitData[firstVar.name].map(r => first(r)); + const timestamps = splitData[firstVar.name].map((r) => first(r)); // Map the timestamps to actual data const data = timestamps.map((ts, index) => { const params = mathMetric.variables.reduce((acc, v) => { - acc[v.name] = last(splitData[v.name].find(row => row[0] === ts)); + acc[v.name] = last(splitData[v.name].find((row) => row[0] === ts)); return acc; }, {}); // If some of the values are null, return the timestamp and null, this is // a safety check for the user - const someNull = values(params).some(v => v == null); + const someNull = values(params).some((v) => v == null); if (someNull) return [ts, null]; // calculate the result based on the user's script and return the value const result = evaluate(mathMetric.script, { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.js index 00fb48c88ec3f..2e0d176f80b23 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.js @@ -24,18 +24,18 @@ import { getLastMetric } from '../../helpers/get_last_metric'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function percentile(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type !== METRIC_TYPES.PERCENTILE) { return next(results); } - getSplits(resp, panel, series, meta).forEach(split => { - metric.percentiles.forEach(percentile => { + getSplits(resp, panel, series, meta).forEach((split) => { + metric.percentiles.forEach((percentile) => { const percentileValue = percentile.value ? percentile.value : 0; const id = `${split.id}:${percentile.id}`; - const data = split.timeseries.buckets.map(bucket => { + const data = split.timeseries.buckets.map((bucket) => { const higherMetric = { ...metric, percent: percentileValue }; const serieData = [bucket.key, getAggValue(bucket, higherMetric)]; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.test.js index aec1c45cf97e1..d239cb2138fe1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile.test.js @@ -87,7 +87,7 @@ describe('percentile(resp, panel, series)', () => { }); test('creates a series', () => { - const next = results => results; + const next = (results) => results; const results = percentile(resp, panel, series)(next)([]); expect(results).toHaveLength(2); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.js index cdb7a2046d893..a11324f73e611 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/percentile_rank.js @@ -24,16 +24,16 @@ import { toPercentileNumber } from '../../../../../common/to_percentile_number'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function percentileRank(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type !== METRIC_TYPES.PERCENTILE_RANK) { return next(results); } - getSplits(resp, panel, series, meta).forEach(split => { - (metric.values || []).forEach(percentileRank => { - const data = split.timeseries.buckets.map(bucket => [ + getSplits(resp, panel, series, meta).forEach((split) => { + (metric.values || []).forEach((percentileRank) => { + const data = split.timeseries.buckets.map((bucket) => [ bucket.key, getAggValue(bucket, { ...metric, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.js index 79f6e69cfd82b..d2b0ce9226bb9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.js @@ -23,14 +23,14 @@ import { getDefaultDecoration } from '../../helpers/get_default_decoration'; import { calculateLabel } from '../../../../../common/calculate_label'; export function seriesAgg(resp, panel, series) { - return next => results => { - if (series.metrics.some(m => m.type === 'series_agg')) { + return (next) => (results) => { + if (series.metrics.some((m) => m.type === 'series_agg')) { const decoration = getDefaultDecoration(series); const targetSeries = []; // Filter out the seires with the matching metric and store them // in targetSeries - results = results.filter(s => { + results = results.filter((s) => { if (s.id.split(/:/)[0] === series.id) { targetSeries.push(s.data); return false; @@ -38,7 +38,7 @@ export function seriesAgg(resp, panel, series) { return true; }); const data = series.metrics - .filter(m => m.type === 'series_agg') + .filter((m) => m.type === 'series_agg') .reduce((acc, m) => { const fn = SeriesAgg[m.function]; return (fn && fn(acc)) || acc; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.test.js index 3e09c51d9184f..b458eee17bce5 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/series_agg.test.js @@ -98,7 +98,7 @@ describe('seriesAgg(resp, panel, series)', () => { }); test('creates a series', () => { - const next = seriesAgg(resp, panel, series)(results => results); + const next = seriesAgg(resp, panel, series)((results) => results); const results = stdMetric(resp, panel, series)(next)([]); expect(results).toHaveLength(1); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.js index 4479cec721e4c..be95913c6ec38 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.js @@ -21,11 +21,11 @@ import { getAggValue, getLastMetric, getSplits } from '../../helpers'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function stdDeviationBands(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type === METRIC_TYPES.STD_DEVIATION && metric.mode === 'band') { getSplits(resp, panel, series, meta).forEach(({ id, color, label, timeseries }) => { - const data = timeseries.buckets.map(bucket => [ + const data = timeseries.buckets.map((bucket) => [ bucket.key, getAggValue(bucket, { ...metric, mode: 'upper' }), getAggValue(bucket, { ...metric, mode: 'lower' }), diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.test.js index a229646ba8f3f..4899eaed2611a 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_bands.test.js @@ -84,7 +84,7 @@ describe('stdDeviationBands(resp, panel, series)', () => { }); test('creates a series', () => { - const next = results => results; + const next = (results) => results; const results = stdDeviationBands(resp, panel, series)(next)([]); expect(results).toHaveLength(1); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.js index 1c6ee94050a62..321e1c5125e1c 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.js @@ -20,11 +20,11 @@ import { getSplits, getLastMetric, getSiblingAggValue } from '../../helpers'; export function stdDeviationSibling(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.mode === 'band' && metric.type === 'std_deviation_bucket') { - getSplits(resp, panel, series, meta).forEach(split => { - const data = split.timeseries.buckets.map(bucket => [ + getSplits(resp, panel, series, meta).forEach((split) => { + const data = split.timeseries.buckets.map((bucket) => [ bucket.key, getSiblingAggValue(split, { ...metric, mode: 'upper' }), getSiblingAggValue(split, { ...metric, mode: 'lower' }), diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.test.js index b93d929d5157a..b6acf822bc242 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_deviation_sibling.test.js @@ -84,7 +84,7 @@ describe('stdDeviationSibling(resp, panel, series)', () => { }); test('creates a series', () => { - const next = results => results; + const next = (results) => results; const results = stdDeviationSibling(resp, panel, series)(next)([]); expect(results).toHaveLength(1); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.js index 0fa723c8629b1..0d567b7fd4154 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.js @@ -24,7 +24,7 @@ import { mapBucket } from '../../helpers/map_bucket'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function stdMetric(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type === METRIC_TYPES.STD_DEVIATION && metric.mode === 'band') { return next(results); @@ -35,7 +35,7 @@ export function stdMetric(resp, panel, series, meta) { } if (/_bucket$/.test(metric.type)) return next(results); const decoration = getDefaultDecoration(series); - getSplits(resp, panel, series, meta).forEach(split => { + getSplits(resp, panel, series, meta).forEach((split) => { const data = split.timeseries.buckets.map(mapBucket(metric)); results.push({ id: `${split.id}`, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.test.js index 6ddd6f907fa97..78a29c04732d7 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_metric.test.js @@ -66,7 +66,7 @@ describe('stdMetric(resp, panel, series)', () => { test('calls next when finished (percentile)', () => { series.metrics[0].type = 'percentile'; - const next = jest.fn(d => d); + const next = jest.fn((d) => d); const results = stdMetric(resp, panel, series)(next)([]); expect(next.mock.calls.length).toEqual(1); expect(results).toHaveLength(0); @@ -75,14 +75,14 @@ describe('stdMetric(resp, panel, series)', () => { test('calls next when finished (std_deviation band)', () => { series.metrics[0].type = 'std_deviation'; series.metrics[0].mode = 'band'; - const next = jest.fn(d => d); + const next = jest.fn((d) => d); const results = stdMetric(resp, panel, series)(next)([]); expect(next.mock.calls.length).toEqual(1); expect(results).toHaveLength(0); }); test('creates a series', () => { - const next = results => results; + const next = (results) => results; const results = stdMetric(resp, panel, series)(next)([]); expect(results).toHaveLength(1); expect(results[0]).toHaveProperty('color', 'rgb(255, 0, 0)'); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.js index 35ac4be8fa6f8..b5d972a38769e 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.js @@ -23,15 +23,15 @@ import { getLastMetric } from '../../helpers/get_last_metric'; import { getSiblingAggValue } from '../../helpers/get_sibling_agg_value'; export function stdSibling(resp, panel, series, meta) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (!/_bucket$/.test(metric.type)) return next(results); if (metric.type === 'std_deviation_bucket' && metric.mode === 'band') return next(results); const decoration = getDefaultDecoration(series); - getSplits(resp, panel, series, meta).forEach(split => { - const data = split.timeseries.buckets.map(bucket => { + getSplits(resp, panel, series, meta).forEach((split) => { + const data = split.timeseries.buckets.map((bucket) => { return [bucket.key, getSiblingAggValue(split, metric)]; }); results.push({ diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.test.js index 9ed60a6d16492..d99ae6771c437 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/std_sibling.test.js @@ -80,14 +80,14 @@ describe('stdSibling(resp, panel, series)', () => { test('calls next when std. deviation bands set', () => { series.metrics[1].mode = 'band'; - const next = jest.fn(results => results); + const next = jest.fn((results) => results); const results = stdSibling(resp, panel, series)(next)([]); expect(next.mock.calls.length).toEqual(1); expect(results).toHaveLength(0); }); test('creates a series', () => { - const next = results => results; + const next = (results) => results; const results = stdSibling(resp, panel, series)(next)([]); expect(results).toHaveLength(1); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.js index ad2f5c9acecce..14de6aa18f872 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.js @@ -21,7 +21,7 @@ import _ from 'lodash'; import moment from 'moment'; export function timeShift(resp, panel, series) { - return next => results => { + return (next) => (results) => { if (/^([+-]?[\d]+)([shmdwMy]|ms)$/.test(series.offset_time)) { const matches = series.offset_time.match(/^([+-]?[\d]+)([shmdwMy]|ms)$/); @@ -30,7 +30,7 @@ export function timeShift(resp, panel, series) { const offsetUnit = matches[2]; const offset = moment.duration(offsetValue, offsetUnit).valueOf(); - results.forEach(item => { + results.forEach((item) => { if (_.startsWith(item.id, series.id)) { item.data = item.data.map(([time, value]) => [time + offset, value]); } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.test.js index 7047c54fa1c0e..57c1a8aead7dc 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/series/time_shift.test.js @@ -67,7 +67,7 @@ describe('timeShift(resp, panel, series)', () => { }); test('creates a series', () => { - const next = timeShift(resp, panel, series)(results => results); + const next = timeShift(resp, panel, series)((results) => results); const results = stdMetric(resp, panel, series)(next)([]); expect(results).toHaveLength(1); expect(results[0]).toHaveProperty('color', 'rgb(255, 0, 0)'); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/_series_agg.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/_series_agg.js index 956409d4f34d9..511349b89deb1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/_series_agg.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/_series_agg.js @@ -23,26 +23,26 @@ function mean(values) { return _.sum(values) / values.length; } -const basic = fnName => targetSeries => { +const basic = (fnName) => (targetSeries) => { const data = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; - const values = row.map(r => r[1]); + const values = row.map((r) => r[1]); const fn = _[fnName] || (() => null); data.push([key, fn(values)]); }); return [data]; }; -const overall = fnName => targetSeries => { +const overall = (fnName) => (targetSeries) => { const fn = _[fnName]; const keys = []; const values = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { keys.push(row[0][0]); - values.push(fn(row.map(r => r[1]))); + values.push(fn(row.map((r) => r[1]))); }); - return [keys.map(k => [k, fn(values)])]; + return [keys.map((k) => [k, fn(values)])]; }; export const SeriesAgg = { @@ -51,9 +51,9 @@ export const SeriesAgg = { min: basic('min'), mean(targetSeries) { const data = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; - const values = row.map(r => r[1]); + const values = row.map((r) => r[1]); data.push([key, mean(values)]); }); return [data]; @@ -67,19 +67,19 @@ export const SeriesAgg = { const fn = mean; const keys = []; const values = []; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { keys.push(row[0][0]); - values.push(_.sum(row.map(r => r[1]))); + values.push(_.sum(row.map((r) => r[1]))); }); - return [keys.map(k => [k, fn(values)])]; + return [keys.map((k) => [k, fn(values)])]; }, cumulative_sum(targetSeries) { const data = []; let sum = 0; - _.zip(...targetSeries).forEach(row => { + _.zip(...targetSeries).forEach((row) => { const key = row[0][0]; - sum += _.sum(row.map(r => r[1])); + sum += _.sum(row.map((r) => r[1])); data.push([key, sum]); }); return [data]; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.js index 05269335790b3..678631bce8faa 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/drop_last_bucket.js @@ -21,7 +21,7 @@ import { dropLastBucket } from '../series/drop_last_bucket'; import { isLastValueTimerangeMode } from '../../helpers/get_timerange_mode'; export function dropLastBucketFn(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const shouldDropLastBucket = isLastValueTimerangeMode(panel); if (shouldDropLastBucket) { diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.js index 6da39077aa63b..43d641c5f60de 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/math.js @@ -20,7 +20,7 @@ import { mathAgg } from '../series/math'; export function math(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const mathFn = mathAgg({ aggregations: bucket }, panel, series); return mathFn(next)(results); }; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.js index 91c714c49ea6b..788bb6f14a0c7 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile.js @@ -23,7 +23,7 @@ import { toPercentileNumber } from '../../../../../common/to_percentile_number'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function percentile(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type !== METRIC_TYPES.PERCENTILE) { @@ -34,11 +34,11 @@ export function percentile(bucket, panel, series) { aggregations: bucket, }; - getSplits(fakeResp, panel, series).forEach(split => { + getSplits(fakeResp, panel, series).forEach((split) => { // table allows only one percentile in a series (the last one will be chosen in case of several) const percentile = last(metric.percentiles); const percentileKey = toPercentileNumber(percentile.value); - const data = split.timeseries.buckets.map(bucket => [ + const data = split.timeseries.buckets.map((bucket) => [ bucket.key, bucket[metric.id].values[percentileKey], ]); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.js index a87e0f7c05e91..c280538c7ce5f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/percentile_rank.js @@ -24,7 +24,7 @@ import { getAggValue } from '../../helpers/get_agg_value'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function percentileRank(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type !== METRIC_TYPES.PERCENTILE_RANK) { @@ -35,12 +35,12 @@ export function percentileRank(bucket, panel, series) { aggregations: bucket, }; - getSplits(fakeResp, panel, series).forEach(split => { + getSplits(fakeResp, panel, series).forEach((split) => { // table allows only one percentile rank in a series (the last one will be chosen in case of several) const lastRankValue = last(metric.values); const percentileRank = toPercentileNumber(lastRankValue); - const data = split.timeseries.buckets.map(bucket => [ + const data = split.timeseries.buckets.map((bucket) => [ bucket.key, getAggValue(bucket, { ...metric, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.js index 77e5907c083d0..343198bc22a6e 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/series_agg.js @@ -22,12 +22,12 @@ import _ from 'lodash'; import { calculateLabel } from '../../../../../common/calculate_label'; export function seriesAgg(resp, panel, series) { - return next => results => { + return (next) => (results) => { if (series.aggregate_by && series.aggregate_function) { const targetSeries = []; // Filter out the seires with the matching metric and store them // in targetSeries - results = results.filter(s => { + results = results.filter((s) => { if (s.id.split(/:/)[0] === series.id) { targetSeries.push(s.data); return false; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.js index 2be649c8f03b4..2242b338e7b92 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_metric.js @@ -23,7 +23,7 @@ import { mapBucket } from '../../helpers/map_bucket'; import { METRIC_TYPES } from '../../../../../common/metric_types'; export function stdMetric(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (metric.type === METRIC_TYPES.STD_DEVIATION && metric.mode === 'band') { @@ -42,7 +42,7 @@ export function stdMetric(bucket, panel, series) { aggregations: bucket, }; - getSplits(fakeResp, panel, series).forEach(split => { + getSplits(fakeResp, panel, series).forEach((split) => { const data = split.timeseries.buckets.map(mapBucket(metric)); results.push({ id: split.id, diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.js index 9dd9609dc1af3..17cfac6e8895b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/response_processors/table/std_sibling.js @@ -22,15 +22,15 @@ import { getLastMetric } from '../../helpers/get_last_metric'; import { getSiblingAggValue } from '../../helpers/get_sibling_agg_value'; export function stdSibling(bucket, panel, series) { - return next => results => { + return (next) => (results) => { const metric = getLastMetric(series); if (!/_bucket$/.test(metric.type)) return next(results); if (metric.type === 'std_deviation_bucket' && metric.mode === 'band') return next(results); const fakeResp = { aggregations: bucket }; - getSplits(fakeResp, panel, series).forEach(split => { - const data = split.timeseries.buckets.map(b => { + getSplits(fakeResp, panel, series).forEach((split) => { + const data = split.timeseries.buckets.map((b) => { return [b.key, getSiblingAggValue(split, metric)]; }); results.push({ diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/series/handle_response_body.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/series/handle_response_body.js index a4dcf6f5a85cd..eef7143990e98 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/series/handle_response_body.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/series/handle_response_body.js @@ -23,7 +23,7 @@ import { get } from 'lodash'; import { i18n } from '@kbn/i18n'; export function handleResponseBody(panel) { - return resp => { + return (resp) => { if (resp.error) { const err = new Error(resp.error.type); err.response = JSON.stringify(resp); @@ -47,7 +47,7 @@ export function handleResponseBody(panel) { } const [seriesId] = keys; const meta = get(resp, `aggregations.${seriesId}.meta`, {}); - const series = panel.series.find(s => s.id === (meta.seriesId || seriesId)); + const series = panel.series.find((s) => s.id === (meta.seriesId || seriesId)); const processor = buildProcessorFunction(processors, resp, panel, series, meta); return processor([]); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.js index 87e9734ea1054..0f2a7e153bde0 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/table/process_bucket.js @@ -26,8 +26,8 @@ import { overwrite } from '../helpers'; import { getActiveSeries } from '../helpers/get_active_series'; export function processBucket(panel) { - return bucket => { - const series = getActiveSeries(panel).map(series => { + return (bucket) => { + const series = getActiveSeries(panel).map((series) => { const timeseries = get(bucket, `${series.id}.timeseries`); const buckets = get(bucket, `${series.id}.buckets`); diff --git a/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts b/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts index 1d565e69a801c..c74d1dd72d761 100644 --- a/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts +++ b/src/plugins/vis_type_timeseries/server/routes/post_vis_schema.ts @@ -26,7 +26,7 @@ const stringRequired = schema.string(); const arrayNullable = schema.arrayOf(schema.nullable(schema.any())); -const validateInteger: TypeOptions['validate'] = value => { +const validateInteger: TypeOptions['validate'] = (value) => { if (!Number.isInteger(value)) { return `${value} is not an integer`; } diff --git a/src/plugins/vis_type_timeseries/server/saved_objects/tsvb_telemetry.ts b/src/plugins/vis_type_timeseries/server/saved_objects/tsvb_telemetry.ts index 1e5508b44ee0e..f6754e5fd9ca4 100644 --- a/src/plugins/vis_type_timeseries/server/saved_objects/tsvb_telemetry.ts +++ b/src/plugins/vis_type_timeseries/server/saved_objects/tsvb_telemetry.ts @@ -20,7 +20,7 @@ import { flow } from 'lodash'; import { SavedObjectMigrationFn, SavedObjectsType } from 'kibana/server'; -const resetCount: SavedObjectMigrationFn = doc => ({ +const resetCount: SavedObjectMigrationFn = (doc) => ({ ...doc, attributes: { ...doc.attributes, diff --git a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts index e4b8ca19094e4..505816d48af52 100644 --- a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts +++ b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts @@ -38,7 +38,7 @@ export class ValidationTelemetryService implements Plugin { + globalConfig$.subscribe((config) => { this.kibanaIndex = config.kibana.index; }); if (usageCollection) { diff --git a/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx b/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx index 3d7fda990b2ae..f10954df432c2 100644 --- a/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx +++ b/src/plugins/vis_type_vega/public/components/vega_actions_menu.tsx @@ -30,7 +30,7 @@ interface VegaActionsMenuProps { function VegaActionsMenu({ formatHJson, formatJson }: VegaActionsMenuProps) { const [isPopoverOpen, setIsPopoverOpen] = useState(false); - const onButtonClick = useCallback(() => setIsPopoverOpen(isOpen => !isOpen), []); + const onButtonClick = useCallback(() => setIsPopoverOpen((isOpen) => !isOpen), []); const onHJsonCLick = useCallback(() => { formatHJson(); setIsPopoverOpen(false); diff --git a/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js b/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js index 02009a87bc297..ecdf6a43d5287 100644 --- a/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js @@ -65,7 +65,7 @@ export class EmsFileParser { const layers = await this._fileLayersP; for (const { obj, name } of requests) { - const foundLayer = layers.find(v => v.name === name); + const foundLayer = layers.find((v) => v.name === name); if (!foundLayer) { throw new Error( i18n.translate('visTypeVega.emsFileParser.emsFileNameDoesNotExistErrorMessage', { diff --git a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js b/src/plugins/vis_type_vega/public/data_model/es_query_parser.js index 7c239800483f0..066c9f06fc109 100644 --- a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/es_query_parser.js @@ -179,7 +179,7 @@ export class EsQueryParser { return { dataObject, url }; } - mapRequest = request => { + mapRequest = (request) => { const esRequest = request.url; if (this._esShardTimeout) { // remove possible timeout query param to prevent two conflicting timeout parameters diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.js b/src/plugins/vis_type_vega/public/data_model/vega_parser.js index 735ce60f76d47..f541b9f104adc 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.js @@ -408,7 +408,7 @@ export class VegaParser { if ( !Array.isArray(maxBounds) || maxBounds.length !== 4 || - !maxBounds.every(v => typeof v === 'number' && Number.isFinite(v)) + !maxBounds.every((v) => typeof v === 'number' && Number.isFinite(v)) ) { this._onWarning( i18n.translate('visTypeVega.vegaParser.maxBoundsValueTypeWarningMessage', { @@ -491,7 +491,7 @@ export class VegaParser { async _resolveDataUrls() { const pending = {}; - this._findObjectDataUrls(this.spec, obj => { + this._findObjectDataUrls(this.spec, (obj) => { const url = obj.url; delete obj.url; let type = url['%type%']; @@ -524,7 +524,7 @@ export class VegaParser { if (pendingParsers.length > 0) { // let each parser populate its data in parallel await Promise.all( - pendingParsers.map(type => this._urlParsers[type].populateData(pending[type])) + pendingParsers.map((type) => this._urlParsers[type].populateData(pending[type])) ); } } diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js b/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js index 78d1cad874311..1bd26b8713044 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.test.js @@ -82,7 +82,7 @@ describe('VegaParser._resolveEsQueries', () => { return async () => { const vp = new VegaParser(spec, { search: async () => [[42]] }, 0, 0, { getFileLayers: async () => [{ name: 'file1', url: 'url1' }], - getUrlForRegionLayer: async layer => { + getUrlForRegionLayer: async (layer) => { return layer.url; }, }); diff --git a/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js b/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js index be98d2b69ad87..4f6697de1f29e 100644 --- a/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js +++ b/src/plugins/vis_type_vega/public/vega_view/vega_base_view.js @@ -79,10 +79,7 @@ export class VegaBaseView { this._initialized = true; try { - this._$parentEl - .empty() - .addClass(`vgaVis`) - .css('flex-direction', this._parser.containerDir); + this._$parentEl.empty().addClass(`vgaVis`).css('flex-direction', this._parser.containerDir); // bypass the onWarn warning checks - in some cases warnings may still need to be shown despite being disabled for (const warn of this._parser.warnings) { @@ -283,7 +280,7 @@ export class VegaBaseView { const filterToRemove = esFilters.buildQueryFilter(query, indexId); const currentFilters = this._filterManager.getFilters(); - const existingFilter = currentFilters.find(filter => + const existingFilter = currentFilters.find((filter) => esFilters.compareFilters(filter, filterToRemove) ); @@ -398,7 +395,7 @@ export class VegaBaseView { // into the _ongoingDestroy promise, while handlers are being disposed if (this._destroyHandlers) { // If no destroy is yet running, execute all handlers and wait for all of them to resolve. - this._ongoingDestroy = Promise.all(this._destroyHandlers.map(v => v())); + this._ongoingDestroy = Promise.all(this._destroyHandlers.map((v) => v())); this._destroyHandlers = null; } return this._ongoingDestroy; diff --git a/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js b/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js index 4cd3eea503cb0..1cc163848fcf0 100644 --- a/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js +++ b/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js @@ -42,7 +42,7 @@ export class VegaMapView extends VegaBaseView { const mapStyle = mapConfig.mapStyle === 'default' ? emsTileLayerId.bright : mapConfig.mapStyle; const isDarkMode = getUISettings().get('theme:darkMode'); - baseMapOpts = tmsServices.find(s => s.id === mapStyle); + baseMapOpts = tmsServices.find((s) => s.id === mapStyle); baseMapOpts = { ...baseMapOpts, ...(await this._serviceSettings.getAttributesForTMSLayer(baseMapOpts, true, isDarkMode)), diff --git a/src/plugins/vis_type_vega/public/vega_view/vega_tooltip.js b/src/plugins/vis_type_vega/public/vega_view/vega_tooltip.js index adb43913ff2e3..01386fd91abc5 100644 --- a/src/plugins/vis_type_vega/public/vega_view/vega_tooltip.js +++ b/src/plugins/vis_type_vega/public/vega_view/vega_tooltip.js @@ -68,7 +68,7 @@ export class TooltipHandler { const el = document.createElement('div'); el.setAttribute('id', tooltipId); ['vgaVis__tooltip', 'euiToolTipPopover', 'euiToolTip', `euiToolTip--${this.position}`].forEach( - className => { + (className) => { el.classList.add(className); } ); diff --git a/src/plugins/vis_type_vislib/public/components/common/validation_wrapper.tsx b/src/plugins/vis_type_vislib/public/components/common/validation_wrapper.tsx index 718056fd85492..1a54132a3156e 100644 --- a/src/plugins/vis_type_vislib/public/components/common/validation_wrapper.tsx +++ b/src/plugins/vis_type_vislib/public/components/common/validation_wrapper.tsx @@ -38,11 +38,11 @@ function ValidationWrapper({ ...rest }: ValidationWrapperProps) { const [panelState, setPanelState] = useState({} as { [key: string]: Item }); - const isPanelValid = Object.values(panelState).every(item => item.isValid); + const isPanelValid = Object.values(panelState).every((item) => item.isValid); const { setValidity } = rest; const setValidityHandler = useCallback((paramName: string, isValid: boolean) => { - setPanelState(state => ({ + setPanelState((state) => ({ ...state, [paramName]: { isValid, diff --git a/src/plugins/vis_type_vislib/public/components/options/heatmap/labels_panel.tsx b/src/plugins/vis_type_vislib/public/components/options/heatmap/labels_panel.tsx index 8d5f529ce0fc7..4998a8fd02521 100644 --- a/src/plugins/vis_type_vislib/public/components/options/heatmap/labels_panel.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/heatmap/labels_panel.tsx @@ -58,7 +58,7 @@ function LabelsPanel({ valueAxis, setValue }: LabelsPanelProps) { [setValueAxisLabels] ); - const setColor = useCallback(value => setValueAxisLabels('color', value), [setValueAxisLabels]); + const setColor = useCallback((value) => setValueAxisLabels('color', value), [setValueAxisLabels]); return ( diff --git a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx index 114305d653dd1..d885f8fb0b12f 100644 --- a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/index.tsx @@ -216,12 +216,12 @@ function MetricsAxisOptions(props: ValidationVisOptionsProps) const removeValueAxis = useCallback( (axis: ValueAxis) => { - const newValueAxes = stateParams.valueAxes.filter(valAxis => valAxis.id !== axis.id); + const newValueAxes = stateParams.valueAxes.filter((valAxis) => valAxis.id !== axis.id); setValue('valueAxes', newValueAxes); let isSeriesUpdated = false; - const series = stateParams.seriesParams.map(ser => { + const series = stateParams.seriesParams.map((ser) => { if (axis.id === ser.valueAxis) { isSeriesUpdated = true; return { ...ser, valueAxis: newValueAxes[0].id }; @@ -265,8 +265,8 @@ function MetricsAxisOptions(props: ValidationVisOptionsProps) const firstValueAxesId = stateParams.valueAxes[0].id; useEffect(() => { - const updatedSeries = metrics.map(agg => { - const params = stateParams.seriesParams.find(param => param.data.id === agg.id); + const updatedSeries = metrics.map((agg) => { + const params = stateParams.seriesParams.find((param) => param.data.id === agg.id); const label = agg.makeLabel(); // update labels for existing params or create new one diff --git a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.test.tsx b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.test.tsx index 2f7dd4071b52c..c5dfebdf720d8 100644 --- a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.test.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.test.tsx @@ -92,10 +92,7 @@ describe('ValueAxesPanel component', () => { it('should call removeAgg', () => { const comp = mountWithIntl(); - comp - .find('[data-test-subj="removeValueAxisBtn"] button') - .first() - .simulate('click'); + comp.find('[data-test-subj="removeValueAxisBtn"] button').first().simulate('click'); expect(removeValueAxis).toBeCalledWith(axisLeft); }); @@ -111,10 +108,7 @@ describe('ValueAxesPanel component', () => { it('should show when one serie matches value axis', () => { const comp = mountWithIntl(); expect( - comp - .find('.visEditorSidebar__aggGroupAccordionButtonContent span') - .first() - .text() + comp.find('.visEditorSidebar__aggGroupAccordionButtonContent span').first().text() ).toBe(seriesParamCount.data.label); }); @@ -122,10 +116,7 @@ describe('ValueAxesPanel component', () => { defaultProps.seriesParams[1].valueAxis = 'ValueAxis-1'; const comp = mountWithIntl(); expect( - comp - .find('.visEditorSidebar__aggGroupAccordionButtonContent span') - .first() - .text() + comp.find('.visEditorSidebar__aggGroupAccordionButtonContent span').first().text() ).toBe(`${seriesParamCount.data.label}, ${seriesParamAverage.data.label}`); }); @@ -133,10 +124,7 @@ describe('ValueAxesPanel component', () => { defaultProps.seriesParams[0].valueAxis = 'ValueAxis-2'; const comp = mountWithIntl(); expect( - comp - .find('.visEditorSidebar__aggGroupAccordionButtonContent span') - .first() - .text() + comp.find('.visEditorSidebar__aggGroupAccordionButtonContent span').first().text() ).toBe(''); }); }); diff --git a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.tsx b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.tsx index b17f67b81d2b0..5f7d33b7f1f47 100644 --- a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/value_axes_panel.tsx @@ -55,9 +55,9 @@ function ValueAxesPanel(props: ValueAxesPanelProps) { (axis: ValueAxis) => { const isFirst = valueAxes[0].id === axis.id; const series = seriesParams.filter( - serie => serie.valueAxis === axis.id || (isFirst && !serie.valueAxis) + (serie) => serie.valueAxis === axis.id || (isFirst && !serie.valueAxis) ); - return series.map(serie => serie.data.label).join(', '); + return series.map((serie) => serie.data.label).join(', '); }, [seriesParams, valueAxes] ); diff --git a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/y_extents.test.tsx b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/y_extents.test.tsx index 3bacb0be34d13..7bd5c9efdf29d 100644 --- a/src/plugins/vis_type_vislib/public/components/options/metrics_axes/y_extents.test.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/metrics_axes/y_extents.test.tsx @@ -90,10 +90,7 @@ describe('YExtents component', () => { it('should call setScale with input number', () => { const inputNumber = 5; const comp = shallow(); - const inputProps = comp - .find(NumberInputOption) - .first() - .props(); + const inputProps = comp.find(NumberInputOption).first().props(); inputProps.setValue(Y_EXTENTS, inputNumber); expect(setScale).toBeCalledWith(Y_EXTENTS, inputNumber); @@ -101,10 +98,7 @@ describe('YExtents component', () => { it('should call setScale with null when input is empty', () => { const comp = shallow(); - const inputProps = comp - .find(NumberInputOption) - .first() - .props(); + const inputProps = comp.find(NumberInputOption).first().props(); inputProps.setValue(Y_EXTENTS, ''); expect(setScale).toBeCalledWith(Y_EXTENTS, null); diff --git a/src/plugins/vis_type_vislib/public/components/options/point_series/point_series.tsx b/src/plugins/vis_type_vislib/public/components/options/point_series/point_series.tsx index dfe469bc9843b..a27d0be8018c9 100644 --- a/src/plugins/vis_type_vislib/public/components/options/point_series/point_series.tsx +++ b/src/plugins/vis_type_vislib/public/components/options/point_series/point_series.tsx @@ -47,7 +47,7 @@ function PointSeriesOptions(props: ValidationVisOptionsProps) {vis.data.aggs!.aggs.some( - agg => agg.schema === 'segment' && agg.type.name === 'date_histogram' + (agg) => agg.schema === 'segment' && agg.type.name === 'date_histogram' ) ? ( ({ - convert: v => v, + convert: (v) => v, }), }); diff --git a/src/plugins/vis_type_vislib/public/plugin.ts b/src/plugins/vis_type_vislib/public/plugin.ts index e19a2ec451f2b..19bbf89ee0243 100644 --- a/src/plugins/vis_type_vislib/public/plugin.ts +++ b/src/plugins/vis_type_vislib/public/plugin.ts @@ -97,14 +97,14 @@ export class VisTypeVislibPlugin implements Plugin { // Register legacy vislib types that have been converted convertedFns.forEach(expressions.registerFunction); - convertedTypes.forEach(vis => + convertedTypes.forEach((vis) => visualizations.createBaseVisualization(vis(visualizationDependencies)) ); } // Register non-converted types vislibFns.forEach(expressions.registerFunction); - vislibTypes.forEach(vis => + vislibTypes.forEach((vis) => visualizations.createBaseVisualization(vis(visualizationDependencies)) ); } diff --git a/src/plugins/vis_type_vislib/public/vis_controller.tsx b/src/plugins/vis_type_vislib/public/vis_controller.tsx index 65acc08b58da0..262290b071abc 100644 --- a/src/plugins/vis_type_vislib/public/vis_controller.tsx +++ b/src/plugins/vis_type_vislib/public/vis_controller.tsx @@ -72,7 +72,7 @@ export const createVislibVisController = (deps: VisTypeVislibDependencies) => { this.destroy(); } - return new Promise(async resolve => { + return new Promise(async (resolve) => { if (this.el.clientWidth === 0 || this.el.clientHeight === 0) { return resolve(); } diff --git a/src/plugins/vis_type_vislib/public/vislib/components/labels/flatten_series.js b/src/plugins/vis_type_vislib/public/vislib/components/labels/flatten_series.js index bc51beb9c0818..87477332f76e5 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/labels/flatten_series.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/labels/flatten_series.js @@ -30,8 +30,5 @@ export function flattenSeries(obj) { obj = obj.rows ? obj.rows : obj.columns; - return _.chain(obj) - .pluck('series') - .flattenDeep() - .value(); + return _.chain(obj).pluck('series').flattenDeep().value(); } diff --git a/src/plugins/vis_type_vislib/public/vislib/components/labels/labels.test.js b/src/plugins/vis_type_vislib/public/vislib/components/labels/labels.test.js index 838275d44d2a1..5e78637ef0c02 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/labels/labels.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/labels/labels.test.js @@ -157,9 +157,9 @@ const columnsData = { ], }; -describe('Vislib Labels Module Test Suite', function() { +describe('Vislib Labels Module Test Suite', function () { let uniqSeriesLabels; - describe('Labels (main)', function() { + describe('Labels (main)', function () { beforeEach(() => { seriesLabels = labels(seriesData); rowsLabels = labels(rowsData); @@ -173,32 +173,32 @@ describe('Vislib Labels Module Test Suite', function() { .value(); }); - it('should be a function', function() { + it('should be a function', function () { expect(typeof labels).toBe('function'); }); - it('should return an array if input is data.series', function() { + it('should return an array if input is data.series', function () { expect(seriesArr).toBe(true); }); - it('should return an array if input is data.rows', function() { + it('should return an array if input is data.rows', function () { expect(rowsArr).toBe(true); }); - it('should throw an error if input is not an object', function() { - expect(function() { + it('should throw an error if input is not an object', function () { + expect(function () { labels('string not object'); }).toThrow(); }); - it('should return unique label values', function() { + it('should return unique label values', function () { expect(rowsLabels[0]).toEqual(uniqSeriesLabels[0]); expect(rowsLabels[1]).toEqual(uniqSeriesLabels[1]); expect(rowsLabels[2]).toEqual(uniqSeriesLabels[2]); }); }); - describe('Data array', function() { + describe('Data array', function () { const childrenObject = { children: [], }; @@ -227,36 +227,36 @@ describe('Vislib Labels Module Test Suite', function() { testRows = Array.isArray(rowsLabels); }); - it('should throw an error if the input is not an object', function() { - expect(function() { + it('should throw an error if the input is not an object', function () { + expect(function () { dataArray(string); }).toThrow(); - expect(function() { + expect(function () { dataArray(number); }).toThrow(); - expect(function() { + expect(function () { dataArray(boolean); }).toThrow(); - expect(function() { + expect(function () { dataArray(emptyArray); }).toThrow(); - expect(function() { + expect(function () { dataArray(nullValue); }).toThrow(); - expect(function() { + expect(function () { dataArray(notAValue); }).toThrow(); }); it( 'should throw an error if property series, rows, or ' + 'columns is not present', - function() { - expect(function() { + function () { + expect(function () { dataArray(childrenObject); }).toThrow(); } @@ -264,49 +264,49 @@ describe('Vislib Labels Module Test Suite', function() { it( 'should not throw an error if object has property series, rows, or ' + 'columns', - function() { - expect(function() { + function () { + expect(function () { dataArray(seriesObject); }).not.toThrow(); - expect(function() { + expect(function () { dataArray(rowsObject); }).not.toThrow(); - expect(function() { + expect(function () { dataArray(columnsObject); }).not.toThrow(); } ); - it('should be a function', function() { + it('should be a function', function () { expect(typeof dataArray).toEqual('function'); }); - it('should return an array of objects if input is data.series', function() { + it('should return an array of objects if input is data.series', function () { expect(testSeries).toEqual(true); }); - it('should return an array of objects if input is data.rows', function() { + it('should return an array of objects if input is data.rows', function () { expect(testRows).toEqual(true); }); - it('should return an array of same length as input data.series', function() { + it('should return an array of same length as input data.series', function () { expect(seriesLabels.length).toEqual(seriesData.series.length); }); - it('should return an array of same length as input data.rows', function() { + it('should return an array of same length as input data.rows', function () { expect(rowsLabels.length).toEqual(rowsData.rows.length); }); - it('should return an array of objects with obj.labels and obj.values', function() { + it('should return an array of objects with obj.labels and obj.values', function () { expect(seriesLabels[0].label).toEqual('100'); expect(seriesLabels[0].values[0].x).toEqual(0); expect(seriesLabels[0].values[0].y).toEqual(1); }); }); - describe('Unique labels', function() { + describe('Unique labels', function () { const arrObj = [ { label: 'a' }, { label: 'b' }, @@ -327,58 +327,58 @@ describe('Vislib Labels Module Test Suite', function() { let testArr; beforeEach(() => { - uniq = uniqLabels(arrObj, function(d) { + uniq = uniqLabels(arrObj, function (d) { return d; }); testArr = Array.isArray(uniq); }); - it('should throw an error if input is not an array', function() { - expect(function() { + it('should throw an error if input is not an array', function () { + expect(function () { uniqLabels(string); }).toThrow(); - expect(function() { + expect(function () { uniqLabels(number); }).toThrow(); - expect(function() { + expect(function () { uniqLabels(boolean); }).toThrow(); - expect(function() { + expect(function () { uniqLabels(nullValue); }).toThrow(); - expect(function() { + expect(function () { uniqLabels(emptyObject); }).toThrow(); - expect(function() { + expect(function () { uniqLabels(notAValue); }).toThrow(); }); - it('should not throw an error if the input is an array', function() { - expect(function() { + it('should not throw an error if the input is an array', function () { + expect(function () { uniqLabels(emptyArray); }).not.toThrow(); }); - it('should be a function', function() { + it('should be a function', function () { expect(typeof uniqLabels).toBe('function'); }); - it('should return an array', function() { + it('should return an array', function () { expect(testArr).toBe(true); }); - it('should return array of 5 unique values', function() { + it('should return array of 5 unique values', function () { expect(uniq.length).toBe(5); }); }); - describe('Get series', function() { + describe('Get series', function () { const string = 'string'; const number = 24; const boolean = false; @@ -404,65 +404,65 @@ describe('Vislib Labels Module Test Suite', function() { rowsArr = Array.isArray(rowsLabels); }); - it('should throw an error if input is not an object', function() { - expect(function() { + it('should throw an error if input is not an object', function () { + expect(function () { getSeries(string); }).toThrow(); - expect(function() { + expect(function () { getSeries(number); }).toThrow(); - expect(function() { + expect(function () { getSeries(boolean); }).toThrow(); - expect(function() { + expect(function () { getSeries(nullValue); }).toThrow(); - expect(function() { + expect(function () { getSeries(emptyArray); }).toThrow(); - expect(function() { + expect(function () { getSeries(notAValue); }).toThrow(); }); - it('should throw an if property rows or columns is not set on the object', function() { - expect(function() { + it('should throw an if property rows or columns is not set on the object', function () { + expect(function () { getSeries(emptyObject); }).toThrow(); }); - it('should not throw an error if rows or columns set on object', function() { - expect(function() { + it('should not throw an error if rows or columns set on object', function () { + expect(function () { getSeries(rowsObject); }).not.toThrow(); - expect(function() { + expect(function () { getSeries(columnsObject); }).not.toThrow(); }); - it('should be a function', function() { + it('should be a function', function () { expect(typeof getSeries).toBe('function'); }); - it('should return an array if input is data.columns', function() { + it('should return an array if input is data.columns', function () { expect(columnsArr).toBe(true); }); - it('should return an array if input is data.rows', function() { + it('should return an array if input is data.rows', function () { expect(rowsArr).toBe(true); }); - it('should return an array of the same length as as input data.columns', function() { + it('should return an array of the same length as as input data.columns', function () { expect(columnsLabels.length).toBe(columnsData.columns.length); }); - it('should return an array of the same length as as input data.rows', function() { + it('should return an array of the same length as as input data.rows', function () { expect(rowsLabels.length).toBe(rowsData.rows.length); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/components/labels/truncate_labels.js b/src/plugins/vis_type_vislib/public/vislib/components/labels/truncate_labels.js index 679a38a540416..daf802b844327 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/labels/truncate_labels.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/labels/truncate_labels.js @@ -26,7 +26,7 @@ import d3 from 'd3'; * @param size (number of characters to leave) * @returns {text} the updated text */ -const truncateLabel = function(text, size) { +const truncateLabel = function (text, size) { const node = d3.select(text).node(); const str = $(node).text(); if (size === 0) return str; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/labels/uniq_labels.js b/src/plugins/vis_type_vislib/public/vislib/components/labels/uniq_labels.js index bf42949afc03d..489cb81306b3d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/labels/uniq_labels.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/labels/uniq_labels.js @@ -28,8 +28,5 @@ export function uniqLabels(arr) { throw new TypeError('UniqLabelUtil expects an array of objects'); } - return _(arr) - .pluck('label') - .unique() - .value(); + return _(arr).pluck('label').unique().value(); } diff --git a/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.tsx b/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.tsx index 7eb25e3930718..a2fe4d9249bd0 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.tsx +++ b/src/plugins/vis_type_vislib/public/vislib/components/legend/legend.tsx @@ -117,7 +117,7 @@ export class VisLegend extends PureComponent { }; getSeriesLabels = (data: any[]) => { - const values = data.map(chart => chart.series).reduce((a, b) => a.concat(b), []); + const values = data.map((chart) => chart.series).reduce((a, b) => a.concat(b), []); return compact(uniq(values, 'label')).map((label: any) => ({ ...label, @@ -126,9 +126,9 @@ export class VisLegend extends PureComponent { }; setFilterableLabels = (items: LegendItem[]): Promise => - new Promise(async resolve => { + new Promise(async (resolve) => { const filterableLabels = new Set(); - items.forEach(async item => { + items.forEach(async (item) => { const canFilter = await this.canFilter(item); if (canFilter) { filterableLabels.add(item.label); @@ -143,7 +143,7 @@ export class VisLegend extends PureComponent { if (CUSTOM_LEGEND_VIS_TYPES.includes(type)) { const legendLabels = this.props.vislibVis.getLegendLabels(); if (legendLabels) { - labels = map(legendLabels, label => { + labels = map(legendLabels, (label) => { return { label }; }); } @@ -229,7 +229,7 @@ export class VisLegend extends PureComponent { renderLegend = (anchorPosition: EuiPopoverProps['anchorPosition']) => (
    - {this.state.labels.map(item => ( + {this.state.labels.map((item) => ( - {legendColors.map(color => ( + {legendColors.map((color) => ( serie.rawId === datum.seriesId); + const currentSeries = + data.series && data.series.find((serie) => serie.rawId === datum.seriesId); const addDetail = (label, value) => details.push({ label, value }); if (datum.extraMetrics) { - datum.extraMetrics.forEach(metric => { + datum.extraMetrics.forEach((metric) => { addDetail(metric.label, metric.value); }); } diff --git a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/_pointseries_tooltip_formatter.test.js b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/_pointseries_tooltip_formatter.test.js index 953c115cc0d02..c01e32abb8dcb 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/_pointseries_tooltip_formatter.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/_pointseries_tooltip_formatter.test.js @@ -22,14 +22,11 @@ import $ from 'jquery'; import { pointSeriesTooltipFormatter } from './_pointseries_tooltip_formatter'; -describe('tooltipFormatter', function() { +describe('tooltipFormatter', function () { const tooltipFormatter = pointSeriesTooltipFormatter(); function cell($row, i) { - return $row - .eq(i) - .text() - .trim(); + return $row.eq(i).text().trim(); } const baseEvent = { @@ -59,7 +56,7 @@ describe('tooltipFormatter', function() { }, }; - it('returns html based on the mouse event', function() { + it('returns html based on the mouse event', function () { const event = _.cloneDeep(baseEvent); const $el = $(tooltipFormatter(event)); const $rows = $el.find('tr'); @@ -78,7 +75,7 @@ describe('tooltipFormatter', function() { expect(cell($row3, 1)).toBe('1'); }); - it('renders correctly on missing extraMetrics in datum', function() { + it('renders correctly on missing extraMetrics in datum', function () { const event = _.cloneDeep(baseEvent); delete event.datum.extraMetrics; const $el = $(tooltipFormatter(event)); diff --git a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.js b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.js index 9097e4db42473..e22105d5a086f 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.js @@ -90,11 +90,11 @@ function getOverflow(size, pos, containers) { containers .map(getBounds) - .sort(function(a, b) { + .sort(function (a, b) { // ensure smallest containers are merged first return a.area - b.area; }) - .forEach(function(bounds) { + .forEach(function (bounds) { // number of pixels that the tooltip would overflow it's far // side, if we placed it that way. (negative === no overflow) mergeOverflows(overflow, { @@ -110,7 +110,7 @@ function getOverflow(size, pos, containers) { } function mergeOverflows(dest, src) { - _.merge(dest, src, function(a, b) { + _.merge(dest, src, function (a, b) { if (a == null || b == null) return a || b; if (a < 0 && b < 0) return Math.min(a, b); return Math.max(a, b); @@ -176,7 +176,7 @@ positionTooltip.getBasePosition = getBasePosition; positionTooltip.getOverflow = getOverflow; positionTooltip.getBounds = getBounds; positionTooltip.placeToAvoidOverflow = placeToAvoidOverflow; -positionTooltip.removeClone = function() { +positionTooltip.removeClone = function () { $clone && $clone.remove(); $clone = null; }; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.test.js b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.test.js index c184d0e9fbcf7..85954aa9393e3 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/position_tooltip.test.js @@ -23,7 +23,7 @@ import sinon from 'sinon'; import { positionTooltip } from './position_tooltip'; -describe('Tooltip Positioning', function() { +describe('Tooltip Positioning', function () { const sandbox = sinon.createSandbox(); const positions = ['north', 'south', 'east', 'west']; const bounds = ['top', 'left', 'bottom', 'right', 'area']; @@ -57,7 +57,7 @@ describe('Tooltip Positioning', function() { return $el; } - beforeEach(function() { + beforeEach(function () { $window = testEl( [500, 1000], [600, 800], @@ -67,7 +67,7 @@ describe('Tooltip Positioning', function() { $sizer = $tooltip.clone().appendTo($window); }); - afterEach(function() { + afterEach(function () { $window.remove(); $window = $chart = $tooltip = $sizer = null; positionTooltip.removeClone(); @@ -86,16 +86,16 @@ describe('Tooltip Positioning', function() { }; } - describe('getTtSize()', function() { - it('should measure the outer-size of the tooltip using an un-obstructed clone', function() { + describe('getTtSize()', function () { + it('should measure the outer-size of the tooltip using an un-obstructed clone', function () { const w = sandbox.spy($.fn, 'outerWidth'); const h = sandbox.spy($.fn, 'outerHeight'); positionTooltip.getTtSize($tooltip.html(), $sizer); - [w, h].forEach(function(spy) { + [w, h].forEach(function (spy) { expect(spy).toHaveProperty('callCount', 1); - const matchHtml = w.thisValues.filter(function($t) { + const matchHtml = w.thisValues.filter(function ($t) { return !$t.is($tooltip) && $t.html() === $tooltip.html(); }); expect(matchHtml).toHaveLength(1); @@ -103,12 +103,12 @@ describe('Tooltip Positioning', function() { }); }); - describe('getBasePosition()', function() { - it('calculates the offset values for the four positions', function() { + describe('getBasePosition()', function () { + it('calculates the offset values for the four positions', function () { const size = positionTooltip.getTtSize($tooltip.html(), $sizer); const pos = positionTooltip.getBasePosition(size, makeEvent()); - positions.forEach(function(p) { + positions.forEach(function (p) { expect(pos).toHaveProperty(p); }); @@ -117,11 +117,11 @@ describe('Tooltip Positioning', function() { }); }); - describe('getBounds()', function() { - it('returns the offsets for the tlrb of the element', function() { + describe('getBounds()', function () { + it('returns the offsets for the tlrb of the element', function () { const cbounds = positionTooltip.getBounds($chart); - bounds.forEach(function(b) { + bounds.forEach(function (b) { expect(cbounds).toHaveProperty(b); }); @@ -130,8 +130,8 @@ describe('Tooltip Positioning', function() { }); }); - describe('getOverflow()', function() { - it('determines how much the base placement overflows the containing bounds in each direction', function() { + describe('getOverflow()', function () { + it('determines how much the base placement overflows the containing bounds in each direction', function () { // size the tooltip very small so it won't collide with the edges $tooltip.css({ width: 15, height: 15 }); $sizer.css({ width: 15, height: 15 }); @@ -143,7 +143,7 @@ describe('Tooltip Positioning', function() { const pos = positionTooltip.getBasePosition(size, makeEvent(0.5, 0.5)); const overflow = positionTooltip.getOverflow(size, pos, [$chart, $window]); - positions.forEach(function(p) { + positions.forEach(function (p) { expect(overflow).toHaveProperty(p); // all positions should be less than 0 because the tooltip is so much smaller than the chart @@ -151,14 +151,14 @@ describe('Tooltip Positioning', function() { }); }); - it('identifies an overflow with a positive value in that direction', function() { + it('identifies an overflow with a positive value in that direction', function () { const size = positionTooltip.getTtSize($tooltip.html(), $sizer); // position the element based on a mouse that is in the bottom right hand corner of the chart const pos = positionTooltip.getBasePosition(size, makeEvent(0.99, 0.99)); const overflow = positionTooltip.getOverflow(size, pos, [$chart, $window]); - positions.forEach(function(p) { + positions.forEach(function (p) { expect(overflow).toHaveProperty(p); if (p === 'south' || p === 'east') { @@ -169,7 +169,7 @@ describe('Tooltip Positioning', function() { }); }); - it('identifies only right overflow when tooltip overflows both sides of inner container but outer contains tooltip', function() { + it('identifies only right overflow when tooltip overflows both sides of inner container but outer contains tooltip', function () { // Size $tooltip larger than chart const largeWidth = $chart.width() + 10; $tooltip.css({ width: largeWidth }); @@ -195,8 +195,8 @@ describe('Tooltip Positioning', function() { }); }); - describe('positionTooltip() integration', function() { - it('returns nothing if the $chart or $tooltip are not passed in', function() { + describe('positionTooltip() integration', function () { + it('returns nothing if the $chart or $tooltip are not passed in', function () { expect(positionTooltip() === void 0).toBe(true); expect(positionTooltip(null, null, null) === void 0).toBe(true); expect(positionTooltip(null, $(), $()) === void 0).toBe(true); @@ -217,7 +217,7 @@ describe('Tooltip Positioning', function() { expect(placement).toHaveProperty('top'); expect(placement).toHaveProperty('left'); - directions.forEach(function(dir) { + directions.forEach(function (dir) { switch (dir) { case 'top': expect(placement.top).toBeLessThan(event.clientY); @@ -237,35 +237,35 @@ describe('Tooltip Positioning', function() { return placement; } - describe('calculates placement of the tooltip properly', function() { - it('mouse is in the middle', function() { + describe('calculates placement of the tooltip properly', function () { + it('mouse is in the middle', function () { check(0.5, 0.5, 'bottom', 'right'); }); - it('mouse is in the top left', function() { + it('mouse is in the top left', function () { check(0.1, 0.1, 'bottom', 'right'); }); - it('mouse is in the top right', function() { + it('mouse is in the top right', function () { check(0.99, 0.1, 'bottom', 'left'); }); - it('mouse is in the bottom right', function() { + it('mouse is in the bottom right', function () { check(0.99, 0.99, 'top', 'left'); }); - it('mouse is in the bottom left', function() { + it('mouse is in the bottom left', function () { check(0.1, 0.99, 'top', 'right'); }); }); - describe('maintain the direction of the tooltip on reposition', function() { - it('mouse moves from the top right to the middle', function() { + describe('maintain the direction of the tooltip on reposition', function () { + it('mouse moves from the top right to the middle', function () { const pos = check(0.99, 0.1, 'bottom', 'left'); check(0.5, 0.5, pos, 'bottom', 'left'); }); - it('mouse moves from the bottom left to the middle', function() { + it('mouse moves from the bottom left to the middle', function () { const pos = check(0.1, 0.99, 'top', 'right'); check(0.5, 0.5, pos, 'top', 'right'); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/tooltip.js b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/tooltip.js index 2c482db0a9dd9..0bfcedc5e6055 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/tooltip/tooltip.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/tooltip/tooltip.js @@ -63,10 +63,8 @@ export function Tooltip(id, el, formatter, events) { * * @return {Object} jQuery node object */ -Tooltip.prototype.$get = _.once(function() { - return $('
    ') - .addClass(this.tooltipClass) - .appendTo(document.body); +Tooltip.prototype.$get = _.once(function () { + return $('
    ').addClass(this.tooltipClass).appendTo(document.body); }); /** @@ -74,7 +72,7 @@ Tooltip.prototype.$get = _.once(function() { * * @return {Object} jQuery node object */ -Tooltip.prototype.$getSizer = _.once(function() { +Tooltip.prototype.$getSizer = _.once(function () { return this.$get() .clone() .removeClass(this.tooltipClass) @@ -85,7 +83,7 @@ Tooltip.prototype.$getSizer = _.once(function() { /** * Show the tooltip, positioning it based on the content and chart container */ -Tooltip.prototype.show = function() { +Tooltip.prototype.show = function () { const $tooltip = this.$get(); const $chart = this.$getChart(); const html = $tooltip.html(); @@ -154,7 +152,7 @@ Tooltip.prototype.show = function() { /** * Hide the tooltip, clearing its contents */ -Tooltip.prototype.hide = function() { +Tooltip.prototype.hide = function () { const $tooltip = this.$get(); allContents = []; $tooltip.css({ @@ -170,7 +168,7 @@ Tooltip.prototype.hide = function() { * * @return {Object} jQuery node for the chart */ -Tooltip.prototype.$getChart = function() { +Tooltip.prototype.$getChart = function () { const chart = $(this.container && this.container.node()); return chart.length ? chart : false; }; @@ -181,7 +179,7 @@ Tooltip.prototype.$getChart = function() { * @method render * @return {Function} Renders tooltip on a D3 selection */ -Tooltip.prototype.render = function() { +Tooltip.prototype.render = function () { const self = this; /** @@ -189,7 +187,7 @@ Tooltip.prototype.render = function() { * * @param {Object} selection D3 selection object */ - return function(selection) { + return function (selection) { const $tooltip = self.$get(); const id = self.id; const order = self.order; @@ -203,28 +201,24 @@ Tooltip.prototype.render = function() { const $chart = self.$getChart(); if ($chart) { - self.binder.jqOn($chart, 'mouseleave', function() { + self.binder.jqOn($chart, 'mouseleave', function () { // only clear when we leave the chart, so that // moving between points doesn't make it reposition $chart.removeData('previousPlacement'); }); } - selection.each(function(d, i) { + selection.each(function (d, i) { const element = d3.select(this); function render(html) { - allContents = _.filter(allContents, function(content) { + allContents = _.filter(allContents, function (content) { return content.id !== id; }); if (html) allContents.push({ id, html, order }); - const allHtml = _(allContents) - .sortBy('order') - .pluck('html') - .compact() - .join('\n'); + const allHtml = _(allContents).sortBy('order').pluck('html').compact().join('\n'); if (allHtml) { $tooltip.html(allHtml); @@ -234,7 +228,7 @@ Tooltip.prototype.render = function() { } } - self.binder.fakeD3Bind(this, 'mousemove', function() { + self.binder.fakeD3Bind(this, 'mousemove', function () { if (!self.showCondition.call(element, d, i)) { return render(); } @@ -243,14 +237,14 @@ Tooltip.prototype.render = function() { return render(self.formatter(events)); }); - self.binder.fakeD3Bind(this, 'mouseleave', function() { + self.binder.fakeD3Bind(this, 'mouseleave', function () { render(); }); }); }; }; -Tooltip.prototype.destroy = function() { +Tooltip.prototype.destroy = function () { this.hide(); this.binder.destroy(); }; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/inject_zeros.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/inject_zeros.js index 6320586765761..9b48b53345a8a 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/inject_zeros.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/inject_zeros.js @@ -35,7 +35,7 @@ import { zeroFillDataArray } from './zero_fill_data_array'; export function injectZeros(obj, data, orderBucketsBySum = false) { const keys = orderXValues(data, orderBucketsBySum); - obj.forEach(function(series) { + obj.forEach(function (series) { const zeroArray = createZeroFilledArray(keys, series.label); series.values = zeroFillDataArray(zeroArray, series.values); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/ordered_x_keys.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/ordered_x_keys.js index 206ad8bb14b85..e9f75e64c1d3d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/ordered_x_keys.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/ordered_x_keys.js @@ -39,13 +39,13 @@ export function orderXValues(obj, orderBucketsBySum = false) { const dateInterval = moment.isDuration(interval) ? interval : false; return _(uniqKeysPairs) - .sortBy(function(d) { + .sortBy(function (d) { if (d[1].isDate || d[1].isOrdered) { return +d[0]; } return orderBucketsBySum ? -d[1].sum : d[1].index; }) - .map(function(d, i, list) { + .map(function (d, i, list) { if (!d[1].isNumber) return d[0]; const val = +d[0]; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/uniq_keys.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/uniq_keys.js index 5d9cddc448e54..8854fb13e4e90 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/uniq_keys.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/uniq_keys.js @@ -41,11 +41,11 @@ export function getUniqKeys(obj) { charts = [obj]; } - const isDate = charts.every(chart => { + const isDate = charts.every((chart) => { return chart.ordered && chart.ordered.date; }); - const isOrdered = charts.every(chart => { + const isOrdered = charts.every((chart) => { return chart.ordered; }); @@ -68,7 +68,7 @@ export function getUniqKeys(obj) { } // Generate a sum for each value - flattenedData.forEach(d => { + flattenedData.forEach((d) => { const key = d.x; let prev = uniqueXValues.get(key); if (!prev) { diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_fill_data_array.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_fill_data_array.js index 7f432569c1b88..90c8f6ca052fb 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_fill_data_array.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_fill_data_array.js @@ -35,7 +35,7 @@ export function zeroFillDataArray(arr1, arr2) { let index; const max = arr2.length; - const getX = function(d) { + const getX = function (d) { return d.x === val.x; }; diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_filled_array.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_filled_array.js index 7fa138521f6ad..84093c42e7cfd 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_filled_array.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_filled_array.js @@ -28,7 +28,7 @@ export function createZeroFilledArray(arr, label) { const zeroFilledArray = []; - arr.forEach(function(val) { + arr.forEach(function (val) { zeroFilledArray.push({ x: val, xi: Infinity, diff --git a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_injection.test.js b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_injection.test.js index df502b7cde3df..23096b164b452 100644 --- a/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_injection.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/components/zero_injection/zero_injection.test.js @@ -25,7 +25,7 @@ import { flattenData } from './flatten_data'; import { createZeroFilledArray } from './zero_filled_array'; import { zeroFillDataArray } from './zero_fill_data_array'; -describe('Vislib Zero Injection Module Test Suite', function() { +describe('Vislib Zero Injection Module Test Suite', function () { const dateHistogramRowsObj = { xAxisOrderedValues: [ 1418410560000, @@ -146,7 +146,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { const emptyArray = []; let notAValue; - describe('Zero Injection (main)', function() { + describe('Zero Injection (main)', function () { let sample1; let sample2; let sample3; @@ -157,16 +157,16 @@ describe('Vislib Zero Injection Module Test Suite', function() { sample3 = injectZeros(multiSeriesNumberedData, multiSeriesNumberedDataObj); }); - it('should be a function', function() { + it('should be a function', function () { expect(_.isFunction(injectZeros)).toBe(true); }); - it('should return an object with series[0].values', function() { + it('should return an object with series[0].values', function () { expect(_.isObject(sample1)).toBe(true); expect(_.isObject(sample1[0].values)).toBe(true); }); - it('should return the same array of objects when the length of the series array is 1', function() { + it('should return the same array of objects when the length of the series array is 1', function () { expect(sample1[0].values[0].x).toBe(seriesData[0].values[0].x); expect(sample1[0].values[1].x).toBe(seriesData[0].values[1].x); expect(sample1[0].values[2].x).toBe(seriesData[0].values[2].x); @@ -174,7 +174,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(sample1[0].values[4].x).toBe(seriesData[0].values[4].x); }); - it('should inject zeros in the input array', function() { + it('should inject zeros in the input array', function () { expect(sample2[1].values[1].y).toBe(0); expect(sample2[2].values[0].y).toBe(0); expect(sample2[2].values[1].y).toBe(0); @@ -185,7 +185,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(sample3[2].values[4].y).toBe(0); }); - it('should return values arrays with the same x values', function() { + it('should return values arrays with the same x values', function () { expect(sample2[1].values[0].x).toBe(sample2[2].values[0].x); expect(sample2[1].values[1].x).toBe(sample2[2].values[1].x); expect(sample2[1].values[2].x).toBe(sample2[2].values[2].x); @@ -193,14 +193,14 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(sample2[1].values[4].x).toBe(sample2[2].values[4].x); }); - it('should return values arrays of the same length', function() { + it('should return values arrays of the same length', function () { expect(sample2[0].values.length).toBe(sample2[1].values.length); expect(sample2[0].values.length).toBe(sample2[2].values.length); expect(sample2[1].values.length).toBe(sample2[2].values.length); }); }); - describe('Order X Values', function() { + describe('Order X Values', function () { let results; let numberedResults; @@ -209,15 +209,15 @@ describe('Vislib Zero Injection Module Test Suite', function() { numberedResults = orderXValues(multiSeriesNumberedDataObj); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(orderXValues)).toBe(true); }); - it('should return an array', function() { + it('should return an array', function () { expect(Array.isArray(results)).toBe(true); }); - it('should return an array of values ordered by their index by default', function() { + it('should return an array of values ordered by their index by default', function () { expect(results[0]).toBe('1'); expect(results[1]).toBe('2'); expect(results[2]).toBe('3'); @@ -230,7 +230,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(numberedResults[4]).toBe(5); }); - it('should return an array of values that preserve the index from xAxisOrderedValues', function() { + it('should return an array of values that preserve the index from xAxisOrderedValues', function () { const data = { xAxisOrderedValues: ['1', '2', '3', '4', '5'], series: [ @@ -259,7 +259,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(result).toEqual(['1', '2', '3', '4', '5']); }); - it('should return an array of values ordered by their sum when orderBucketsBySum is true', function() { + it('should return an array of values ordered by their sum when orderBucketsBySum is true', function () { const orderBucketsBySum = true; results = orderXValues(multiSeriesDataObj, orderBucketsBySum); numberedResults = orderXValues(multiSeriesNumberedDataObj, orderBucketsBySum); @@ -277,75 +277,75 @@ describe('Vislib Zero Injection Module Test Suite', function() { }); }); - describe('Unique Keys', function() { + describe('Unique Keys', function () { let results; beforeEach(() => { results = getUniqKeys(multiSeriesDataObj); }); - it('should throw an error if input is not an object', function() { - expect(function() { + it('should throw an error if input is not an object', function () { + expect(function () { getUniqKeys(str); }).toThrow(); - expect(function() { + expect(function () { getUniqKeys(number); }).toThrow(); - expect(function() { + expect(function () { getUniqKeys(boolean); }).toThrow(); - expect(function() { + expect(function () { getUniqKeys(nullValue); }).toThrow(); - expect(function() { + expect(function () { getUniqKeys(emptyArray); }).toThrow(); - expect(function() { + expect(function () { getUniqKeys(notAValue); }).toThrow(); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(getUniqKeys)).toBe(true); }); - it('should return an object', function() { + it('should return an object', function () { expect(_.isObject(results)).toBe(true); }); - it('should return an object of unique keys', function() { + it('should return an object of unique keys', function () { expect(_.uniq(_.keys(results)).length).toBe(_.keys(results).length); }); }); - describe('Flatten Data', function() { + describe('Flatten Data', function () { let results; beforeEach(() => { results = flattenData(multiSeriesDataObj); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(flattenData)).toBe(true); }); - it('should return an array', function() { + it('should return an array', function () { expect(Array.isArray(results)).toBe(true); }); - it('should return an array of objects', function() { + it('should return an array of objects', function () { expect(_.isObject(results[0])).toBe(true); expect(_.isObject(results[1])).toBe(true); expect(_.isObject(results[2])).toBe(true); }); }); - describe('Zero Filled Array', function() { + describe('Zero Filled Array', function () { const arr1 = [1, 2, 3, 4, 5]; const arr2 = ['1', '2', '3', '4', '5']; let results1; @@ -356,41 +356,41 @@ describe('Vislib Zero Injection Module Test Suite', function() { results2 = createZeroFilledArray(arr2); }); - it('should throw an error if input is not an array', function() { - expect(function() { + it('should throw an error if input is not an array', function () { + expect(function () { createZeroFilledArray(str); }).toThrow(); - expect(function() { + expect(function () { createZeroFilledArray(number); }).toThrow(); - expect(function() { + expect(function () { createZeroFilledArray(boolean); }).toThrow(); - expect(function() { + expect(function () { createZeroFilledArray(nullValue); }).toThrow(); - expect(function() { + expect(function () { createZeroFilledArray(emptyObject); }).toThrow(); - expect(function() { + expect(function () { createZeroFilledArray(notAValue); }).toThrow(); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(createZeroFilledArray)).toBe(true); }); - it('should return an array', function() { + it('should return an array', function () { expect(Array.isArray(results1)).toBe(true); }); - it('should return an array of objects', function() { + it('should return an array of objects', function () { expect(_.isObject(results1[0])).toBe(true); expect(_.isObject(results1[1])).toBe(true); expect(_.isObject(results1[2])).toBe(true); @@ -398,7 +398,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(_.isObject(results1[4])).toBe(true); }); - it('should return an array of objects where each y value is 0', function() { + it('should return an array of objects where each y value is 0', function () { expect(results1[0].y).toBe(0); expect(results1[1].y).toBe(0); expect(results1[2].y).toBe(0); @@ -406,7 +406,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(results1[4].y).toBe(0); }); - it('should return an array of objects where each x values are numbers', function() { + it('should return an array of objects where each x values are numbers', function () { expect(_.isNumber(results1[0].x)).toBe(true); expect(_.isNumber(results1[1].x)).toBe(true); expect(_.isNumber(results1[2].x)).toBe(true); @@ -414,7 +414,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { expect(_.isNumber(results1[4].x)).toBe(true); }); - it('should return an array of objects where each x values are strings', function() { + it('should return an array of objects where each x values are strings', function () { expect(_.isString(results2[0].x)).toBe(true); expect(_.isString(results2[1].x)).toBe(true); expect(_.isString(results2[2].x)).toBe(true); @@ -423,7 +423,7 @@ describe('Vislib Zero Injection Module Test Suite', function() { }); }); - describe('Zero Filled Data Array', function() { + describe('Zero Filled Data Array', function () { const xValueArr = [1, 2, 3, 4, 5]; let arr1; const arr2 = [{ x: 3, y: 834 }]; @@ -435,47 +435,47 @@ describe('Vislib Zero Injection Module Test Suite', function() { results = zeroFillDataArray(arr1, arr2); }); - it('should throw an error if input are not arrays', function() { - expect(function() { + it('should throw an error if input are not arrays', function () { + expect(function () { zeroFillDataArray(str, str); }).toThrow(); - expect(function() { + expect(function () { zeroFillDataArray(number, number); }).toThrow(); - expect(function() { + expect(function () { zeroFillDataArray(boolean, boolean); }).toThrow(); - expect(function() { + expect(function () { zeroFillDataArray(nullValue, nullValue); }).toThrow(); - expect(function() { + expect(function () { zeroFillDataArray(emptyObject, emptyObject); }).toThrow(); - expect(function() { + expect(function () { zeroFillDataArray(notAValue, notAValue); }).toThrow(); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(zeroFillDataArray)).toBe(true); }); - it('should return an array', function() { + it('should return an array', function () { expect(Array.isArray(results)).toBe(true); }); - it('should return an array of objects', function() { + it('should return an array of objects', function () { expect(_.isObject(results[0])).toBe(true); expect(_.isObject(results[1])).toBe(true); expect(_.isObject(results[2])).toBe(true); }); - it('should return an array with zeros injected in the appropriate objects as y values', function() { + it('should return an array with zeros injected in the appropriate objects as y values', function () { expect(results[0].y).toBe(0); expect(results[1].y).toBe(0); expect(results[3].y).toBe(0); @@ -483,20 +483,20 @@ describe('Vislib Zero Injection Module Test Suite', function() { }); }); - describe('Injected Zero values return in the correct order', function() { + describe('Injected Zero values return in the correct order', function () { let results; beforeEach(() => { results = injectZeros(dateHistogramRows, dateHistogramRowsObj); }); - it('should return an array of objects', function() { - results.forEach(function(row) { + it('should return an array of objects', function () { + results.forEach(function (row) { expect(Array.isArray(row.values)).toBe(true); }); }); - it('should return ordered x values', function() { + it('should return ordered x values', function () { const values = results[0].values; expect(values[0].x).toBeLessThan(values[1].x); expect(values[1].x).toBeLessThan(values[2].x); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.test.ts index 475555f3a15f3..7cef113ffc349 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.test.ts @@ -76,7 +76,7 @@ function tableVisResponseHandler(table: Table, dimensions: Dimensions) { jest.mock('../../../services', () => ({ getFormatService: jest.fn(() => ({ deserialize: () => ({ - convert: jest.fn(v => JSON.stringify(v)), + convert: jest.fn((v) => JSON.stringify(v)), }), })), })); @@ -238,7 +238,7 @@ describe('buildHierarchicalData convertTable', () => { }); it('should set the correct hits attribute for each of the results', () => { - tables.forEach(t => { + tables.forEach((t) => { const results = buildHierarchicalData(t.tables![0], dimensions); expect(results).toHaveProperty('hits'); expect(results.hits).toBe(4); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.ts index c3b82f72af482..3bc8fa0f035b6 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/hierarchical/build_hierarchical_data.ts @@ -70,7 +70,7 @@ export const buildHierarchicalData = (table: Table, { metric, buckets = [] }: Di let parent: Slice; let dataLevel = slices; - buckets.forEach(bucket => { + buckets.forEach((bucket) => { const bucketColumn = table.columns[bucket.accessor]; const bucketValueColumn = table.columns[bucket.accessor + 1]; const bucketFormatter = getFormatService().deserialize(bucket.format); @@ -78,7 +78,7 @@ export const buildHierarchicalData = (table: Table, { metric, buckets = [] }: Di const size = row[bucketValueColumn.id] as number; names[name] = name; - let slice = dataLevel.find(dataLevelSlice => dataLevelSlice.name === name); + let slice = dataLevel.find((dataLevelSlice) => dataLevelSlice.name === name); if (!slice) { slice = { name, diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_add_to_siri.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_add_to_siri.test.ts index e4fdd6bb71c00..ae6b365efc0cd 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_add_to_siri.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_add_to_siri.test.ts @@ -21,8 +21,8 @@ import { addToSiri, Serie } from './_add_to_siri'; import { Point } from './_get_point'; import { Dimension } from './point_series'; -describe('addToSiri', function() { - it('creates a new series the first time it sees an id', function() { +describe('addToSiri', function () { + it('creates a new series the first time it sees an id', function () { const series = new Map(); const point = {} as Point; const id = 'id'; @@ -36,7 +36,7 @@ describe('addToSiri', function() { expect(expectedSerie.values[0]).toBe(point); }); - it('adds points to existing series if id has been seen', function() { + it('adds points to existing series if id has been seen', function () { const series = new Map(); const id = 'id'; @@ -54,7 +54,7 @@ describe('addToSiri', function() { expect(series.get(id).values[1]).toBe(point2); }); - it('allows overriding the series label', function() { + it('allows overriding the series label', function () { const series = new Map(); const id = 'id'; const label = 'label'; @@ -68,7 +68,7 @@ describe('addToSiri', function() { expect(series.get(id).values[0]).toBe(point); }); - it('correctly sets id and rawId', function() { + it('correctly sets id and rawId', function () { const series = new Map(); const id = 'id-id2'; diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_fake_x_aspect.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_fake_x_aspect.test.ts index 43d4c3d7ca7c4..61c6a89a423b4 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_fake_x_aspect.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_fake_x_aspect.test.ts @@ -18,8 +18,8 @@ */ import { makeFakeXAspect } from './_fake_x_aspect'; -describe('makeFakeXAspect', function() { - it('creates an object that looks like an aspect', function() { +describe('makeFakeXAspect', function () { + it('creates an object that looks like an aspect', function () { const aspect = makeFakeXAspect(); expect(aspect).toHaveProperty('accessor', -1); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.test.ts index 450b283abbed2..fb14b04357f8f 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.test.ts @@ -21,7 +21,7 @@ import { getAspects } from './_get_aspects'; import { Dimension, Dimensions, Aspect } from './point_series'; import { Table, Row } from '../../types'; -describe('getAspects', function() { +describe('getAspects', function () { let table: Table; let dimensions: Dimensions; @@ -50,7 +50,7 @@ describe('getAspects', function() { } as Dimensions; } - it('produces an aspect object for each of the aspect types found in the columns', function() { + it('produces an aspect object for each of the aspect types found in the columns', function () { init(1, 0, 2); const aspects = getAspects(table, dimensions); @@ -59,7 +59,7 @@ describe('getAspects', function() { validate(aspects.y![0], '2'); }); - it('creates a fake x aspect if the column does not exist', function() { + it('creates a fake x aspect if the column does not exist', function () { init(0, null, 1); const aspects = getAspects(table, dimensions); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.ts index 29134409ddd5f..87819aa9b2a5c 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_aspects.ts @@ -30,10 +30,10 @@ import { Table } from '../../types'; */ export function getAspects(table: Table, dimensions: Dimensions) { const aspects: Partial = {}; - (Object.keys(dimensions) as Array).forEach(name => { + (Object.keys(dimensions) as Array).forEach((name) => { const dimension = dimensions[name]; const dimensionList = Array.isArray(dimension) ? dimension : [dimension]; - dimensionList.forEach(d => { + dimensionList.forEach((d) => { if (!d) { return; } diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.test.ts index dc10c9f4938a0..be44975bd4eb0 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.test.ts @@ -23,12 +23,12 @@ import { setFormatService } from '../../../services'; import { Aspect } from './point_series'; import { Table, Row, Column } from '../../types'; -describe('getPoint', function() { +describe('getPoint', function () { let deserialize: IFieldFormatsRegistry['deserialize']; beforeAll(() => { deserialize = jest.fn(() => ({ - convert: jest.fn(v => v), + convert: jest.fn((v) => v), })) as any; setFormatService({ @@ -44,17 +44,17 @@ describe('getPoint', function() { ], } as Table; - describe('Without series aspect', function() { + describe('Without series aspect', function () { let seriesAspect: undefined; let xAspect: Aspect; let yAspect: Aspect; - beforeEach(function() { + beforeEach(function () { xAspect = { accessor: '0' } as Aspect; yAspect = { accessor: '1', title: 'Y' } as Aspect; }); - it('properly unwraps values', function() { + it('properly unwraps values', function () { const row = table.rows[0]; const zAspect = { accessor: '2' } as Aspect; const point = getPoint(table, xAspect, seriesAspect, row, 0, yAspect, zAspect); @@ -65,25 +65,25 @@ describe('getPoint', function() { expect(point).toHaveProperty('series', yAspect.title); }); - it('ignores points with a y value of NaN', function() { + it('ignores points with a y value of NaN', function () { const row = table.rows[1]; const point = getPoint(table, xAspect, seriesAspect, row, 1, yAspect); expect(point).toBe(void 0); }); }); - describe('With series aspect', function() { + describe('With series aspect', function () { let row: Row; let xAspect: Aspect; let yAspect: Aspect; - beforeEach(function() { + beforeEach(function () { row = table.rows[0]; xAspect = { accessor: '0' } as Aspect; yAspect = { accessor: '2' } as Aspect; }); - it('properly unwraps values', function() { + it('properly unwraps values', function () { const seriesAspect = [{ accessor: '1' } as Aspect]; const point = getPoint(table, xAspect, seriesAspect, row, 0, yAspect); @@ -92,7 +92,7 @@ describe('getPoint', function() { expect(point).toHaveProperty('y', 3); }); - it('should call deserialize', function() { + it('should call deserialize', function () { const seriesAspect = [ { accessor: '1', format: { id: 'number', params: { pattern: '$' } } } as Aspect, ]; diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.ts index 3fc13eb0c04b5..5eb1e65965318 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_point.ts @@ -108,7 +108,7 @@ export function getPoint( if (series) { point.series = series - .map(s => { + .map((s) => { const fieldFormatter = getFormatService().deserialize(s.format); return fieldFormatter.convert(row[s.accessor]); }) diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.test.ts index 6b94b9de8e15f..9de0ed4921998 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.test.ts @@ -24,16 +24,16 @@ import { Table, Column } from '../../types'; import { Serie } from './_add_to_siri'; import { Point } from './_get_point'; -describe('getSeries', function() { +describe('getSeries', function () { beforeAll(() => { setFormatService({ deserialize: () => ({ - convert: jest.fn(v => v), + convert: jest.fn((v) => v), }), } as any); }); - it('produces a single series with points for each row', function() { + it('produces a single series with points for each row', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -67,14 +67,14 @@ describe('getSeries', function() { expect(siri.values).toEqual(expect.any(Array)); expect(siri.values).toHaveLength(5); - siri.values.forEach(point => { + siri.values.forEach((point) => { expect(point).toHaveProperty('x', 1); expect(point).toHaveProperty('y', 2); expect(point).toHaveProperty('z', 3); }); }); - it('adds the seriesId to each point', function() { + it('adds the seriesId to each point', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -98,16 +98,16 @@ describe('getSeries', function() { const series = getSeries(table, chart); - series[0].values.forEach(point => { + series[0].values.forEach((point) => { expect(point).toHaveProperty('seriesId', '1'); }); - series[1].values.forEach(point => { + series[1].values.forEach((point) => { expect(point).toHaveProperty('seriesId', '2'); }); }); - it('produces multiple series if there are multiple y aspects', function() { + it('produces multiple series if there are multiple y aspects', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -134,7 +134,7 @@ describe('getSeries', function() { expect(series).toEqual(expect.any(Array)); expect(series).toHaveLength(2); - series.forEach(function(siri: Serie, i: number) { + series.forEach(function (siri: Serie, i: number) { expect(siri).toEqual(expect.any(Object)); expect(siri).toHaveProperty('label', '' + i); expect(siri).toHaveProperty('values'); @@ -142,14 +142,14 @@ describe('getSeries', function() { expect(siri.values).toEqual(expect.any(Array)); expect(siri.values).toHaveLength(5); - siri.values.forEach(function(point: Point) { + siri.values.forEach(function (point: Point) { expect(point).toHaveProperty('x', 1); expect(point).toHaveProperty('y', i + 2); }); }); }); - it('produces multiple series if there is a series aspect', function() { + it('produces multiple series if there is a series aspect', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -175,7 +175,7 @@ describe('getSeries', function() { expect(series).toEqual(expect.any(Array)); expect(series).toHaveLength(2); - series.forEach(function(siri: Serie, i: number) { + series.forEach(function (siri: Serie, i: number) { expect(siri).toEqual(expect.any(Object)); expect(siri).toHaveProperty('label', '' + i); expect(siri).toHaveProperty('values'); @@ -183,13 +183,13 @@ describe('getSeries', function() { expect(siri.values).toEqual(expect.any(Array)); expect(siri.values).toHaveLength(3); - siri.values.forEach(function(point: Point) { + siri.values.forEach(function (point: Point) { expect(point).toHaveProperty('y', 2); }); }); }); - it('produces multiple series if there is a series aspect and multiple y aspects', function() { + it('produces multiple series if there is a series aspect and multiple y aspects', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -231,13 +231,13 @@ describe('getSeries', function() { expect(siri.values).toEqual(expect.any(Array)); expect(siri.values).toHaveLength(3); - siri.values.forEach(function(point: Point) { + siri.values.forEach(function (point: Point) { expect(point).toHaveProperty('y', y); }); } }); - it('produces a series list in the same order as its corresponding metric column', function() { + it('produces a series list in the same order as its corresponding metric column', function () { const table = { columns: [{ id: '0' }, { id: '1' }, { id: '3' }] as Column[], rows: [ @@ -268,7 +268,7 @@ describe('getSeries', function() { // switch the order of the y columns chart.aspects.y = chart.aspects.y.reverse(); - chart.aspects.y.forEach(function(y: any, i) { + chart.aspects.y.forEach(function (y: any, i) { y.i = i; }); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.ts index edde5b69af022..c5fb4761eb9ee 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_get_series.ts @@ -53,7 +53,7 @@ export function getSeries(table: Table, chart: Chart) { return; } - aspects.y.forEach(function(y) { + aspects.y.forEach(function (y) { const point = partGetPoint(row, rowIndex, y, zAspect); if (!point) { return; diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.test.ts index d3049d7675408..3f0560c2c9f28 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.test.ts @@ -30,11 +30,11 @@ import { } from './point_series'; import { Table, Column } from '../../types'; -describe('initXAxis', function() { +describe('initXAxis', function () { let chart: Chart; let table: Table; - beforeEach(function() { + beforeEach(function () { chart = { aspects: { x: [ @@ -53,13 +53,13 @@ describe('initXAxis', function() { }; }); - it('sets the xAxisFormatter if the agg is not ordered', function() { + it('sets the xAxisFormatter if the agg is not ordered', function () { initXAxis(chart, table); expect(chart).toHaveProperty('xAxisLabel', 'label'); expect(chart).toHaveProperty('xAxisFormat', chart.aspects.x[0].format); }); - it('makes the chart ordered if the agg is ordered', function() { + it('makes the chart ordered if the agg is ordered', function () { (chart.aspects.x[0].params as HistogramParams).interval = 10; initXAxis(chart, table); @@ -68,18 +68,18 @@ describe('initXAxis', function() { expect(chart).toHaveProperty('ordered'); }); - describe('xAxisOrderedValues', function() { - it('sets the xAxisOrderedValues property', function() { + describe('xAxisOrderedValues', function () { + it('sets the xAxisOrderedValues property', function () { initXAxis(chart, table); expect(chart).toHaveProperty('xAxisOrderedValues'); }); - it('returns a list of values, preserving the table order', function() { + it('returns a list of values, preserving the table order', function () { initXAxis(chart, table); expect(chart.xAxisOrderedValues).toEqual(['hello', 'world', 'foo', 'bar', 'baz']); }); - it('only returns unique values', function() { + it('only returns unique values', function () { table = { columns: [{ id: '0' } as Column], rows: [ @@ -97,7 +97,7 @@ describe('initXAxis', function() { expect(chart.xAxisOrderedValues).toEqual(['hello', 'world', 'foo', 'bar', 'baz']); }); - it('returns the defaultValue if using fake x aspect', function() { + it('returns the defaultValue if using fake x aspect', function () { chart = { aspects: { x: [makeFakeXAspect()], @@ -108,7 +108,7 @@ describe('initXAxis', function() { }); }); - it('reads the date interval param from the x agg', function() { + it('reads the date interval param from the x agg', function () { const dateHistogramParams = chart.aspects.x[0].params as DateHistogramParams; dateHistogramParams.interval = 'P1D'; dateHistogramParams.intervalESValue = 1; @@ -127,7 +127,7 @@ describe('initXAxis', function() { expect(intervalESUnit).toBe('d'); }); - it('reads the numeric interval param from the x agg', function() { + it('reads the numeric interval param from the x agg', function () { (chart.aspects.x[0].params as HistogramParams).interval = 0.5; initXAxis(chart, table); expect(chart).toHaveProperty('xAxisLabel', 'label'); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.ts index 9d16c4857be00..32536960c59cd 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_x_axis.ts @@ -28,7 +28,7 @@ export function initXAxis(chart: Chart, table: Table) { chart.xAxisOrderedValues = accessor === -1 && 'defaultValue' in params ? [params.defaultValue] - : uniq(table.rows.map(r => r[accessor])); + : uniq(table.rows.map((r) => r[accessor])); chart.xAxisFormat = format; chart.xAxisLabel = title; diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_y_axis.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_y_axis.test.ts index df84d69c9f849..fa22ae570f38d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_y_axis.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_init_y_axis.test.ts @@ -21,7 +21,7 @@ import _ from 'lodash'; import { initYAxis } from './_init_y_axis'; import { Chart } from './point_series'; -describe('initYAxis', function() { +describe('initYAxis', function () { const baseChart = { aspects: { y: [ @@ -36,25 +36,25 @@ describe('initYAxis', function() { }, } as Chart; - describe('with a single y aspect', function() { + describe('with a single y aspect', function () { const singleYBaseChart = _.cloneDeep(baseChart); singleYBaseChart.aspects.y = [singleYBaseChart.aspects.y[0]]; - it('sets the yAxisFormatter the the field formats convert fn', function() { + it('sets the yAxisFormatter the the field formats convert fn', function () { const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).toHaveProperty('yAxisFormat'); }); - it('sets the yAxisLabel', function() { + it('sets the yAxisLabel', function () { const chart = _.cloneDeep(singleYBaseChart); initYAxis(chart); expect(chart).toHaveProperty('yAxisLabel', 'y1'); }); }); - describe('with multiple y aspects', function() { - it('sets the yAxisFormatter the the field formats convert fn for the first y aspect', function() { + describe('with multiple y aspects', function () { + it('sets the yAxisFormatter the the field formats convert fn for the first y aspect', function () { const chart = _.cloneDeep(baseChart); initYAxis(chart); @@ -63,7 +63,7 @@ describe('initYAxis', function() { expect(chart.yAxisFormat).not.toBe(chart.aspects.y[1].format); }); - it('does not set the yAxisLabel, it does not make sense to put multiple labels on the same axis', function() { + it('does not set the yAxisLabel, it does not make sense to put multiple labels on the same axis', function () { const chart = _.cloneDeep(baseChart); initYAxis(chart); expect(chart).toHaveProperty('yAxisLabel', ''); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_ordered_date_axis.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_ordered_date_axis.test.ts index 25e466f21c3e7..b2e4d6e4b40c9 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_ordered_date_axis.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/_ordered_date_axis.test.ts @@ -22,7 +22,7 @@ import _ from 'lodash'; import { orderedDateAxis } from './_ordered_date_axis'; import { DateHistogramParams, OrderedChart } from './point_series'; -describe('orderedDateAxis', function() { +describe('orderedDateAxis', function () { const baseArgs = { vis: { indexPattern: { @@ -37,9 +37,7 @@ describe('orderedDateAxis', function() { params: { format: 'hh:mm:ss', bounds: { - min: moment() - .subtract(15, 'm') - .valueOf(), + min: moment().subtract(15, 'm').valueOf(), max: moment().valueOf(), }, }, @@ -49,8 +47,8 @@ describe('orderedDateAxis', function() { } as OrderedChart, }; - describe('ordered object', function() { - it('sets date: true', function() { + describe('ordered object', function () { + it('sets date: true', function () { const args = _.cloneDeep(baseArgs); orderedDateAxis(args.chart); @@ -59,14 +57,14 @@ describe('orderedDateAxis', function() { expect(args.chart.ordered).toHaveProperty('date', true); }); - it('sets the min/max when the buckets are bounded', function() { + it('sets the min/max when the buckets are bounded', function () { const args = _.cloneDeep(baseArgs); orderedDateAxis(args.chart); expect(args.chart.ordered).toHaveProperty('min'); expect(args.chart.ordered).toHaveProperty('max'); }); - it('does not set the min/max when the buckets are unbounded', function() { + it('does not set the min/max when the buckets are unbounded', function () { const args = _.cloneDeep(baseArgs); (args.chart.aspects.x[0].params as DateHistogramParams).bounds = undefined; orderedDateAxis(args.chart); diff --git a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/point_series.test.ts b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/point_series.test.ts index 3725bf06660e2..2a5ab197c9ab7 100644 --- a/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/point_series.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/helpers/point_series/point_series.test.ts @@ -23,16 +23,16 @@ import { Table, Column } from '../../types'; import { setFormatService } from '../../../services'; import { Serie } from './_add_to_siri'; -describe('pointSeriesChartDataFromTable', function() { +describe('pointSeriesChartDataFromTable', function () { beforeAll(() => { setFormatService({ deserialize: () => ({ - convert: jest.fn(v => v), + convert: jest.fn((v) => v), }), } as any); }); - it('handles a table with just a count', function() { + it('handles a table with just a count', function () { const table = { columns: [{ id: '0' } as Column], rows: [{ '0': 100 }], @@ -55,7 +55,7 @@ describe('pointSeriesChartDataFromTable', function() { expect(series.values[0]).toHaveProperty('y', 100); }); - it('handles a table with x and y column', function() { + it('handles a table with x and y column', function () { const table = { columns: [ { id: '0', name: 'x' }, @@ -83,7 +83,7 @@ describe('pointSeriesChartDataFromTable', function() { expect(series.values).toHaveLength(3); }); - it('handles a table with an x and two y aspects', function() { + it('handles a table with an x and two y aspects', function () { const table = { columns: [{ id: '0' }, { id: '1', name: 'Count-0' }, { id: '2', name: 'Count-1' }], rows: [ @@ -105,13 +105,13 @@ describe('pointSeriesChartDataFromTable', function() { expect(chartData).toEqual(expect.any(Object)); expect(chartData.series).toEqual(expect.any(Array)); expect(chartData.series).toHaveLength(2); - chartData.series.forEach(function(siri: Serie, i: number) { + chartData.series.forEach(function (siri: Serie, i: number) { expect(siri).toHaveProperty('label', `Count-${i}`); expect(siri.values).toHaveLength(3); }); }); - it('handles a table with an x, a series, and two y aspects', function() { + it('handles a table with an x, a series, and two y aspects', function () { const table = { columns: [ { id: '0', name: 'x' }, @@ -141,7 +141,7 @@ describe('pointSeriesChartDataFromTable', function() { expect(chartData.series).toEqual(expect.any(Array)); // one series for each extension, and then one for each metric inside expect(chartData.series).toHaveLength(4); - chartData.series.forEach(function(siri: Serie) { + chartData.series.forEach(function (siri: Serie) { expect(siri.values).toHaveLength(2); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/_error_handler.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/_error_handler.test.js index b7764b92b7805..1eeef175971b5 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/_error_handler.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/_error_handler.test.js @@ -19,28 +19,28 @@ import { ErrorHandler } from './_error_handler'; -describe('Vislib ErrorHandler Test Suite', function() { +describe('Vislib ErrorHandler Test Suite', function () { let errorHandler; beforeEach(() => { errorHandler = new ErrorHandler(); }); - describe('validateWidthandHeight Method', function() { - it('should throw an error when width and/or height is 0', function() { - expect(function() { + describe('validateWidthandHeight Method', function () { + it('should throw an error when width and/or height is 0', function () { + expect(function () { errorHandler.validateWidthandHeight(0, 200); }).toThrow(); - expect(function() { + expect(function () { errorHandler.validateWidthandHeight(200, 0); }).toThrow(); }); - it('should throw an error when width and/or height is NaN', function() { - expect(function() { + it('should throw an error when width and/or height is NaN', function () { + expect(function () { errorHandler.validateWidthandHeight(null, 200); }).toThrow(); - expect(function() { + expect(function () { errorHandler.validateWidthandHeight(200, null); }).toThrow(); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/alerts.js b/src/plugins/vis_type_vislib/public/vislib/lib/alerts.js index 086b4e31be1a3..b0d5e758c7d42 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/alerts.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/alerts.js @@ -34,7 +34,7 @@ export class Alerts { this.alertDefs = _.cloneDeep(alertDefs); this.alerts = _(alertDefs) - .map(alertDef => { + .map((alertDef) => { if (!alertDef) return; if (alertDef.test && !alertDef.test(vis, this.data)) return; return this._addAlert(alertDef); @@ -48,13 +48,9 @@ export class Alerts { const msg = alertDef.msg; // alert container const $icon = $('').addClass('visAlerts__icon fa fa-' + icon); - const $text = $('

    ') - .addClass('visAlerts__text') - .text(msg); + const $text = $('

    ').addClass('visAlerts__text').text(msg); const $closeIcon = $('').addClass('fa fa-close'); - const $closeDiv = $('

    ') - .addClass('visAlerts__close') - .append($closeIcon); + const $closeDiv = $('
    ').addClass('visAlerts__close').append($closeIcon); const $alert = $('
    ') .addClass('visAlert visAlert--' + type) @@ -71,13 +67,9 @@ export class Alerts { const alerts = this.alerts; const vis = this.vis; - $(vis.element) - .find('.visWrapper__alerts') - .append($('
    ').addClass('visAlerts__tray')); + $(vis.element).find('.visWrapper__alerts').append($('
    ').addClass('visAlerts__tray')); if (!alerts.size()) return; - $(vis.element) - .find('.visAlerts__tray') - .append(alerts.value()); + $(vis.element).find('.visAlerts__tray').append(alerts.value()); } // shows new alert @@ -87,16 +79,12 @@ export class Alerts { msg: msg, type: type, }; - if (this.alertDefs.find(alertDef => alertDef.msg === alert.msg)) return; + if (this.alertDefs.find((alertDef) => alertDef.msg === alert.msg)) return; this.alertDefs.push(alert); - $(vis.element) - .find('.visAlerts__tray') - .append(this._addAlert(alert)); + $(vis.element).find('.visAlerts__tray').append(this._addAlert(alert)); } destroy() { - $(this.vis.element) - .find('.visWrapper__alerts') - .remove(); + $(this.vis.element).find('.visWrapper__alerts').remove(); } } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.js index 7b74c3b2d8e43..cbd42d281b286 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.js @@ -43,10 +43,10 @@ export class Axis extends ErrorHandler { this.stack = d3.layout .stack() - .x(d => { + .x((d) => { return d.x; }) - .y(d => { + .y((d) => { if ( typeof this.axisConfig.get('scale.offset') === 'function' && this.axisConfig.get('scale.offset').name === 'expand' @@ -65,8 +65,8 @@ export class Axis extends ErrorHandler { _stackNegAndPosVals(data) { const cache = {}; - data.forEach(series => { - series.forEach(value => { + data.forEach((series) => { + series.forEach((value) => { if (!cache[value.x]) cache[value.x] = [0, 0]; value.y0 = cache[value.x][value.y < 0 ? 0 : 1]; cache[value.x][value.y < 0 ? 0 : 1] += value.y; @@ -78,18 +78,13 @@ export class Axis extends ErrorHandler { render() { const elSelector = this.axisConfig.get('elSelector'); const rootEl = this.axisConfig.get('rootEl'); - d3.select(rootEl) - .selectAll(elSelector) - .call(this.draw()); + d3.select(rootEl).selectAll(elSelector).call(this.draw()); } destroy() { const elSelector = this.axisConfig.get('elSelector'); const rootEl = this.axisConfig.get('rootEl'); - $(rootEl) - .find(elSelector) - .find('svg') - .remove(); + $(rootEl).find(elSelector).find('svg').remove(); this.axisTitle.destroy(); } @@ -98,11 +93,7 @@ export class Axis extends ErrorHandler { const position = this.axisConfig.get('position'); const axisFormatter = this.axisConfig.get('labels.axisFormatter'); - const d3Axis = d3.svg - .axis() - .scale(scale) - .tickFormat(axisFormatter) - .orient(position); + const d3Axis = d3.svg.axis().scale(scale).tickFormat(axisFormatter).orient(position); if (this.axisConfig.isTimeDomain()) { // use custom overwritten tick function on time domains to get nice @@ -128,11 +119,7 @@ export class Axis extends ErrorHandler { } tickScale(length) { - const yTickScale = d3.scale - .linear() - .clamp(true) - .domain([20, 40, 1000]) - .range([0, 3, 11]); + const yTickScale = d3.scale.linear().clamp(true).domain([20, 40, 1000]).range([0, 3, 11]); return Math.ceil(yTickScale(length)); } @@ -152,7 +139,7 @@ export class Axis extends ErrorHandler { const position = config.get('position'); const axisPadding = 5; - return function(selection) { + return function (selection) { const text = selection.selectAll('.tick text'); const lengths = []; @@ -160,15 +147,9 @@ export class Axis extends ErrorHandler { lengths.push( (() => { if (config.isHorizontal()) { - return d3 - .select(this.parentNode) - .node() - .getBBox().height; + return d3.select(this.parentNode).node().getBBox().height; } else { - return d3 - .select(this.parentNode) - .node() - .getBBox().width; + return d3.select(this.parentNode).node().getBBox().width; } })() ); @@ -186,9 +167,7 @@ export class Axis extends ErrorHandler { } if (config.get('type') === 'value') { const spacerNodes = $(chartEl).find(`.visAxis__spacer--y-${position}`); - const elHeight = $(chartEl) - .find(`.visAxis__column--${position}`) - .height(); + const elHeight = $(chartEl).find(`.visAxis__column--${position}`).height(); spacerNodes.height(elHeight); } } else { @@ -213,7 +192,7 @@ export class Axis extends ErrorHandler { const config = this.axisConfig; const style = config.get('style'); - return function(selection) { + return function (selection) { const n = selection[0].length; if ( config.get('show') && @@ -222,7 +201,7 @@ export class Axis extends ErrorHandler { ) { self.axisTitle.render(selection); } - selection.each(function() { + selection.each(function () { const el = this; const div = d3.select(el); const width = $(el).width(); @@ -269,7 +248,7 @@ export class Axis extends ErrorHandler { self.axisTitle.render(selection); } - svgs.forEach(svg => svg.call(self.adjustSize())); + svgs.forEach((svg) => svg.call(self.adjustSize())); }; } } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.test.js index dec7de5ceeda9..320d9b541de2a 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis.test.js @@ -25,7 +25,7 @@ import { Axis } from './axis'; import { VisConfig } from '../vis_config'; import { getMockUiState } from '../../../fixtures/mocks'; -describe('Vislib Axis Class Test Suite', function() { +describe('Vislib Axis Class Test Suite', function () { let mockUiState; let yAxis; let el; @@ -92,7 +92,7 @@ describe('Vislib Axis Class Test Suite', function() { ], }, ], - xAxisFormatter: function(thing) { + xAxisFormatter: function (thing) { return new Date(thing); }, xAxisLabel: 'Date Histogram', @@ -101,11 +101,7 @@ describe('Vislib Axis Class Test Suite', function() { beforeEach(() => { mockUiState = getMockUiState(); - el = d3 - .select('body') - .append('div') - .attr('class', 'visAxis--x') - .style('height', '40px'); + el = d3.select('body').append('div').attr('class', 'visAxis--x').style('height', '40px'); fixture = el.append('div').attr('class', 'x-axis-div'); @@ -123,18 +119,18 @@ describe('Vislib Axis Class Test Suite', function() { id: 'ValueAxis-1', }); - seriesData = data.series.map(series => { + seriesData = data.series.map((series) => { return series.values; }); }); - afterEach(function() { + afterEach(function () { fixture.remove(); el.remove(); }); - describe('_stackNegAndPosVals Method', function() { - it('should correctly stack positive values', function() { + describe('_stackNegAndPosVals Method', function () { + it('should correctly stack positive values', function () { const expectedResult = [ { x: 1408734060000, @@ -166,7 +162,7 @@ describe('Vislib Axis Class Test Suite', function() { expect(stackedData[1]).toEqual(expectedResult); }); - it('should correctly stack pos and neg values', function() { + it('should correctly stack pos and neg values', function () { const expectedResult = [ { x: 1408734060000, @@ -195,14 +191,14 @@ describe('Vislib Axis Class Test Suite', function() { }, ]; const dataClone = _.cloneDeep(seriesData); - dataClone[0].forEach(value => { + dataClone[0].forEach((value) => { value.y = -value.y; }); const stackedData = yAxis._stackNegAndPosVals(dataClone); expect(stackedData[1]).toEqual(expectedResult); }); - it('should correctly stack mixed pos and neg values', function() { + it('should correctly stack mixed pos and neg values', function () { const expectedResult = [ { x: 1408734060000, diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_labels.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_labels.js index 155be41523ce7..06286331c5e59 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_labels.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_labels.js @@ -33,12 +33,12 @@ export class AxisLabels { rotateAxisLabels() { const config = this.axisConfig; - return function(selection) { + return function (selection) { const text = selection.selectAll('.tick text'); if (config.get('labels.rotate')) { text - .style('text-anchor', function() { + .style('text-anchor', function () { const currentValue = $(this).css('text-anchor'); const rotateDeg = config.get('labels.rotate'); if (!rotateDeg) return currentValue; @@ -55,7 +55,7 @@ export class AxisLabels { } } }) - .attr('dy', function() { + .attr('dy', function () { return config.isHorizontal() ? '0.3em' : '0'; }) .attr('transform', function rotate(d, j) { @@ -80,10 +80,10 @@ export class AxisLabels { truncateLabels() { const config = this.axisConfig; - return function(selection) { + return function (selection) { if (!config.get('labels.truncate')) return; - selection.selectAll('.tick text').text(function() { + selection.selectAll('.tick text').text(function () { return truncateLabel(this, config.get('labels.truncate')); }); }; @@ -96,7 +96,7 @@ export class AxisLabels { let lastTickStartEdge = Number.POSITIVE_INFINITY; let lastTickEndEdge = Number.NEGATIVE_INFINITY; - return function(selection) { + return function (selection) { if (!config.get('labels.filter')) return; const el = $(config.get('rootEl')).find(config.get('elSelector')); @@ -106,7 +106,7 @@ export class AxisLabels { const scaleWidth = Math.abs(scaleRange[scaleRange.length - 1] - scaleRange[0]); const scaleStartPad = 0.5 * (upperBound - scaleWidth); - selection.selectAll('.tick text').text(function(d) { + selection.selectAll('.tick text').text(function (d) { const parentNode = d3.select(this.parentNode).node(); const currentTickCenter = config.isHorizontal() ? scaleStartPad + self.axisScale.scale(d) @@ -138,9 +138,9 @@ export class AxisLabels { const self = this; const config = this.axisConfig; - return function(selection) { - selection.each(function() { - selection.selectAll('text').attr('style', function() { + return function (selection) { + selection.each(function () { + selection.selectAll('text').attr('style', function () { const currentStyle = d3.select(this).attr('style'); return `${currentStyle} font-size: ${config.get('labels.fontSize')};`; }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_scale.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_scale.js index ed197f5309e55..a24ba908e177f 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_scale.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_scale.js @@ -41,7 +41,7 @@ export class AxisScale { validateUserExtents(domain) { const config = this.axisConfig; - return domain.map(val => { + return domain.map((val) => { val = parseFloat(val); if (isNaN(val)) throw new Error(val + ' is not a valid number'); if (config.isPercentage() && config.isUserDefined()) return val / 100; @@ -72,7 +72,7 @@ export class AxisScale { opts.push(point); return d3[extent]( - opts.reduce(function(opts, v) { + opts.reduce(function (opts, v) { if (!_.isNumber(v)) v = +v; if (!isNaN(v)) opts.push(v); return opts; @@ -101,7 +101,7 @@ export class AxisScale { const y = moment(x); const method = n > 0 ? 'add' : 'subtract'; - _.times(Math.abs(n), function() { + _.times(Math.abs(n), function () { y[method](interval); }); @@ -121,7 +121,7 @@ export class AxisScale { const isFirstAxis = config.get('id') === this.visConfig.get('valueAxes[0].id'); if (matchingValueAxis || (!seriConfig.valueAxis && isFirstAxis)) { - const axisPoints = seri.values.map(val => { + const axisPoints = seri.values.map((val) => { if (val.y0) { return val.y0 + val.y; } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.js index 261b670063750..3b59413398e19 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.js @@ -29,23 +29,18 @@ export class AxisTitle { } render() { - d3.select(this.axisConfig.get('rootEl')) - .selectAll(this.elSelector) - .call(this.draw()); + d3.select(this.axisConfig.get('rootEl')).selectAll(this.elSelector).call(this.draw()); } destroy() { - $(this.axisConfig.get('rootEl')) - .find(this.elSelector) - .find('svg') - .remove(); + $(this.axisConfig.get('rootEl')).find(this.elSelector).find('svg').remove(); } draw() { const config = this.axisConfig; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { if (!config.get('show') && !config.get('title.show', false)) return; const el = this; @@ -63,7 +58,7 @@ export class AxisTitle { const bbox = svg .append('text') - .attr('transform', function() { + .attr('transform', function () { if (config.isHorizontal()) { return `translate(${width / 2},0)`; } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.test.js index 7901919d306d2..c43f66d0ac34d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_title.test.js @@ -27,7 +27,7 @@ import { VisConfig } from '../vis_config'; import { Data } from '../data'; import { getMockUiState } from '../../../fixtures/mocks'; -describe('Vislib AxisTitle Class Test Suite', function() { +describe('Vislib AxisTitle Class Test Suite', function () { let el; let dataObj; let xTitle; @@ -93,10 +93,7 @@ describe('Vislib AxisTitle Class Test Suite', function() { }; beforeEach(() => { - el = d3 - .select('body') - .append('div') - .attr('class', 'visWrapper'); + el = d3.select('body').append('div').attr('class', 'visWrapper'); el.append('div') .attr('class', 'visAxis__column--bottom') @@ -140,11 +137,11 @@ describe('Vislib AxisTitle Class Test Suite', function() { yTitle = new AxisTitle(yAxisConfig); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - it('should not do anything if title.show is set to false', function() { + it('should not do anything if title.show is set to false', function () { const xAxisConfig = new AxisConfig(visConfig, { position: 'bottom', show: false, @@ -154,57 +151,33 @@ describe('Vislib AxisTitle Class Test Suite', function() { }); xTitle = new AxisTitle(xAxisConfig); xTitle.render(); - expect( - $(el.node()) - .find('.x-axis-title') - .find('svg').length - ).toBe(0); + expect($(el.node()).find('.x-axis-title').find('svg').length).toBe(0); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { xTitle.render(); yTitle.render(); }); - it('should append an svg to div', function() { + it('should append an svg to div', function () { expect(el.select('.x-axis-title').selectAll('svg').length).toBe(1); expect(el.select('.y-axis-title').selectAll('svg').length).toBe(1); }); - it('should append a g element to the svg', function() { - expect( - el - .select('.x-axis-title') - .selectAll('svg') - .select('g').length - ).toBe(1); - expect( - el - .select('.y-axis-title') - .selectAll('svg') - .select('g').length - ).toBe(1); + it('should append a g element to the svg', function () { + expect(el.select('.x-axis-title').selectAll('svg').select('g').length).toBe(1); + expect(el.select('.y-axis-title').selectAll('svg').select('g').length).toBe(1); }); - it('should append text', function() { - expect( - !!el - .select('.x-axis-title') - .selectAll('svg') - .selectAll('text') - ).toBe(true); - expect( - !!el - .select('.y-axis-title') - .selectAll('svg') - .selectAll('text') - ).toBe(true); + it('should append text', function () { + expect(!!el.select('.x-axis-title').selectAll('svg').selectAll('text')).toBe(true); + expect(!!el.select('.y-axis-title').selectAll('svg').selectAll('text')).toBe(true); }); }); - describe('draw Method', function() { - it('should be a function', function() { + describe('draw Method', function () { + it('should be a function', function () { expect(_.isFunction(xTitle.draw())).toBe(true); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.js index 714e88de0b544..fb1c9123d1468 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.js @@ -19,21 +19,21 @@ import moment from 'moment'; -export const timeTicks = scale => { +export const timeTicks = (scale) => { // on a time domain shift it to have the buckets start at nice points in time (e.g. at the start of the day) in UTC // then shift the calculated tick positions back into the real domain to have a nice tick position in the actual // time zone. This is necessary because the d3 time scale doesn't provide a function to get nice time positions in // a configurable time zone directly. const domain = scale.domain(); const startOffset = moment(domain[0]).utcOffset(); - const shiftedDomain = domain.map(val => moment(val).add(startOffset, 'minute')); + const shiftedDomain = domain.map((val) => moment(val).add(startOffset, 'minute')); const tickScale = scale.copy().domain(shiftedDomain); - return n => { + return (n) => { const ticks = tickScale.ticks(n); const timePerTick = (domain[1] - domain[0]) / ticks.length; const hourTicks = timePerTick < 1000 * 60 * 60 * 12; - return ticks.map(d => { + return ticks.map((d) => { // To get a nice date for the tick, we have to shift the offset of the current UTC tick. This is // relevant in cases where the domain spans various DSTs. // However if there are multiple ticks per day, this would cause a gap because the ticks are placed diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.test.js index 7aa35d00e7083..6ef1d91da70b1 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/time_ticks.test.js @@ -40,7 +40,7 @@ describe('timeTicks', () => { moment.tz.setDefault(); }); - timezonesToTest.map(tz => { + timezonesToTest.map((tz) => { describe(`standard tests in ${tz}`, () => { beforeEach(() => { moment.tz.setDefault(tz); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/x_axis.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/x_axis.test.js index d007a8a14de13..3127bcf17ed07 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/x_axis.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/x_axis.test.js @@ -25,7 +25,7 @@ import { Axis } from './axis'; import { VisConfig } from '../vis_config'; import { getMockUiState } from '../../../fixtures/mocks'; -describe('Vislib xAxis Class Test Suite', function() { +describe('Vislib xAxis Class Test Suite', function () { let mockUiState; let xAxis; let el; @@ -97,7 +97,7 @@ describe('Vislib xAxis Class Test Suite', function() { ], }, ], - xAxisFormatter: function(thing) { + xAxisFormatter: function (thing) { return new Date(thing); }, xAxisLabel: 'Date Histogram', @@ -106,11 +106,7 @@ describe('Vislib xAxis Class Test Suite', function() { beforeEach(() => { mockUiState = getMockUiState(); - el = d3 - .select('body') - .append('div') - .attr('class', 'visAxis--x') - .style('height', '40px'); + el = d3.select('body').append('div').attr('class', 'visAxis--x').style('height', '40px'); fixture = el.append('div').attr('class', 'x-axis-div'); @@ -129,67 +125,67 @@ describe('Vislib xAxis Class Test Suite', function() { }); }); - afterEach(function() { + afterEach(function () { fixture.remove(); el.remove(); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { xAxis.render(); }); - it('should append an svg to div', function() { + it('should append an svg to div', function () { expect(el.selectAll('svg').length).toBe(1); }); - it('should append a g element to the svg', function() { + it('should append a g element to the svg', function () { expect(el.selectAll('svg').select('g').length).toBe(1); }); - it('should append ticks with text', function() { + it('should append ticks with text', function () { expect(!!el.selectAll('svg').selectAll('.tick text')).toBe(true); }); }); - describe('getScale, getDomain, getTimeDomain, and getRange Methods', function() { + describe('getScale, getDomain, getTimeDomain, and getRange Methods', function () { let timeScale; let width; let range; - beforeEach(function() { + beforeEach(function () { width = $('.x-axis-div').width(); xAxis.getAxis(width); timeScale = xAxis.getScale(); range = xAxis.axisScale.getRange(width); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(timeScale)).toBe(true); }); - it('should return the correct domain', function() { + it('should return the correct domain', function () { expect(_.isDate(timeScale.domain()[0])).toBe(true); expect(_.isDate(timeScale.domain()[1])).toBe(true); }); - it('should return the min and max dates', function() { + it('should return the min and max dates', function () { expect(timeScale.domain()[0].toDateString()).toBe(new Date(1408734060000).toDateString()); expect(timeScale.domain()[1].toDateString()).toBe(new Date(1408734330000).toDateString()); }); - it('should return the correct range', function() { + it('should return the correct range', function () { expect(range[0]).toBe(0); expect(range[1]).toBe(width); }); }); - describe('getOrdinalDomain Method', function() { + describe('getOrdinalDomain Method', function () { let ordinalScale; let ordinalDomain; let width; - beforeEach(function() { + beforeEach(function () { width = $('.x-axis-div').width(); xAxis.ordered = null; xAxis.axisConfig.ordered = null; @@ -198,56 +194,56 @@ describe('Vislib xAxis Class Test Suite', function() { ordinalDomain = ordinalScale.domain(['this', 'should', 'be', 'an', 'array']); }); - it('should return an ordinal scale', function() { + it('should return an ordinal scale', function () { expect(ordinalDomain.domain()[0]).toBe('this'); expect(ordinalDomain.domain()[4]).toBe('array'); }); - it('should return an array of values', function() { + it('should return an array of values', function () { expect(Array.isArray(ordinalDomain.domain())).toBe(true); }); }); - describe('getXScale Method', function() { + describe('getXScale Method', function () { let width; let xScale; - beforeEach(function() { + beforeEach(function () { width = $('.x-axis-div').width(); xAxis.getAxis(width); xScale = xAxis.getScale(); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(xScale)).toBe(true); }); - it('should return a domain', function() { + it('should return a domain', function () { expect(_.isDate(xScale.domain()[0])).toBe(true); expect(_.isDate(xScale.domain()[1])).toBe(true); }); - it('should return a range', function() { + it('should return a range', function () { expect(xScale.range()[0]).toBe(0); expect(xScale.range()[1]).toBe(width); }); }); - describe('getXAxis Method', function() { + describe('getXAxis Method', function () { let width; - beforeEach(function() { + beforeEach(function () { width = $('.x-axis-div').width(); xAxis.getAxis(width); }); - it('should create an getScale function on the xAxis class', function() { + it('should create an getScale function on the xAxis class', function () { expect(_.isFunction(xAxis.getScale())).toBe(true); }); }); - describe('draw Method', function() { - it('should be a function', function() { + describe('draw Method', function () { + it('should be a function', function () { expect(_.isFunction(xAxis.draw())).toBe(true); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/y_axis.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/y_axis.test.js index 85378ff1a14e8..4d237669ff849 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/y_axis.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/y_axis.test.js @@ -51,7 +51,7 @@ const defaultGraphData = [ ]; function makeSeriesData(data) { - return timeSeries.map(function(timestamp, i) { + return timeSeries.map(function (timestamp, i) { return { x: timestamp, y: data[i] || 0, @@ -69,7 +69,7 @@ function createData(seriesData) { max: 1408734982458, min: 1408734082458, }, - series: seriesData.map(function(series) { + series: seriesData.map(function (series) { return { values: makeSeriesData(series) }; }), xAxisLabel: 'Date Histogram', @@ -89,7 +89,7 @@ function createData(seriesData) { yAxisDiv = el.append('div').attr('class', 'y-axis-div'); - buildYAxis = function(params) { + buildYAxis = function (params) { const visConfig = new VisConfig( { type: 'histogram', @@ -119,39 +119,39 @@ function createData(seriesData) { yAxis = buildYAxis(); } -describe('Vislib yAxis Class Test Suite', function() { +describe('Vislib yAxis Class Test Suite', function () { beforeEach(() => { mockUiState = getMockUiState(); expect($('.y-axis-wrapper')).toHaveLength(0); }); - afterEach(function() { + afterEach(function () { if (el) { el.remove(); yAxisDiv.remove(); } }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { createData(defaultGraphData); yAxis.render(); }); - it('should append an svg to div', function() { + it('should append an svg to div', function () { expect(el.selectAll('svg').length).toBe(1); }); - it('should append a g element to the svg', function() { + it('should append a g element to the svg', function () { expect(el.selectAll('svg').select('g').length).toBe(1); }); - it('should append ticks with text', function() { + it('should append ticks with text', function () { expect(!!el.selectAll('svg').selectAll('.tick text')).toBe(true); }); }); - describe('getYScale Method', function() { + describe('getYScale Method', function () { let yScale; let graphData; let domain; @@ -169,27 +169,27 @@ describe('Vislib yAxis Class Test Suite', function() { expect(yScale.range()[1]).toBe(0); } - describe('API', function() { - beforeEach(function() { + describe('API', function () { + beforeEach(function () { createData(defaultGraphData); yAxis.getAxis(height); yScale = yAxis.getScale(); }); - it('should return a function', function() { + it('should return a function', function () { expect(_.isFunction(yScale)).toBe(true); }); }); - describe('positive values', function() { - beforeEach(function() { + describe('positive values', function () { + beforeEach(function () { graphData = defaultGraphData; createData(graphData); yAxis.getAxis(height); yScale = yAxis.getScale(); }); - it('should have domain between 0 and max value', function() { + it('should have domain between 0 and max value', function () { const min = 0; const max = _.max(_.flattenDeep(graphData)); const domain = checkDomain(min, max); @@ -198,8 +198,8 @@ describe('Vislib yAxis Class Test Suite', function() { }); }); - describe('negative values', function() { - beforeEach(function() { + describe('negative values', function () { + beforeEach(function () { graphData = [ [-8, -23, -30, -28, -36, -30, -26, -22, -29, -24], [-22, -8, -30, -4, 0, 0, -3, -22, -14, -24], @@ -209,7 +209,7 @@ describe('Vislib yAxis Class Test Suite', function() { yScale = yAxis.getScale(); }); - it('should have domain between min value and 0', function() { + it('should have domain between min value and 0', function () { const min = _.min(_.flattenDeep(graphData)); const max = 0; const domain = checkDomain(min, max); @@ -218,8 +218,8 @@ describe('Vislib yAxis Class Test Suite', function() { }); }); - describe('positive and negative values', function() { - beforeEach(function() { + describe('positive and negative values', function () { + beforeEach(function () { graphData = [ [8, 23, 30, 28, 36, 30, 26, 22, 29, 24], [22, 8, -30, -4, 0, 0, 3, -22, 14, 24], @@ -229,7 +229,7 @@ describe('Vislib yAxis Class Test Suite', function() { yScale = yAxis.getScale(); }); - it('should have domain between min and max values', function() { + it('should have domain between min and max values', function () { const min = _.min(_.flattenDeep(graphData)); const max = _.max(_.flattenDeep(graphData)); const domain = checkDomain(min, max); @@ -239,8 +239,8 @@ describe('Vislib yAxis Class Test Suite', function() { }); }); - describe('validate user defined values', function() { - beforeEach(function() { + describe('validate user defined values', function () { + beforeEach(function () { createData(defaultGraphData); yAxis.axisConfig.set('scale.stacked', true); yAxis.axisConfig.set('scale.setYExtents', false); @@ -248,16 +248,16 @@ describe('Vislib yAxis Class Test Suite', function() { yScale = yAxis.getScale(); }); - it('should throw a NaN error', function() { + it('should throw a NaN error', function () { const min = 'Not a number'; const max = 12; - expect(function() { + expect(function () { yAxis.axisScale.validateUserExtents(min, max); }).toThrow(); }); - it('should return a decimal value', function() { + it('should return a decimal value', function () { yAxis.axisConfig.set('scale.mode', 'percentage'); yAxis.axisConfig.set('scale.setYExtents', true); yAxis.getAxis(height); @@ -270,7 +270,7 @@ describe('Vislib yAxis Class Test Suite', function() { expect(newDomain[1]).toBe(domain[1] / 100); }); - it('should return the user defined value', function() { + it('should return the user defined value', function () { domain = [20, 50]; const newDomain = yAxis.axisScale.validateUserExtents(domain); @@ -279,32 +279,32 @@ describe('Vislib yAxis Class Test Suite', function() { }); }); - describe('should throw an error when', function() { - it('min === max', function() { + describe('should throw an error when', function () { + it('min === max', function () { const min = 12; const max = 12; - expect(function() { + expect(function () { yAxis.axisScale.validateAxisExtents(min, max); }).toThrow(); }); - it('min > max', function() { + it('min > max', function () { const min = 30; const max = 10; - expect(function() { + expect(function () { yAxis.axisScale.validateAxisExtents(min, max); }).toThrow(); }); }); }); - describe('getScaleType method', function() { + describe('getScaleType method', function () { const fnNames = ['linear', 'log', 'square root']; - it('should return a function', function() { - fnNames.forEach(function(fnName) { + it('should return a function', function () { + fnNames.forEach(function (fnName) { expect(yAxis.axisScale.getD3Scale(fnName)).toEqual(expect.any(Function)); }); @@ -312,67 +312,67 @@ describe('Vislib yAxis Class Test Suite', function() { expect(yAxis.axisScale.getD3Scale()).toEqual(expect.any(Function)); }); - it('should throw an error if function name is undefined', function() { - expect(function() { + it('should throw an error if function name is undefined', function () { + expect(function () { yAxis.axisScale.getD3Scale('square'); }).toThrow(); }); }); - describe('_logDomain method', function() { - it('should throw an error', function() { - expect(function() { + describe('_logDomain method', function () { + it('should throw an error', function () { + expect(function () { yAxis.axisScale.logDomain(-10, -5); }).toThrow(); - expect(function() { + expect(function () { yAxis.axisScale.logDomain(-10, 5); }).toThrow(); - expect(function() { + expect(function () { yAxis.axisScale.logDomain(0, -5); }).toThrow(); }); - it('should return a yMin value of 1', function() { + it('should return a yMin value of 1', function () { const yMin = yAxis.axisScale.logDomain(0, 200)[0]; expect(yMin).toBe(1); }); }); - describe('getYAxis method', function() { + describe('getYAxis method', function () { let yMax; - beforeEach(function() { + beforeEach(function () { createData(defaultGraphData); yMax = yAxis.yMax; }); - afterEach(function() { + afterEach(function () { yAxis.yMax = yMax; yAxis = buildYAxis(); }); - it('should use decimal format for small values', function() { + it('should use decimal format for small values', function () { yAxis.yMax = 1; const tickFormat = yAxis.getAxis().tickFormat(); expect(tickFormat(0.8)).toBe('0.8'); }); }); - describe('draw Method', function() { - beforeEach(function() { + describe('draw Method', function () { + beforeEach(function () { createData(defaultGraphData); }); - it('should be a function', function() { + it('should be a function', function () { expect(_.isFunction(yAxis.draw())).toBe(true); }); }); - describe('tickScale Method', function() { - beforeEach(function() { + describe('tickScale Method', function () { + beforeEach(function () { createData(defaultGraphData); }); - it('should return the correct number of ticks', function() { + it('should return the correct number of ticks', function () { expect(yAxis.tickScale(1000)).toBe(11); expect(yAxis.tickScale(40)).toBe(3); expect(yAxis.tickScale(20)).toBe(0); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/binder.ts b/src/plugins/vis_type_vislib/public/vislib/lib/binder.ts index 87221333c0ba5..8b06a65e71698 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/binder.ts +++ b/src/plugins/vis_type_vislib/public/vislib/lib/binder.ts @@ -49,7 +49,7 @@ export class Binder { public destroy() { const destroyers = this.disposal; this.disposal = []; - destroyers.forEach(fn => fn()); + destroyers.forEach((fn) => fn()); } jqOn(el: HTMLElement, ...args: [string, (event: JQueryEventObject) => void]) { diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js b/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js index 3f6e3dd851edc..aac019a98e790 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js @@ -47,8 +47,8 @@ export class ChartGrid { const y1 = !isHorizontal ? tick : height; const d3Line = d3.svg .line() - .x(d => (isHorizontal ? scale(d[0]) : d[0])) - .y(d => (!isHorizontal ? scale(d[1]) : d[1])); + .x((d) => (isHorizontal ? scale(d[0]) : d[0])) + .y((d) => (!isHorizontal ? scale(d[1]) : d[1])); return d3Line([ [x0, y0], [x1, y1], @@ -64,28 +64,28 @@ export class ChartGrid { if (!axis) return; const ticks = axis.getScale().ticks; if (!ticks) return; - ticks().forEach(tick => { + ticks().forEach((tick) => { this.drawLine(svg, tick, axis, width, height); }); } drawValueLines(svg, width, height) { const axis = this._handler.valueAxes.find( - axis => axis.axisConfig.get('id') === this.get('valueAxis') + (axis) => axis.axisConfig.get('id') === this.get('valueAxis') ); if (!axis) return; const ticks = axis.getScale().ticks; if (!ticks) return; - ticks().forEach(tick => { + ticks().forEach((tick) => { this.drawLine(svg, tick, axis, width, height); }); } draw(width, height) { const self = this; - return function(selection) { + return function (selection) { if (!self._values) return; - selection.each(function() { + selection.each(function () { if (self.get('categoryLines')) self.drawCategoryLines(d3.select(this), width, height); if (self.get('valueAxis', false)) self.drawValueLines(d3.select(this), width, height); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/chart_title.js b/src/plugins/vis_type_vislib/public/vislib/lib/chart_title.js index 3caaf99cbb5c1..a281cea38bada 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/chart_title.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/chart_title.js @@ -27,30 +27,24 @@ export class ChartTitle extends ErrorHandler { constructor(visConfig) { super(); this.el = visConfig.get('el'); - this.tooltip = new Tooltip('chart-title', this.el, function(d) { + this.tooltip = new Tooltip('chart-title', this.el, function (d) { return '

    ' + _.escape(d.label) + '

    '; }); } render() { - const el = d3 - .select(this.el) - .select('.chart-title') - .node(); + const el = d3.select(this.el).select('.chart-title').node(); const width = el ? el.clientWidth : 0; const height = el ? el.clientHeight : 0; - return d3 - .select(this.el) - .selectAll('.chart-title') - .call(this.draw(width, height)); + return d3.select(this.el).selectAll('.chart-title').call(this.draw(width, height)); } truncate(size) { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const text = d3.select(this); const n = text[0].length; const maxWidth = (size / n) * 0.9; @@ -83,8 +77,8 @@ export class ChartTitle extends ErrorHandler { draw(width, height) { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const div = d3.select(this); const dataType = this.parentNode.__data__.rows ? 'rows' : 'columns'; const size = dataType === 'rows' ? height : width; @@ -98,14 +92,14 @@ export class ChartTitle extends ErrorHandler { .attr('width', width) .attr('height', height) .append('text') - .attr('transform', function() { + .attr('transform', function () { if (dataType === 'rows') { return 'translate(' + txtHtOffset + ',' + height / 2 + ')rotate(270)'; } return 'translate(' + width / 2 + ',' + txtHtOffset + ')'; }) .attr('text-anchor', 'middle') - .text(function(d) { + .text(function (d) { return d.label; }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/data.js b/src/plugins/vis_type_vislib/public/vislib/lib/data.js index 2adabd4d315b4..98d384f95a839 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/data.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/data.js @@ -69,18 +69,18 @@ export class Data { } copyDataObj(data) { - const copyChart = data => { + const copyChart = (data) => { const newData = {}; - Object.keys(data).forEach(key => { + Object.keys(data).forEach((key) => { if (key === 'xAxisOrderedValues') { - newData[key] = data[key].map(val => { + newData[key] = data[key].map((val) => { if (typeof val === 'object') { return new D3MappableObject(val); } return val; }); } else if (key === 'series') { - newData[key] = data[key].map(seri => { + newData[key] = data[key].map((seri) => { const converter = getFormatService().deserialize(seri.format); const zConverter = getFormatService().deserialize(seri.zFormat); return { @@ -88,7 +88,7 @@ export class Data { rawId: seri.rawId, label: seri.label, zLabel: seri.zLabel, - values: seri.values.map(val => { + values: seri.values.map((val) => { const newVal = _.clone(val); newVal.extraMetrics = val.extraMetrics; newVal.series = val.series || seri.label; @@ -97,8 +97,8 @@ export class Data { } return newVal; }), - yAxisFormatter: val => converter.convert(val), - zAxisFormatter: val => zConverter.convert(val), + yAxisFormatter: (val) => converter.convert(val), + zAxisFormatter: (val) => zConverter.convert(val), }; }); } else { @@ -109,20 +109,20 @@ export class Data { const xConverter = getFormatService().deserialize(newData.xAxisFormat); const yConverter = getFormatService().deserialize(newData.yAxisFormat); const zConverter = getFormatService().deserialize(newData.zAxisFormat); - newData.xAxisFormatter = val => xConverter.convert(val); - newData.yAxisFormatter = val => yConverter.convert(val); - newData.zAxisFormatter = val => zConverter.convert(val); + newData.xAxisFormatter = (val) => xConverter.convert(val); + newData.yAxisFormatter = (val) => yConverter.convert(val); + newData.zAxisFormatter = (val) => zConverter.convert(val); return newData; }; if (!data.series) { const newData = {}; - Object.keys(data).forEach(key => { + Object.keys(data).forEach((key) => { if (!['rows', 'columns'].includes(key)) { newData[key] = data[key]; } else { - newData[key] = data[key].map(chart => { + newData[key] = data[key].map((chart) => { return copyChart(chart); }); } @@ -143,7 +143,7 @@ export class Data { const data = this.getVisData(); let type; - data.forEach(function(obj) { + data.forEach(function (obj) { if (obj.series) { type = 'series'; } else if (obj.slices) { @@ -249,7 +249,7 @@ export class Data { return _.reduce( _.pluck(visData, 'geoJson.properties'), - function(minMax, props) { + function (minMax, props) { return { min: Math.min(props.min, minMax.min), max: Math.max(props.max, minMax.max), @@ -294,9 +294,9 @@ export class Data { hasNullValues() { const chartData = this.chartData(); - return chartData.some(function(chart) { - return chart.series.some(function(obj) { - return obj.values.some(function(d) { + return chartData.some(function (chart) { + return chart.series.some(function (obj) { + return obj.values.some(function (d) { return d.y === null; }); }); @@ -312,12 +312,7 @@ export class Data { * @returns {Array} Value objects */ flatten() { - return _(this.chartData()) - .pluck('series') - .flattenDeep() - .pluck('values') - .flattenDeep() - .value(); + return _(this.chartData()).pluck('series').flattenDeep().pluck('values').flattenDeep().value(); } /** @@ -349,7 +344,7 @@ export class Data { const names = []; const self = this; - _.forEach(array, function(obj) { + _.forEach(array, function (obj) { names.push({ label: obj.name, values: [obj.rawData], @@ -359,7 +354,7 @@ export class Data { if (obj.children) { const plusIndex = index + 1; - _.forEach(self.returnNames(obj.children, plusIndex, columns), function(namedObj) { + _.forEach(self.returnNames(obj.children, plusIndex, columns), function (namedObj) { names.push(namedObj); }); } @@ -385,10 +380,10 @@ export class Data { const namedObj = this.returnNames(slices.children, 0, columns); return _(namedObj) - .sortBy(function(obj) { + .sortBy(function (obj) { return obj.index; }) - .unique(function(d) { + .unique(function (d) { return d.label; }) .value(); @@ -413,7 +408,7 @@ export class Data { * @param {Array} data */ _cleanPieChartData(data) { - _.forEach(data, obj => { + _.forEach(data, (obj) => { obj.slices = this._removeZeroSlices(obj.slices); }); } @@ -450,9 +445,9 @@ export class Data { const self = this; const names = []; - _.forEach(data, function(obj) { + _.forEach(data, function (obj) { const columns = obj.raw ? obj.raw.columns : undefined; - _.forEach(self.getNames(obj, columns), function(name) { + _.forEach(self.getNames(obj, columns), function (name) { names.push(name); }); }); @@ -516,7 +511,7 @@ export class Data { */ getPieColorFunc() { return this.createColorLookupFunction( - this.pieNames(this.getVisData()).map(function(d) { + this.pieNames(this.getVisData()).map(function (d) { return d.label; }), this.uiState.get('vis.colors') @@ -533,7 +528,7 @@ export class Data { const data = this.getVisData(); const self = this; - data.forEach(function(d) { + data.forEach(function (d) { if (!d.ordered || !d.ordered.date) return; const missingMin = d.ordered.min == null; @@ -558,7 +553,7 @@ export class Data { * @returns {Array} min and max values */ mapDataExtents(series) { - const values = _.map(series.rows, function(row) { + const values = _.map(series.rows, function (row) { return row[row.length - 1]; }); return [_.min(values), _.max(values)]; @@ -571,7 +566,7 @@ export class Data { * @return {number} - the largest number of series from all charts */ maxNumberOfSeries() { - return this.chartData().reduce(function(max, chart) { + return this.chartData().reduce(function (max, chart) { return Math.max(max, chart.series.length); }, 0); } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/data.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/data.test.js index b1a91979b3d9d..82bb472f1696d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/data.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/data.test.js @@ -150,25 +150,25 @@ const colsData = { ], }; -describe('Vislib Data Class Test Suite', function() { +describe('Vislib Data Class Test Suite', function () { let mockUiState; beforeEach(() => { mockUiState = getMockUiState(); }); - describe('Data Class (main)', function() { - it('should be a function', function() { + describe('Data Class (main)', function () { + it('should be a function', function () { expect(_.isFunction(Data)).toBe(true); }); - it('should return an object', function() { + it('should return an object', function () { const rowIn = new Data(rowsData, mockUiState, () => undefined); expect(_.isObject(rowIn)).toBe(true); }); }); - describe('_removeZeroSlices', function() { + describe('_removeZeroSlices', function () { let data; const pieData = { slices: { @@ -176,26 +176,26 @@ describe('Vislib Data Class Test Suite', function() { }, }; - beforeEach(function() { + beforeEach(function () { data = new Data(pieData, mockUiState, () => undefined); }); - it('should remove zero values', function() { + it('should remove zero values', function () { const slices = data._removeZeroSlices(data.data.slices); expect(slices.children.length).toBe(2); }); }); - describe('Data.flatten', function() { + describe('Data.flatten', function () { let serIn; let serOut; - beforeEach(function() { + beforeEach(function () { serIn = new Data(seriesData, mockUiState, () => undefined); serOut = serIn.flatten(); }); - it('should return an array of value objects from every series', function() { + it('should return an array of value objects from every series', function () { expect(serOut.every(_.isObject)).toBe(true); }); @@ -204,14 +204,14 @@ describe('Vislib Data Class Test Suite', function() { it('should return all points from every series in the columns', testLength(colsData)); function testLength(inputData) { - return function() { + return function () { const data = new Data(inputData, mockUiState, () => undefined); const len = _.reduce( data.chartData(), - function(sum, chart) { + function (sum, chart) { return ( sum + - chart.series.reduce(function(sum, series) { + chart.series.reduce(function (sum, series) { return sum + series.values.length; }, 0) ); @@ -224,7 +224,7 @@ describe('Vislib Data Class Test Suite', function() { } }); - describe('geohashGrid methods', function() { + describe('geohashGrid methods', function () { let data; const geohashGridData = { hits: 3954, @@ -260,19 +260,19 @@ describe('Vislib Data Class Test Suite', function() { ], }; - beforeEach(function() { + beforeEach(function () { data = new Data(geohashGridData, mockUiState, () => undefined); }); - describe('getVisData', function() { - it('should return the rows property', function() { + describe('getVisData', function () { + it('should return the rows property', function () { const visData = data.getVisData(); expect(visData[0].title).toEqual(geohashGridData.rows[0].title); }); }); - describe('getGeoExtents', function() { - it('should return the min and max geoJson properties', function() { + describe('getGeoExtents', function () { + it('should return the min and max geoJson properties', function () { const minMax = data.getGeoExtents(); expect(minMax.min).toBe(1); expect(minMax.max).toBe(331); @@ -280,13 +280,13 @@ describe('Vislib Data Class Test Suite', function() { }); }); - describe('null value check', function() { - it('should return false', function() { + describe('null value check', function () { + it('should return false', function () { const data = new Data(rowsData, mockUiState, () => undefined); expect(data.hasNullValues()).toBe(false); }); - it('should return true', function() { + it('should return true', function () { const nullRowData = { rows: rowsData.rows.slice(0) }; nullRowData.rows.push({ label: 'e', diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/dispatch.js b/src/plugins/vis_type_vislib/public/vislib/lib/dispatch.js index 09256232860bc..37f395aab4011 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/dispatch.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/dispatch.js @@ -97,7 +97,7 @@ export class Dispatch { * @param {*} [arg...] - any number of arguments that will be applied to each handler * @return {Dispatch} - this, for chaining */ - emit = restParam(function(name, args) { + emit = restParam(function (name, args) { if (!this._listeners[name]) { return this; } @@ -155,7 +155,7 @@ export class Dispatch { _seriesClickResponse(data) { const points = []; - ['xRaw', 'yRaw', 'zRaw', 'seriesRaw', 'rawData', 'tableRaw'].forEach(val => { + ['xRaw', 'yRaw', 'zRaw', 'seriesRaw', 'rawData', 'tableRaw'].forEach((val) => { if (data[val] && data[val].column !== undefined && data[val].row !== undefined) { points.push(data[val]); } @@ -201,20 +201,20 @@ export class Dispatch { return false; } //find the primary id by the rawId, that id is used in the config's seriesParams - const { id } = series.find(series => series.rawId === rawId); + const { id } = series.find((series) => series.rawId === rawId); if (!id) { return false; } //find the matching seriesParams of the series, to get the id of the valueAxis const seriesParams = visConfig.get('seriesParams', []); - const { valueAxis: valueAxisId } = seriesParams.find(param => param.data.id === id) || {}; + const { valueAxis: valueAxisId } = seriesParams.find((param) => param.data.id === id) || {}; if (!valueAxisId) { return false; } const usedValueAxis = visConfig .get('valueAxes', []) - .find(valueAxis => valueAxis.id === valueAxisId); + .find((valueAxis) => valueAxis.id === valueAxisId); return get(usedValueAxis, 'scale.mode') === 'percentage'; } @@ -270,8 +270,8 @@ export class Dispatch { * @returns {Function} */ addEvent(event, callback) { - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const element = d3.select(this); if (typeof callback === 'function') { @@ -334,7 +334,7 @@ export class Dispatch { * @returns {Function} */ addClickEvent() { - const onClick = d => this.emit('click', this.clickEventResponse(d)); + const onClick = (d) => this.emit('click', this.clickEventResponse(d)); return this.addEvent('click', onClick); } @@ -444,7 +444,7 @@ export class Dispatch { // Allows for brushing on d3.scale.ordinal() const selected = xScale .domain() - .filter(d => brush.extent()[0] <= xScale(d) && xScale(d) <= brush.extent()[1]); + .filter((d) => brush.extent()[0] <= xScale(d) && xScale(d) <= brush.extent()[1]); const range = isTimeSeries ? brush.extent() : selected; return self.emit('brush', { @@ -461,11 +461,11 @@ export class Dispatch { .insert('g', 'g') .attr('class', 'brush') .call(brush) - .call(brushG => { + .call((brushG) => { // hijack the brush start event to filter out right/middle clicks const brushHandler = brushG.on('mousedown.brush'); if (!brushHandler) return; // touch events in use - brushG.on('mousedown.brush', function() { + brushG.on('mousedown.brush', function () { if (validBrushClick(d3.event)) brushHandler.apply(this, arguments); }); }) diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/handler.js b/src/plugins/vis_type_vislib/public/vislib/lib/handler.js index f5b1c13f1a83f..3c1aeaa0d1d0d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/handler.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/handler.js @@ -58,8 +58,8 @@ export class Handler { this.categoryAxes = visConfig .get('categoryAxes') - .map(axisArgs => new Axis(visConfig, axisArgs)); - this.valueAxes = visConfig.get('valueAxes').map(axisArgs => new Axis(visConfig, axisArgs)); + .map((axisArgs) => new Axis(visConfig, axisArgs)); + this.valueAxes = visConfig.get('valueAxes').map((axisArgs) => new Axis(visConfig, axisArgs)); this.chartTitle = new ChartTitle(visConfig); this.alerts = new Alerts(this, visConfig.get('alerts')); this.grid = new Grid(this, visConfig.get('grid')); @@ -83,9 +83,9 @@ export class Handler { // memoize so that the same function is returned every time, // allowing us to remove/re-add the same function - this.getProxyHandler = _.memoize(function(eventType) { + this.getProxyHandler = _.memoize(function (eventType) { const self = this; - return function(eventPayload) { + return function (eventPayload) { switch (eventType) { case 'brush': const xRaw = _.get(eventPayload.data, 'series[0].values[0].xRaw'); @@ -154,7 +154,7 @@ export class Handler { selection.selectAll('*').remove(); this._validateData(); - this.renderArray.forEach(function(property) { + this.renderArray.forEach(function (property) { if (typeof property.render === 'function') { property.render(); } @@ -163,10 +163,10 @@ export class Handler { // render the chart(s) let loadedCount = 0; const chartSelection = selection.selectAll('.chart'); - chartSelection.each(function(chartData) { + chartSelection.each(function (chartData) { const chart = new self.ChartClass(self, this, chartData, self.deps); - self.vis.eventNames().forEach(function(event) { + self.vis.eventNames().forEach(function (event) { self.enable(event, chart); }); @@ -184,10 +184,10 @@ export class Handler { } chartEventProxyToggle(method) { - return function(event, chart) { + return function (event, chart) { const proxyHandler = this.getProxyHandler(event); - _.each(chart ? [chart] : this.charts, function(chart) { + _.each(chart ? [chart] : this.charts, function (chart) { chart.events[method](event, proxyHandler); }); }; @@ -203,10 +203,7 @@ export class Handler { * child element removed */ removeAll(el) { - return d3 - .select(el) - .selectAll('*') - .remove(); + return d3.select(el).selectAll('*').remove(); } /** @@ -241,13 +238,13 @@ export class Handler { destroy() { this.binder.destroy(); - this.renderArray.forEach(function(renderable) { + this.renderArray.forEach(function (renderable) { if (_.isFunction(renderable.destroy)) { renderable.destroy(); } }); - this.charts.splice(0).forEach(function(chart) { + this.charts.splice(0).forEach(function (chart) { if (_.isFunction(chart.destroy)) { chart.destroy(); } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout.js index a8416241d8a24..a5f4907f46273 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout.js @@ -73,7 +73,7 @@ export class Layout { * @returns {*} Creates the visualization layout */ createLayout(arr) { - return _.each(arr, obj => { + return _.each(arr, (obj) => { this.layout(obj); }); } @@ -93,9 +93,7 @@ export class Layout { const width = axisWrapperElement.width(); const height = axisWrapperElement.height(); axis.destroy(); - $(this.el) - .find('.chart-title svg') - .remove(); + $(this.el).find('.chart-title svg').remove(); axisWrapperElement.css('visibility', ''); if (axis.axisConfig.isHorizontal()) { @@ -145,7 +143,7 @@ export class Layout { if (obj.children) { const newParent = childEl[0][0]; - _.forEach(obj.children, function(obj) { + _.forEach(obj.children, function (obj) { if (!obj.parent) { obj.parent = newParent; } @@ -178,10 +176,7 @@ export class Layout { el = d3.select(this.el).select(el)[0][0]; } - return d3 - .select(el) - .append(type) - .attr('class', className); + return d3.select(el).append(type).attr('class', className); } /** @@ -192,9 +187,6 @@ export class Layout { * @returns {D3.Selection|D3.Transition.Transition} Reference to an empty DOM element */ removeAll(el) { - return d3 - .select(el) - .selectAll('*') - .remove(); + return d3.select(el).selectAll('*').remove(); } } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout_types.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout_types.test.js index 0bc11e5124a07..8b727ea3aa5fe 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout_types.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/layout_types.test.js @@ -21,18 +21,18 @@ import _ from 'lodash'; import { layoutTypes as layoutType } from './layout_types'; -describe('Vislib Layout Types Test Suite', function() { +describe('Vislib Layout Types Test Suite', function () { let layoutFunc; beforeEach(() => { layoutFunc = layoutType.point_series; }); - it('should be an object', function() { + it('should be an object', function () { expect(_.isObject(layoutType)).toBe(true); }); - it('should return a function', function() { + it('should return a function', function () { expect(typeof layoutFunc).toBe('function'); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_split.js index c7d2134f41db8..80c3fc78dc6a6 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_split.js @@ -25,8 +25,8 @@ import d3 from 'd3'; * `.chart` elements as row objects. */ export function chartSplit(selection, parent) { - selection.each(function(data) { - const div = d3.select(this).attr('class', function() { + selection.each(function (data) { + const div = d3.select(this).attr('class', function () { if (data.rows) { return 'visWrapper__splitCharts--row'; } else if (data.columns) { @@ -44,7 +44,7 @@ export function chartSplit(selection, parent) { const charts = div .selectAll('charts') .append('div') - .data(function(d) { + .data(function (d) { if (d.rows) { chartsNumber = d.rows.length; return d.rows; @@ -59,7 +59,7 @@ export function chartSplit(selection, parent) { }) .enter() .append('div') - .attr('class', function(d, i) { + .attr('class', function (d, i) { let fullDivClass = divClass; if (fullDivClass !== 'chart') { if (chartsNumber > 1) { diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_title_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_title_split.js index 958011bac2a3a..4039de6fb1bee 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_title_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/chart_title_split.js @@ -28,14 +28,14 @@ import $ from 'jquery'; * if not data.rows or data.columns, return no chart titles */ export function chartTitleSplit(selection) { - selection.each(function(data) { + selection.each(function (data) { const div = d3.select(this); const parent = $(this).parents('.visWrapper'); if (!data.series) { div .selectAll('.chart-title') - .data(function(d) { + .data(function (d) { return d.rows ? d.rows : d.columns; }) .enter() diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/splits.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/splits.test.js index 117b346efda89..7771377048750 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/splits.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/splits.test.js @@ -25,8 +25,8 @@ import { chartTitleSplit } from './chart_title_split'; import { xAxisSplit } from './x_axis_split'; import { yAxisSplit } from './y_axis_split'; -describe('Vislib Split Function Test Suite', function() { - describe('Column Chart', function() { +describe('Vislib Split Function Test Suite', function () { + describe('Column Chart', function () { let el; const data = { rows: [ @@ -150,54 +150,46 @@ describe('Vislib Split Function Test Suite', function() { }; beforeEach(() => { - el = d3 - .select('body') - .append('div') - .attr('class', 'visualization') - .datum(data); + el = d3.select('body').append('div').attr('class', 'visualization').datum(data); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - describe('chart split function', function() { + describe('chart split function', function () { let fixture; - beforeEach(function() { + beforeEach(function () { fixture = d3.select('.visualization').call(chartSplit); }); - afterEach(function() { + afterEach(function () { fixture.remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect($('.chart').length).toBe(2); }); - it('should add the correct class name', function() { + it('should add the correct class name', function () { expect(!!$('.visWrapper__splitCharts--row').length).toBe(true); }); }); - describe('chart title split function', function() { + describe('chart title split function', function () { let visEl; let newEl; let fixture; - beforeEach(function() { + beforeEach(function () { visEl = el.append('div').attr('class', 'visWrapper'); visEl.append('div').attr('class', 'visAxis__splitTitles--x'); visEl.append('div').attr('class', 'visAxis__splitTitles--y'); visEl.select('.visAxis__splitTitles--x').call(chartTitleSplit); visEl.select('.visAxis__splitTitles--y').call(chartTitleSplit); - newEl = d3 - .select('body') - .append('div') - .attr('class', 'visWrapper') - .datum({ series: [] }); + newEl = d3.select('body').append('div').attr('class', 'visWrapper').datum({ series: [] }); newEl.append('div').attr('class', 'visAxis__splitTitles--x'); newEl.append('div').attr('class', 'visAxis__splitTitles--y'); @@ -207,29 +199,29 @@ describe('Vislib Split Function Test Suite', function() { fixture = newEl.selectAll(this.childNodes)[0].length; }); - afterEach(function() { + afterEach(function () { newEl.remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect($('.chart-title').length).toBe(2); }); - it('should remove the correct div', function() { + it('should remove the correct div', function () { expect($('.visAxis__splitTitles--y').length).toBe(1); expect($('.visAxis__splitTitles--x').length).toBe(0); }); - it('should remove all chart title divs when only one chart is rendered', function() { + it('should remove all chart title divs when only one chart is rendered', function () { expect(fixture).toBe(0); }); }); - describe('x axis split function', function() { + describe('x axis split function', function () { let fixture; let divs; - beforeEach(function() { + beforeEach(function () { fixture = d3 .select('body') .append('div') @@ -239,21 +231,21 @@ describe('Vislib Split Function Test Suite', function() { divs = d3.selectAll('.x-axis-div')[0]; }); - afterEach(function() { + afterEach(function () { fixture.remove(); $(divs).remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect(divs.length).toBe(2); }); }); - describe('y axis split function', function() { + describe('y axis split function', function () { let fixture; let divs; - beforeEach(function() { + beforeEach(function () { fixture = d3 .select('body') .append('div') @@ -265,12 +257,12 @@ describe('Vislib Split Function Test Suite', function() { divs = d3.selectAll('.y-axis-div')[0]; }); - afterEach(function() { + afterEach(function () { fixture.remove(); $(divs).remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect(divs.length).toBe(2); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/x_axis_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/x_axis_split.js index 188754091663a..cfd53d739279c 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/x_axis_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/x_axis_split.js @@ -26,13 +26,13 @@ import d3 from 'd3'; */ export function xAxisSplit(selection) { - selection.each(function() { + selection.each(function () { const div = d3.select(this); let columns; div .selectAll('.x-axis-div') .append('div') - .data(function(d) { + .data(function (d) { columns = d.columns ? d.columns.length : 1; return d.columns ? d.columns : [d]; }) diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/y_axis_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/y_axis_split.js index ff0a553991bf7..6d985d9fa0a53 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/y_axis_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/column_chart/y_axis_split.js @@ -27,14 +27,14 @@ import d3 from 'd3'; // render and get bounding box width export function yAxisSplit(selection) { - selection.each(function() { + selection.each(function () { const div = d3.select(this); let rows; div .selectAll('.y-axis-div') .append('div') - .data(function(d) { + .data(function (d) { rows = d.rows ? d.rows.length : 1; return d.rows ? d.rows : [d]; }) diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_split.js index 245a6e599c4ec..7ae42721e9307 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_split.js @@ -26,8 +26,8 @@ import d3 from 'd3'; */ export function chartSplit(selection) { - selection.each(function(data) { - const div = d3.select(this).attr('class', function() { + selection.each(function (data) { + const div = d3.select(this).attr('class', function () { if (data.rows) { return 'visWrapper__splitCharts--row'; } else if (data.columns) { @@ -41,7 +41,7 @@ export function chartSplit(selection) { const charts = div .selectAll('charts') .append('div') - .data(function(d) { + .data(function (d) { if (d.rows) { divClass = 'chart-row'; return d.rows; @@ -55,7 +55,7 @@ export function chartSplit(selection) { }) .enter() .append('div') - .attr('class', function() { + .attr('class', function () { return divClass; }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_title_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_title_split.js index 9d23cf4591699..2c3336b2a3a33 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_title_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/chart_title_split.js @@ -28,14 +28,14 @@ import d3 from 'd3'; */ export function chartTitleSplit(selection, parent) { - selection.each(function(data) { + selection.each(function (data) { const div = d3.select(this); if (!data.slices) { div .selectAll('.chart-title') .append('div') - .data(function(d) { + .data(function (d) { return d.rows ? d.rows : d.columns; }) .enter() @@ -43,13 +43,9 @@ export function chartTitleSplit(selection, parent) { .attr('class', 'chart-title'); if (data.rows) { - d3.select(parent) - .select('.visAxis__splitTitles--x') - .remove(); + d3.select(parent).select('.visAxis__splitTitles--x').remove(); } else { - d3.select(parent) - .select('.visAxis__splitTitles--y') - .remove(); + d3.select(parent).select('.visAxis__splitTitles--y').remove(); } return div; diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/splits.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/splits.test.js index 05f6f72246d4a..2f191cac023b3 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/splits.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/gauge_chart/splits.test.js @@ -23,8 +23,8 @@ import $ from 'jquery'; import { chartSplit } from './chart_split'; import { chartTitleSplit } from './chart_title_split'; -describe('Vislib Gauge Split Function Test Suite', function() { - describe('Column Chart', function() { +describe('Vislib Gauge Split Function Test Suite', function () { + describe('Column Chart', function () { let el; const data = { rows: [ @@ -147,42 +147,38 @@ describe('Vislib Gauge Split Function Test Suite', function() { ], }; - beforeEach(function() { - el = d3 - .select('body') - .append('div') - .attr('class', 'visualization') - .datum(data); + beforeEach(function () { + el = d3.select('body').append('div').attr('class', 'visualization').datum(data); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - describe('chart split function', function() { + describe('chart split function', function () { let fixture; - beforeEach(function() { + beforeEach(function () { fixture = d3.select('.visualization').call(chartSplit); }); - afterEach(function() { + afterEach(function () { fixture.remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect($('.chart').length).toBe(2); }); - it('should add the correct class name', function() { + it('should add the correct class name', function () { expect(!!$('.visWrapper__splitCharts--row').length).toBe(true); }); }); - describe('chart title split function', function() { + describe('chart title split function', function () { let visEl; - beforeEach(function() { + beforeEach(function () { visEl = el.append('div').attr('class', 'visWrapper'); visEl.append('div').attr('class', 'visAxis__splitTitles--x'); visEl.append('div').attr('class', 'visAxis__splitTitles--y'); @@ -190,11 +186,11 @@ describe('Vislib Gauge Split Function Test Suite', function() { visEl.select('.visAxis__splitTitles--y').call(chartTitleSplit); }); - afterEach(function() { + afterEach(function () { visEl.remove(); }); - it('should append the correct number of divs', function() { + it('should append the correct number of divs', function () { expect($('.visAxis__splitTitles--x .chart-title').length).toBe(2); expect($('.visAxis__splitTitles--y .chart-title').length).toBe(2); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_split.js index a9accb8c80d9c..8f754e867b629 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_split.js @@ -26,8 +26,8 @@ import d3 from 'd3'; */ export function chartSplit(selection) { - selection.each(function(data) { - const div = d3.select(this).attr('class', function() { + selection.each(function (data) { + const div = d3.select(this).attr('class', function () { if (data.rows) { return 'visWrapper__splitCharts--row'; } else if (data.columns) { @@ -41,7 +41,7 @@ export function chartSplit(selection) { const charts = div .selectAll('charts') .append('div') - .data(function(d) { + .data(function (d) { if (d.rows) { divClass = 'chart-row'; return d.rows; @@ -55,7 +55,7 @@ export function chartSplit(selection) { }) .enter() .append('div') - .attr('class', function() { + .attr('class', function () { return divClass; }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js index 9d23cf4591699..2c3336b2a3a33 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/splits/pie_chart/chart_title_split.js @@ -28,14 +28,14 @@ import d3 from 'd3'; */ export function chartTitleSplit(selection, parent) { - selection.each(function(data) { + selection.each(function (data) { const div = d3.select(this); if (!data.slices) { div .selectAll('.chart-title') .append('div') - .data(function(d) { + .data(function (d) { return d.rows ? d.rows : d.columns; }) .enter() @@ -43,13 +43,9 @@ export function chartTitleSplit(selection, parent) { .attr('class', 'chart-title'); if (data.rows) { - d3.select(parent) - .select('.visAxis__splitTitles--x') - .remove(); + d3.select(parent).select('.visAxis__splitTitles--x').remove(); } else { - d3.select(parent) - .select('.visAxis__splitTitles--y') - .remove(); + d3.select(parent).select('.visAxis__splitTitles--y').remove(); } return div; diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/types/column_layout.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/layout/types/column_layout.test.js index a27ee57e64a5a..f6ee5d13badf2 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/types/column_layout.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/types/column_layout.test.js @@ -22,7 +22,7 @@ import _ from 'lodash'; import { layoutTypes } from '../layout_types'; -describe('Vislib Column Layout Test Suite', function() { +describe('Vislib Column Layout Test Suite', function () { let columnLayout; let el; const data = { @@ -84,25 +84,22 @@ describe('Vislib Column Layout Test Suite', function() { yAxisLabel: 'Count', }; - beforeEach(function() { - el = d3 - .select('body') - .append('div') - .attr('class', 'visualization'); + beforeEach(function () { + el = d3.select('body').append('div').attr('class', 'visualization'); columnLayout = layoutTypes.point_series(el, data); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - it('should return an array of objects', function() { + it('should return an array of objects', function () { expect(Array.isArray(columnLayout)).toBe(true); expect(_.isObject(columnLayout[0])).toBe(true); }); - it('should throw an error when the wrong number or no arguments provided', function() { - expect(function() { + it('should throw an error when the wrong number or no arguments provided', function () { + expect(function () { layoutTypes.point_series(el); }).toThrow(); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.js b/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.js index ebaf64874d729..438c071d74532 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.js @@ -29,7 +29,7 @@ const createSeriesFromParams = (cfg, seri) => { //up to match with ids in cfg.seriesParams entry that contain only {mainId} const seriId = getSeriId(seri); const matchingSeriesParams = cfg.seriesParams - ? cfg.seriesParams.find(seriConfig => { + ? cfg.seriesParams.find((seriConfig) => { return seriId === seriConfig.data.id; }) : null; @@ -63,7 +63,7 @@ const createSeries = (cfg, series) => { return { type: 'point_series', addTimeMarker: cfg.addTimeMarker, - series: _.map(series, seri => { + series: _.map(series, (seri) => { return createSeriesFromParams(cfg, seri); }), }; @@ -72,7 +72,7 @@ const createSeries = (cfg, series) => { const createCharts = (cfg, data) => { if (data.rows || data.columns) { const charts = data.rows ? data.rows : data.columns; - return charts.map(chart => { + return charts.map((chart) => { return createSeries(cfg, chart.series); }); } @@ -86,7 +86,7 @@ const createCharts = (cfg, data) => { function create(opts) { opts = opts || {}; - return function(cfg, data) { + return function (cfg, data) { const isUserDefinedYAxis = cfg.setYExtents; const defaultYExtents = cfg.defaultYExtents; const config = _.cloneDeep(cfg); @@ -132,17 +132,17 @@ function create(opts) { }, ]; } else { - config.valueAxes.forEach(axis => { + config.valueAxes.forEach((axis) => { if (axis.labels) { axis.labels.axisFormatter = data.data.yAxisFormatter || data.get('yAxisFormatter'); const seriesParams = config.seriesParams && - config.seriesParams.find(seriesParams => seriesParams.valueAxis === axis.id); + config.seriesParams.find((seriesParams) => seriesParams.valueAxis === axis.id); // if there are series assigned to this axis, get the format from the first one if (seriesParams) { const seriesDataId = seriesParams.data.id; const series = (data.data.series || data.get('series')).find( - series => getSeriId(series) === seriesDataId + (series) => getSeriId(series) === seriesDataId ); if (series) { axis.labels.axisFormatter = series.yAxisFormatter; @@ -169,7 +169,7 @@ function create(opts) { }, ]; } else { - const categoryAxis1 = config.categoryAxes.find(categoryAxis => { + const categoryAxis1 = config.categoryAxes.find((categoryAxis) => { return categoryAxis.id === 'CategoryAxis-1'; }); if (categoryAxis1) { @@ -202,7 +202,7 @@ export const vislibPointSeriesTypes = { 'Positive and negative values are not accurately represented by stacked ' + 'area charts. Either changing the chart mode to "overlap" or using a ' + 'bar chart is recommended.', - test: function(_, data) { + test: function (_, data) { if (!data.shouldBeStacked() || data.maxNumberOfSeries() < 2) return; const hasPos = data.getYMax(data._getY) > 0; @@ -216,7 +216,7 @@ export const vislibPointSeriesTypes = { 'Parts of or the entire area chart might not be displayed due to null ' + 'values in the data. A line chart is recommended when displaying data ' + 'with null values.', - test: function(_, data) { + test: function (_, data) { return data.hasNullValues(); }, }, @@ -254,7 +254,7 @@ export const vislibPointSeriesTypes = { }, labels: { filter: false, - axisFormatter: function(val) { + axisFormatter: function (val) { return val; }, }, diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.test.js index 684d8f346744e..62ff873f28134 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/types/point_series.test.js @@ -22,7 +22,7 @@ import percentileTestdata from './testdata_linechart_percentile.json'; import percentileTestdataResult from './testdata_linechart_percentile_result.json'; const maxBucketData = { - get: prop => { + get: (prop) => { return maxBucketData[prop] || maxBucketData.data[prop] || null; }, getLabels: () => [], @@ -83,7 +83,7 @@ describe('vislibPointSeriesTypes', () => { }; const stackedData = { - get: prop => { + get: (prop) => { return stackedSeries[prop] || null; }, getLabels: () => [], @@ -175,7 +175,7 @@ describe('vislibPointSeriesTypes', () => { }); }); -describe('Point Series Config Type Class Test Suite', function() { +describe('Point Series Config Type Class Test Suite', function () { let parsedConfig; const histogramConfig = { type: 'histogram', @@ -200,11 +200,11 @@ describe('Point Series Config Type Class Test Suite', function() { ], }; - describe('histogram chart', function() { - beforeEach(function() { + describe('histogram chart', function () { + beforeEach(function () { parsedConfig = vislibPointSeriesTypes.column(histogramConfig, maxBucketData); }); - it('should not throw an error when more than 25 series are provided', function() { + it('should not throw an error when more than 25 series are provided', function () { expect(parsedConfig.error).toBeUndefined(); }); @@ -214,10 +214,10 @@ describe('Point Series Config Type Class Test Suite', function() { }); }); - describe('line chart', function() { - beforeEach(function() { + describe('line chart', function () { + beforeEach(function () { const percentileDataObj = { - get: prop => { + get: (prop) => { return maxBucketData[prop] || maxBucketData.data[prop] || null; }, getLabels: () => [], @@ -225,7 +225,7 @@ describe('Point Series Config Type Class Test Suite', function() { }; parsedConfig = vislibPointSeriesTypes.line(percentileTestdata.cfg, percentileDataObj); }); - it('should render a percentile line chart', function() { + it('should render a percentile line chart', function () { expect(JSON.stringify(parsedConfig)).toEqual(JSON.stringify(percentileTestdataResult)); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.test.js b/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.test.js index 1ba7d4aaa8a0c..46ef7eac69e72 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.test.js @@ -22,7 +22,7 @@ import d3 from 'd3'; import { VisConfig } from './vis_config'; import { getMockUiState } from '../../fixtures/mocks'; -describe('Vislib VisConfig Class Test Suite', function() { +describe('Vislib VisConfig Class Test Suite', function () { let el; let visConfig; const data = { @@ -85,11 +85,7 @@ describe('Vislib VisConfig Class Test Suite', function() { }; beforeEach(() => { - el = d3 - .select('body') - .append('div') - .attr('class', 'visWrapper') - .node(); + el = d3.select('body').append('div').attr('class', 'visWrapper').node(); visConfig = new VisConfig( { @@ -106,33 +102,33 @@ describe('Vislib VisConfig Class Test Suite', function() { el.remove(); }); - describe('get Method', function() { - it('should be a function', function() { + describe('get Method', function () { + it('should be a function', function () { expect(typeof visConfig.get).toBe('function'); }); - it('should get the property', function() { + it('should get the property', function () { expect(visConfig.get('el')).toBe(el); expect(visConfig.get('type')).toBe('point_series'); }); - it('should return defaults if property does not exist', function() { + it('should return defaults if property does not exist', function () { expect(visConfig.get('this.does.not.exist', 'defaults')).toBe('defaults'); }); - it('should throw an error if property does not exist and defaults were not provided', function() { - expect(function() { + it('should throw an error if property does not exist and defaults were not provided', function () { + expect(function () { visConfig.get('this.does.not.exist'); }).toThrow(); }); }); - describe('set Method', function() { - it('should be a function', function() { + describe('set Method', function () { + it('should be a function', function () { expect(typeof visConfig.set).toBe('function'); }); - it('should set a property', function() { + it('should set a property', function () { visConfig.set('this.does.not.exist', 'it.does.now'); expect(visConfig.get('this.does.not.exist')).toBe('it.does.now'); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/response_handler.js b/src/plugins/vis_type_vislib/public/vislib/response_handler.js index b5f80303b1d74..871ce97ad4480 100644 --- a/src/plugins/vis_type_vislib/public/vislib/response_handler.js +++ b/src/plugins/vis_type_vislib/public/vislib/response_handler.js @@ -87,7 +87,7 @@ function convertTableGroup(tableGroup, convertTable) { const out = {}; let outList; - tables.forEach(function(table) { + tables.forEach(function (table) { if (!outList) { const direction = tableGroup.direction === 'row' ? 'rows' : 'columns'; outList = out[direction] = []; @@ -103,9 +103,9 @@ function convertTableGroup(tableGroup, convertTable) { } function handlerFunction(convertTable) { - return function(response, dimensions) { + return function (response, dimensions) { const tableGroup = tableResponseHandler(response, dimensions); - let converted = convertTableGroup(tableGroup, table => { + let converted = convertTableGroup(tableGroup, (table) => { return convertTable(table, dimensions); }); if (!converted) { diff --git a/src/plugins/vis_type_vislib/public/vislib/response_handler.test.ts b/src/plugins/vis_type_vislib/public/vislib/response_handler.test.ts index 4a8bebc493235..364004d51a4a3 100644 --- a/src/plugins/vis_type_vislib/public/vislib/response_handler.test.ts +++ b/src/plugins/vis_type_vislib/public/vislib/response_handler.test.ts @@ -58,7 +58,7 @@ describe('response_handler', () => { beforeAll(() => { setFormatService({ deserialize: () => ({ - convert: jest.fn(v => v), + convert: jest.fn((v) => v), }), } as any); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/_chart.js index 8e881c2a15726..5ed6d3eb79f4b 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/_chart.js @@ -96,7 +96,7 @@ export class Chart { return datum[labelProp]; } - selection.each(function(datum) { + selection.each(function (datum) { const label = resolveLabel(datum); if (label != null) dataLabel(this, label); }); @@ -110,7 +110,7 @@ export class Chart { destroy() { const selection = d3.select(this.chartEl); this.events.removeAllListeners(); - this.tooltips.forEach(function(tooltip) { + this.tooltips.forEach(function (tooltip) { tooltip.destroy(); }); selection.remove(); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/gauge_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/gauge_chart.js index 729c664032603..b772aa18ed48d 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/gauge_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/gauge_chart.js @@ -85,8 +85,8 @@ export class GaugeChart extends Chart { const self = this; const { gaugeConfig } = this; - return function(selection) { - selection.each(function(data) { + return function (selection) { + selection.each(function (data) { const div = d3.select(this); const { width, height } = self.calcGaugeDim( gaugeConfig.alignment, @@ -98,7 +98,7 @@ export class GaugeChart extends Chart { div.style('text-align', 'center').style('overflow-y', 'auto'); - data.series.forEach(series => { + data.series.forEach((series) => { const svg = div .append('svg') .style('display', 'inline-block') diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/gauges/meter.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/gauges/meter.js index deafe010b6773..a252002534775 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/gauges/meter.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/gauges/meter.js @@ -82,7 +82,7 @@ export class MeterGauge { const colorsRange = this.gaugeConfig.colorsRange; const max = _.last(colorsRange).to; const labels = []; - colorsRange.forEach(range => { + colorsRange.forEach((range) => { const from = isPercentageMode ? Math.round((100 * range.from) / max) : range.from; const to = isPercentageMode ? Math.round((100 * range.to) / max) : range.to; labels.push(`${from} - ${to}`); @@ -106,7 +106,7 @@ export class MeterGauge { } getBucket(val) { - let bucket = _.findIndex(this.gaugeConfig.colorsRange, range => { + let bucket = _.findIndex(this.gaugeConfig.colorsRange, (range) => { return range.from <= val && range.to > val; }); @@ -137,7 +137,7 @@ export class MeterGauge { const scale = svg.append('g'); - this.gaugeConfig.colorsRange.forEach(range => { + this.gaugeConfig.colorsRange.forEach((range) => { const color = this.getColorBucket(range.from); const scaleArc = d3.svg @@ -147,11 +147,7 @@ export class MeterGauge { .innerRadius(radius) .outerRadius(radius + scaleWidth); - scale - .append('path') - .attr('d', scaleArc) - .style('stroke', color) - .style('fill', color); + scale.append('path').attr('d', scaleArc).style('stroke', color).style('fill', color); }); const extents = angle.domain(); @@ -220,13 +216,13 @@ export class MeterGauge { const arc = d3.svg .arc() .startAngle(minAngle) - .endAngle(function(d) { + .endAngle(function (d) { return Math.max(0, Math.min(maxAngle, angle(Math.max(min, d.y)))); }) - .innerRadius(function(d, i, j) { + .innerRadius(function (d, i, j) { return Math.max(0, radius(j + 1) + gaugePadding); }) - .outerRadius(function(d, i, j) { + .outerRadius(function (d, i, j) { return Math.max(0, radius(j) - gaugePadding); }); @@ -234,10 +230,10 @@ export class MeterGauge { .arc() .startAngle(minAngle) .endAngle(maxAngle) - .innerRadius(function(d, i, j) { + .innerRadius(function (d, i, j) { return Math.max(0, radius(j + 1) + bgPadding); }) - .outerRadius(function(d, i, j) { + .outerRadius(function (d, i, j) { return Math.max(0, radius(j) - bgPadding); }); @@ -246,11 +242,11 @@ export class MeterGauge { .data([data]) .enter() .append('g') - .attr('data-label', d => this.getLabel(d.values[0].y)); + .attr('data-label', (d) => this.getLabel(d.values[0].y)); const gauges = gaugeHolders .selectAll('g') - .data(d => d.values) + .data((d) => d.values) .enter(); gauges @@ -263,7 +259,7 @@ export class MeterGauge { .append('path') .attr('d', arc) .attr('class', this.gaugeConfig.outline ? 'visGauge__meter--outline' : undefined) - .style('fill', d => this.getColorBucket(Math.max(min, d.y))); + .style('fill', (d) => this.getColorBucket(Math.max(min, d.y))); const smallContainer = svg.node().getBBox().height < 70; let hiddenLabels = smallContainer; @@ -276,7 +272,7 @@ export class MeterGauge { .append('text') .attr('class', 'chart-label') .attr('y', -5) - .text(d => { + .text((d) => { if (this.gaugeConfig.percentageMode) { const percentage = (d.y - min) / (max - min); return data.yAxisFormatter(percentage); @@ -286,7 +282,7 @@ export class MeterGauge { .attr('style', 'dominant-baseline: central;') .style('text-anchor', 'middle') .style('font-size', '2em') - .style('display', function() { + .style('display', function () { const textLength = this.getBBox().width; // The text is too long if it's larger than the inner free space minus a couple of random pixels for padding. const textTooLong = textLength >= getInnerFreeSpace() - 6; @@ -304,7 +300,7 @@ export class MeterGauge { .text(data.label) .attr('y', -30) .attr('style', 'dominant-baseline: central; text-anchor: middle;') - .style('display', function() { + .style('display', function () { const textLength = this.getBBox().width; const textTooLong = textLength > maxRadius; if (textTooLong) { @@ -319,7 +315,7 @@ export class MeterGauge { .text(this.gaugeConfig.style.subText) .attr('y', 20) .attr('style', 'dominant-baseline: central; text-anchor: middle;') - .style('display', function() { + .style('display', function () { const textLength = this.getBBox().width; const textTooLong = textLength > maxRadius; if (textTooLong) { @@ -334,7 +330,7 @@ export class MeterGauge { } if (isTooltip) { - series.each(function() { + series.each(function () { const gauge = d3.select(this); gauge.call(tooltip.render()); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/pie_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/pie_chart.js index a2cbf0fe295ce..8e3429a39c955 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/pie_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/pie_chart.js @@ -54,7 +54,7 @@ export class PieChart extends Chart { * If so, an error is thrown. */ _validatePieData(charts) { - const isAllZeros = charts.every(chart => { + const isAllZeros = charts.every((chart) => { return chart.slices.children.length === 0; }); @@ -88,12 +88,12 @@ export class PieChart extends Chart { const parentPercent = parent.percentOfParent; const sum = (parent.sumOfChildren = Math.abs( - children.reduce(function(sum, child) { + children.reduce(function (sum, child) { return sum + Math.abs(child.size); }, 0) )); - children.forEach(function(child) { + children.forEach(function (child) { child.percentOfGroup = Math.abs(child.size) / sum; child.percentOfParent = child.percentOfGroup; @@ -138,18 +138,18 @@ export class PieChart extends Chart { const partition = d3.layout .partition() .sort(null) - .value(function(d) { + .value(function (d) { return d.percentOfParent * 100; }); const x = d3.scale.linear().range([0, 2 * Math.PI]); const y = d3.scale.sqrt().range([0, showLabels ? radius * 0.7 : radius]); - const startAngle = function(d) { + const startAngle = function (d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); }; - const endAngle = function(d) { + const endAngle = function (d) { if (d.dx < 1e-8) return x(d.x); return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); }; @@ -158,7 +158,7 @@ export class PieChart extends Chart { .arc() .startAngle(startAngle) .endAngle(endAngle) - .innerRadius(function(d) { + .innerRadius(function (d) { // option for a single layer, i.e pie chart if (d.depth === 1 && !isDonut) { // return no inner radius @@ -167,7 +167,7 @@ export class PieChart extends Chart { return Math.max(0, y(d.y)); }) - .outerRadius(function(d) { + .outerRadius(function (d) { return Math.max(0, y(d.y + d.dy)); }); @@ -186,20 +186,20 @@ export class PieChart extends Chart { .enter() .append('path') .attr('d', arc) - .attr('class', function(d) { + .attr('class', function (d) { if (d.depth === 0) { return; } if (d.depth > maxDepth) maxDepth = d.depth; return 'slice'; }) - .attr('data-test-subj', function(d) { + .attr('data-test-subj', function (d) { if (d.name) { return `pieSlice-${d.name.split(' ').join('-')}`; } }) .call(self._addIdentifier, 'name') - .style('fill', function(d) { + .style('fill', function (d) { if (d.depth === 0) { return 'none'; } @@ -208,10 +208,7 @@ export class PieChart extends Chart { // add labels if (showLabels) { - const labelGroups = labels - .datum(slices) - .selectAll('.label') - .data(partition.nodes); + const labelGroups = labels.datum(slices).selectAll('.label').data(partition.nodes); // create an empty quadtree to hold label positions const svgParentNode = svg.node().parentNode.parentNode; @@ -226,10 +223,10 @@ export class PieChart extends Chart { [-svgBBox.width, -svgBBox.height], [svgBBox.width, svgBBox.height], ]) - .x(function(d) { + .x(function (d) { return d.position.x; }) - .y(function(d) { + .y(function (d) { return d.position.y; })([]); @@ -238,7 +235,7 @@ export class PieChart extends Chart { .append('g') .attr('class', 'label') .append('text') - .text(function(d) { + .text(function (d) { if (d.depth === 0) { d3.select(this.parentNode).remove(); return; @@ -249,10 +246,10 @@ export class PieChart extends Chart { } return d.name; }) - .text(function() { + .text(function () { return truncateLabel(this, truncateLabelLength); }) - .attr('text-anchor', function(d) { + .attr('text-anchor', function (d) { const midAngle = startAngle(d) + (endAngle(d) - startAngle(d)) / 2; return midAngle < Math.PI ? 'start' : 'end'; }) @@ -281,7 +278,7 @@ export class PieChart extends Chart { }; const conflicts = []; - labelLayout.visit(function(node) { + labelLayout.visit(function (node) { if (!node.point) return; if (conflicts.length) return true; @@ -310,13 +307,13 @@ export class PieChart extends Chart { labelLayout.add(d); }) - .attr('x', function(d) { + .attr('x', function (d) { if (d.depth === 0 || !d.position) { return; } return d.position.x; }) - .attr('y', function(d) { + .attr('y', function (d) { if (d.depth === 0 || !d.position) { return; } @@ -325,7 +322,7 @@ export class PieChart extends Chart { labelGroups .append('polyline') - .attr('points', function(d) { + .attr('points', function (d) { if (d.depth === 0 || !d.position) { return; } @@ -363,8 +360,8 @@ export class PieChart extends Chart { draw() { const self = this; - return function(selection) { - selection.each(function(data) { + return function (selection) { + selection.each(function (data) { const slices = data.slices; const div = d3.select(this); const width = $(this).width(); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series.js index f7e50b841e59c..9a25d041f6567 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series.js @@ -58,7 +58,7 @@ export class PointSeries extends Chart { } getSeries(seriesId) { - return this.series.find(series => series.chartData.aggId === seriesId); + return this.series.find((series) => series.chartData.aggId === seriesId); } addBackground(svg, width, height) { @@ -77,10 +77,7 @@ export class PointSeries extends Chart { addGrid(svg) { const { width, height } = svg.node().getBBox(); - return svg - .append('g') - .attr('class', 'grid') - .call(this.handler.grid.draw(width, height)); + return svg.append('g').attr('class', 'grid').call(this.handler.grid.draw(width, height)); } addClipPath(svg) { @@ -153,10 +150,10 @@ export class PointSeries extends Chart { .attr('class', 'endzone') .append('rect') .attr('class', 'zone') - .attr('x', d => (isHorizontal ? d.x : 0)) - .attr('y', d => (isHorizontal ? 0 : d.x)) - .attr('height', d => (isHorizontal ? height : d.w)) - .attr('width', d => (isHorizontal ? d.w : width)); + .attr('x', (d) => (isHorizontal ? d.x : 0)) + .attr('y', (d) => (isHorizontal ? 0 : d.x)) + .attr('height', (d) => (isHorizontal ? height : d.w)) + .attr('width', (d) => (isHorizontal ? d.w : width)); function callPlay(event) { const boundData = event.target.__data__; @@ -197,12 +194,12 @@ export class PointSeries extends Chart { calculateRadiusLimits(data) { this.radii = _(data.series) - .map(function(series) { + .map(function (series) { return _.map(series.values, 'z'); }) .flattenDeep() .reduce( - function(result, val) { + function (result, val) { if (result.min > val) result.min = val; if (result.max < val) result.max = val; return result; @@ -225,8 +222,8 @@ export class PointSeries extends Chart { let div; let svg; - return function(selection) { - selection.each(function(data) { + return function (selection) { + selection.each(function (data) { const el = this; div = d3.select(el); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/_point_series.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/_point_series.js index b882048a6b269..1b084e4142445 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/_point_series.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/_point_series.js @@ -73,7 +73,7 @@ export class PointSeries { getValueAxis() { return ( - _.find(this.handler.valueAxes, axis => { + _.find(this.handler.valueAxes, (axis) => { return axis.axisConfig.get('id') === this.seriesConfig.valueAxis; }) || this.handler.valueAxes[0] ); @@ -81,7 +81,7 @@ export class PointSeries { getCategoryAxis() { return ( - _.find(this.handler.categoryAxes, axis => { + _.find(this.handler.categoryAxes, (axis) => { return axis.axisConfig.get('id') === this.seriesConfig.categoryAxis; }) || this.handler.categoryAxes[0] ); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/area_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/area_chart.js index 274ae82271e96..e3e2d31ecd4f4 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/area_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/area_chart.js @@ -52,12 +52,12 @@ export class AreaChart extends PointSeries { // Default opacity should return to 0.6 on mouseout const defaultOpacity = 0.6; this.seriesConfig.defaultOpacity = defaultOpacity; - handler.highlight = function(element) { + handler.highlight = function (element) { const label = this.getAttribute('data-label'); if (!label) return; const highlightOpacity = 0.8; - const highlightElements = $('[data-label]', element.parentNode).filter(function(els, el) { + const highlightElements = $('[data-label]', element.parentNode).filter(function (els, el) { return `${$(el).data('label')}` === label; }); $('[data-label]', element.parentNode) @@ -65,7 +65,7 @@ export class AreaChart extends PointSeries { .css('opacity', defaultOpacity / 2); // half of the default opacity highlightElements.css('opacity', highlightOpacity); }; - handler.unHighlight = function(element) { + handler.unHighlight = function (element) { $('[data-label]', element).css('opacity', defaultOpacity); //The legend should keep max opacity @@ -85,7 +85,7 @@ export class AreaChart extends PointSeries { const isHorizontal = this.getCategoryAxis().axisConfig.isHorizontal(); // Data layers - const layer = svg.append('g').attr('class', function(d, i) { + const layer = svg.append('g').attr('class', function (d, i) { return 'series series-' + i; }); @@ -95,7 +95,7 @@ export class AreaChart extends PointSeries { .attr('data-label', data.label) .style('fill', () => color(data.label)) .style('stroke', () => color(data.label)) - .classed('visAreaChart__overlapArea', function() { + .classed('visAreaChart__overlapArea', function () { return isOverlapping; }) .attr('clip-path', 'url(#' + this.baseChart.clipPathId + ')'); @@ -120,25 +120,17 @@ export class AreaChart extends PointSeries { function getArea() { if (isHorizontal) { - return d3.svg - .area() - .x(x) - .y0(y0) - .y1(y1); + return d3.svg.area().x(x).y0(y0).y1(y1); } else { - return d3.svg - .area() - .y(x) - .x0(y0) - .x1(y1); + return d3.svg.area().y(x).x0(y0).x1(y1); } } // update path - .attr('d', function() { + .attr('d', function () { const area = getArea() - .defined(function(d) { + .defined(function (d) { return !_.isNull(d.y); }) .interpolate(interpolate); @@ -242,8 +234,8 @@ export class AreaChart extends PointSeries { draw() { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const svg = self.chartEl.append('g'); svg.data([self.chartData]); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/column_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/column_chart.js index 4b422d9b1419f..cc64e0d746fbf 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/column_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/column_chart.js @@ -75,7 +75,7 @@ export class ColumnChart extends PointSeries { .attr('clip-path', 'url(#' + this.baseChart.clipPathId + ')'); const bars = layer.selectAll('rect').data( - data.values.filter(function(d) { + data.values.filter(function (d) { return !_.isNull(d.y); }) ); @@ -206,7 +206,7 @@ export class ColumnChart extends PointSeries { const layer = d3.select(bars[0].parentNode); const barLabels = layer.selectAll('text').data( - chartData.values.filter(function(d) { + chartData.values.filter(function (d) { return !_.isNull(d.y); }) ); @@ -329,7 +329,7 @@ export class ColumnChart extends PointSeries { const layer = d3.select(bars[0].parentNode); const barLabels = layer.selectAll('text').data( - chartData.values.filter(function(d) { + chartData.values.filter(function (d) { return !_.isNull(d.y); }) ); @@ -366,8 +366,8 @@ export class ColumnChart extends PointSeries { draw() { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const svg = self.chartEl.append('g'); svg.data([self.chartData]); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/heatmap_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/heatmap_chart.js index 6f497ae057d72..4564721464767 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/heatmap_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/heatmap_chart.js @@ -68,7 +68,7 @@ export class HeatmapChart extends PointSeries { const labels = []; const maxColorCnt = 10; if (cfg.get('setColorRange')) { - colorsRange.forEach(range => { + colorsRange.forEach((range) => { const from = isFinite(range.from) ? zAxisFormatter(range.from) : range.from; const to = isFinite(range.to) ? zAxisFormatter(range.to) : range.to; labels.push(`${from} - ${to}`); @@ -150,9 +150,7 @@ export class HeatmapChart extends PointSeries { if (this.getCategoryAxis().axisConfig.isTimeDomain()) { const { min, interval } = this.handler.data.get('ordered'); const start = min; - const end = moment(min) - .add(interval) - .valueOf(); + const end = moment(min).add(interval).valueOf(); barWidth = xScale(end) - xScale(start); if (!isHorizontal) barWidth *= -1; @@ -170,7 +168,7 @@ export class HeatmapChart extends PointSeries { function getColorBucket(d) { let val = 0; if (setColorRange && colorsRange.length) { - const bucket = _.find(colorsRange, range => { + const bucket = _.find(colorsRange, (range) => { return range.from <= d.y && range.to > d.y; }); return bucket ? colorsRange.indexOf(bucket) : -1; @@ -205,10 +203,7 @@ export class HeatmapChart extends PointSeries { const squareWidth = barWidth || xScale.rangeBand(); const squareHeight = yScale.rangeBand(); - squares - .enter() - .append('g') - .attr('class', 'square'); + squares.enter().append('g').attr('class', 'square'); squares .append('rect') @@ -219,7 +214,7 @@ export class HeatmapChart extends PointSeries { .attr('data-label', label) .attr('fill', z) .attr('style', 'cursor: pointer; stroke: black; stroke-width: 0.1px') - .style('display', d => { + .style('display', (d) => { return d.hide ? 'none' : 'initial'; }); @@ -247,7 +242,7 @@ export class HeatmapChart extends PointSeries { labelColor = zAxisConfig.get('labels.color'); } else { // Otherwise provide a function that will calculate a light or dark color - labelColor = d => { + labelColor = (d) => { const bgColor = z(d); const color = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(bgColor); return color && isColorDark(parseInt(color[1]), parseInt(color[2]), parseInt(color[3])) @@ -259,8 +254,8 @@ export class HeatmapChart extends PointSeries { let hiddenLabels = false; squares .append('text') - .text(d => zAxisFormatter(d.y)) - .style('display', function(d) { + .text((d) => zAxisFormatter(d.y)) + .style('display', function (d) { const textLength = this.getBBox().width; const textHeight = this.getBBox().height; const textTooLong = textLength > maxLength; @@ -273,15 +268,15 @@ export class HeatmapChart extends PointSeries { .style('dominant-baseline', 'central') .style('text-anchor', 'middle') .style('fill', labelColor) - .attr('x', function(d) { + .attr('x', function (d) { const center = x(d) + squareWidth / 2; return center; }) - .attr('y', function(d) { + .attr('y', function (d) { const center = y(d) + squareHeight / 2; return center; }) - .attr('transform', function(d) { + .attr('transform', function (d) { const horizontalCenter = x(d) + squareWidth / 2; const verticalCenter = y(d) + squareHeight / 2; return `rotate(${rotate},${horizontalCenter},${verticalCenter})`; @@ -307,8 +302,8 @@ export class HeatmapChart extends PointSeries { draw() { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const svg = self.chartEl.append('g'); svg.data([self.chartData]); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/line_chart.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/line_chart.js index 0038b4401b302..64fbae7d1ac8c 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/line_chart.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/point_series/line_chart.js @@ -70,7 +70,7 @@ export class LineChart extends PointSeries { .attr('clip-path', 'url(#' + this.baseChart.clipPathId + ')'); const circles = layer.selectAll('circle').data(function appendData() { - return data.values.filter(function(d) { + return data.values.filter(function (d) { return !_.isNull(d.y) && (d.y || !d.y0); }); }); @@ -189,7 +189,7 @@ export class LineChart extends PointSeries { .attr('d', () => { const d3Line = d3.svg .line() - .defined(function(d) { + .defined(function (d) { return !_.isNull(d.y); }) .interpolate(interpolate) @@ -215,8 +215,8 @@ export class LineChart extends PointSeries { draw() { const self = this; - return function(selection) { - selection.each(function() { + return function (selection) { + selection.each(function () { const svg = self.chartEl.append('g'); svg.data([self.chartData]); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.js index 5ffb4fd106f15..f652d7383ff00 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.js @@ -35,7 +35,7 @@ export class TimeMarker { this.xScale = xScale; this.height = height; this.times = times.length - ? times.map(function(d) { + ? times.map(function (d) { return { time: dateMath.parse(d.time), class: d.class || 'time-marker', @@ -49,7 +49,7 @@ export class TimeMarker { _isTimeBasedChart(selection) { const data = selection.data(); - return data.every(function(datum) { + return data.every(function (datum) { return datum.ordered && datum.ordered.date; }); } @@ -60,29 +60,29 @@ export class TimeMarker { // return if not time based chart if (!self._isTimeBasedChart(selection)) return; - selection.each(function() { + selection.each(function () { d3.select(this) .selectAll('time-marker') .data(self.times) .enter() .append('line') - .attr('class', function(d) { + .attr('class', function (d) { return d.class; }) .attr('pointer-events', 'none') - .attr('stroke', function(d) { + .attr('stroke', function (d) { return d.color; }) - .attr('stroke-width', function(d) { + .attr('stroke-width', function (d) { return d.width; }) - .attr('stroke-opacity', function(d) { + .attr('stroke-opacity', function (d) { return d.opacity; }) - .attr('x1', function(d) { + .attr('x1', function (d) { return self.xScale(d.time); }) - .attr('x2', function(d) { + .attr('x2', function (d) { return self.xScale(d.time); }) .attr('y1', self.height) diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.test.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.test.js index 058bdb5de8785..6fa3f42e43d7e 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/time_marker.test.js @@ -24,14 +24,14 @@ import series from '../../fixtures/mock_data/date_histogram/_series'; import terms from '../../fixtures/mock_data/terms/_columns'; import { TimeMarker } from './time_marker'; -describe('Vislib Time Marker Test Suite', function() { +describe('Vislib Time Marker Test Suite', function () { const height = 50; const color = '#ff0000'; const opacity = 0.5; const width = 3; const customClass = 'custom-time-marker'; const dateMathTimes = ['now-1m', 'now-5m', 'now-15m']; - const myTimes = dateMathTimes.map(function(dateMathString) { + const myTimes = dateMathTimes.map(function (dateMathString) { return { time: dateMathString, class: customClass, @@ -40,9 +40,9 @@ describe('Vislib Time Marker Test Suite', function() { width: width, }; }); - const getExtent = function(dataArray, func) { - return func(dataArray, function(obj) { - return func(obj.values, function(d) { + const getExtent = function (dataArray, func) { + return func(dataArray, function (obj) { + return func(obj.values, function (d) { return d.x; }); }); @@ -56,83 +56,77 @@ describe('Vislib Time Marker Test Suite', function() { let maxDomain; let domain; - beforeEach(function() { + beforeEach(function () { minDomain = getExtent(series.series, d3.min); maxDomain = getExtent(series.series, d3.max); domain = [minDomain, maxDomain]; - xScale = d3.time - .scale() - .domain(domain) - .range([0, 500]); + xScale = d3.time.scale().domain(domain).range([0, 500]); defaultMarker = new TimeMarker(times, xScale, height); customMarker = new TimeMarker(myTimes, xScale, height); - selection = d3 - .select('body') - .append('div') - .attr('class', 'marker'); + selection = d3.select('body').append('div').attr('class', 'marker'); selection.datum(series); }); - afterEach(function() { + afterEach(function () { selection.remove('*'); selection = null; defaultMarker = null; }); - describe('_isTimeBaseChart method', function() { + describe('_isTimeBaseChart method', function () { let boolean; let newSelection; - it('should return true when data is time based', function() { + it('should return true when data is time based', function () { boolean = defaultMarker._isTimeBasedChart(selection); expect(boolean).toBe(true); }); - it('should return false when data is not time based', function() { + it('should return false when data is not time based', function () { newSelection = selection.datum(terms); boolean = defaultMarker._isTimeBasedChart(newSelection); expect(boolean).toBe(false); }); }); - describe('render method', function() { + describe('render method', function () { let lineArray; - beforeEach(function() { + beforeEach(function () { defaultMarker.render(selection); customMarker.render(selection); lineArray = document.getElementsByClassName('custom-time-marker'); }); - it('should render the default line', function() { + it('should render the default line', function () { expect(!!$('line.time-marker').length).toBe(true); }); - it('should render the custom (user defined) lines', function() { + it('should render the custom (user defined) lines', function () { expect($('line.custom-time-marker').length).toBe(myTimes.length); }); - it('should set the class', function() { - Array.prototype.forEach.call(lineArray, function(line) { + it('should set the class', function () { + Array.prototype.forEach.call(lineArray, function (line) { expect(line.getAttribute('class')).toBe(customClass); }); }); - it('should set the stroke', function() { - Array.prototype.forEach.call(lineArray, function(line) { + it('should set the stroke', function () { + Array.prototype.forEach.call(lineArray, function (line) { expect(line.getAttribute('stroke')).toBe(color); }); }); - it('should set the stroke-opacity', function() { - Array.prototype.forEach.call(lineArray, function(line) { + it('should set the stroke-opacity', function () { + Array.prototype.forEach.call(lineArray, function (line) { expect(+line.getAttribute('stroke-opacity')).toBe(opacity); }); }); - it('should set the stroke-width', function() { - Array.prototype.forEach.call(lineArray, function(line) { + it('should set the stroke-width', function () { + Array.prototype.forEach.call(lineArray, function (line) { expect(+line.getAttribute('stroke-width')).toBe(width); }); }); diff --git a/src/plugins/vis_type_vislib/public/vislib/visualizations/vis_types.test.js b/src/plugins/vis_type_vislib/public/vislib/visualizations/vis_types.test.js index df044f46460c8..a6f2404169f62 100644 --- a/src/plugins/vis_type_vislib/public/vislib/visualizations/vis_types.test.js +++ b/src/plugins/vis_type_vislib/public/vislib/visualizations/vis_types.test.js @@ -21,18 +21,18 @@ import _ from 'lodash'; import { visTypes } from './vis_types'; -describe('Vislib Vis Types Test Suite', function() { +describe('Vislib Vis Types Test Suite', function () { let visFunc; - beforeEach(function() { + beforeEach(function () { visFunc = visTypes.point_series; }); - it('should be an object', function() { + it('should be an object', function () { expect(_.isObject(visTypes)).toBe(true); }); - it('should return a function', function() { + it('should return a function', function () { expect(typeof visFunc).toBe('function'); }); }); diff --git a/src/plugins/visualizations/public/components/visualization.test.js b/src/plugins/visualizations/public/components/visualization.test.js index f2844e3aab113..31ce09d6f4a1c 100644 --- a/src/plugins/visualizations/public/components/visualization.test.js +++ b/src/plugins/visualizations/public/components/visualization.test.js @@ -31,7 +31,7 @@ class VisualizationStub { } render() { - renderPromise = new Promise(resolve => { + renderPromise = new Promise((resolve) => { this.el.innerText = this.vis.params.markdown; resolve(); }); @@ -55,10 +55,10 @@ describe('', () => { beforeEach(() => { vis = { - setUiState: function(uiState) { + setUiState: function (uiState) { this.uiState = uiState; }, - getUiState: function() { + getUiState: function () { return this.uiState; }, params: {}, diff --git a/src/plugins/visualizations/public/components/visualization_chart.test.js b/src/plugins/visualizations/public/components/visualization_chart.test.js index 04d8bb253621a..ed73dee93e13e 100644 --- a/src/plugins/visualizations/public/components/visualization_chart.test.js +++ b/src/plugins/visualizations/public/components/visualization_chart.test.js @@ -32,7 +32,7 @@ class VisualizationStub { } render() { - renderPromise = new Promise(resolve => { + renderPromise = new Promise((resolve) => { this.el.textContent = this.vis.params.markdown; resolve(); }); diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts index 0306b943cbf2b..985062b682293 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts @@ -167,7 +167,7 @@ export class VisualizeEmbeddable extends Embeddable { + getKeys(visCustomizations).forEach((key) => { this.vis.uiState.set(key, visCustomizations[key]); }); } @@ -242,7 +242,7 @@ export class VisualizeEmbeddable extends Embeddable { + this.handler.events$.subscribe(async (event) => { // maps hack, remove once esaggs function is cleaned up and ready to accept variables if (event.name === 'bounds') { const agg = this.vis.data.aggs!.aggs.find((a: any) => { @@ -267,9 +267,7 @@ export class VisualizeEmbeddable extends Embeddable { + this.handler.render$.subscribe((count) => { div.removeAttribute('data-loading'); div.setAttribute('data-render-complete', 'true'); div.setAttribute('data-rendering-count', count.toString()); @@ -306,7 +304,7 @@ export class VisualizeEmbeddable extends Embeddable s.unsubscribe()); + this.subscriptions.forEach((s) => s.unsubscribe()); this.vis.uiState.off('change', this.uiStateChangeHandler); this.vis.uiState.off('reload', this.reload); diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx b/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx index 466224877c52f..c4aa4c262edb0 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable_factory.tsx @@ -66,17 +66,17 @@ export class VisualizeEmbeddableFactory name: i18n.translate('visualizations.savedObjectName', { defaultMessage: 'Visualization' }), includeFields: ['visState'], type: 'visualization', - getIconForSavedObject: savedObject => { + getIconForSavedObject: (savedObject) => { return ( getTypes().get(JSON.parse(savedObject.attributes.visState).type).icon || 'visualizeApp' ); }, - getTooltipForSavedObject: savedObject => { + getTooltipForSavedObject: (savedObject) => { return `${savedObject.attributes.title} (${ getTypes().get(JSON.parse(savedObject.attributes.visState).type).title })`; }, - showSavedObject: savedObject => { + showSavedObject: (savedObject) => { const typeName: string = JSON.parse(savedObject.attributes.visState).type; const visType = getTypes().get(typeName); if (!visType) { diff --git a/src/plugins/visualizations/public/expression_functions/vis_dimension.ts b/src/plugins/visualizations/public/expression_functions/vis_dimension.ts index b9d1a23b1c503..286804d2fa76a 100644 --- a/src/plugins/visualizations/public/expression_functions/vis_dimension.ts +++ b/src/plugins/visualizations/public/expression_functions/vis_dimension.ts @@ -81,7 +81,7 @@ export const visDimension = (): ExpressionFunctionDefinition< const accessor = typeof args.accessor === 'number' ? args.accessor - : input.columns.find(c => c.id === args.accessor); + : input.columns.find((c) => c.id === args.accessor); if (accessor === undefined) { throw new Error( diff --git a/src/plugins/visualizations/public/expressions/visualization_function.ts b/src/plugins/visualizations/public/expressions/visualization_function.ts index 52177f6ec381a..222479158934b 100644 --- a/src/plugins/visualizations/public/expressions/visualization_function.ts +++ b/src/plugins/visualizations/public/expressions/visualization_function.ts @@ -119,7 +119,7 @@ export const visualization = (): ExpressionFunctionVisualization => ({ } }); - Object.keys(schemas).forEach(key => { + Object.keys(schemas).forEach((key) => { schemas[key].forEach((i: any) => { if (input.columns[i] && input.columns[i].aggConfig) { input.columns[i].aggConfig.schema = key; diff --git a/src/plugins/visualizations/public/legacy/build_pipeline.ts b/src/plugins/visualizations/public/legacy/build_pipeline.ts index f3192ba3da81f..5d74cb3d3b1e5 100644 --- a/src/plugins/visualizations/public/legacy/build_pipeline.ts +++ b/src/plugins/visualizations/public/legacy/build_pipeline.ts @@ -186,9 +186,7 @@ export const prepareJson = (variable: string, data?: object): string => { if (data === undefined) { return ''; } - return `${variable}='${JSON.stringify(data) - .replace(/\\/g, `\\\\`) - .replace(/'/g, `\\'`)}' `; + return `${variable}='${JSON.stringify(data).replace(/\\/g, `\\\\`).replace(/'/g, `\\'`)}' `; }; export const escapeString = (data: string): string => { @@ -238,7 +236,7 @@ const adjustVislibDimensionFormmaters = (vis: Vis, dimensions: { y: any[] }): vo const visConfig = vis.params; const responseAggs = vis.data.aggs!.getResponseAggs().filter((agg: IAggConfig) => agg.enabled); - (dimensions.y || []).forEach(yDimension => { + (dimensions.y || []).forEach((yDimension) => { const yAgg = responseAggs[yDimension.accessor]; const seriesParam = (visConfig.seriesParams || []).find( (param: any) => param.data.id === yAgg.id @@ -258,25 +256,25 @@ const adjustVislibDimensionFormmaters = (vis: Vis, dimensions: { y: any[] }): vo }; export const buildPipelineVisFunction: BuildPipelineVisFunction = { - vega: params => { + vega: (params) => { return `vega ${prepareString('spec', params.spec)}`; }, - input_control_vis: params => { + input_control_vis: (params) => { return `input_control_vis ${prepareJson('visConfig', params)}`; }, metrics: (params, schemas, uiState = {}) => { const paramsJson = prepareJson('params', params); const uiStateJson = prepareJson('uiState', uiState); - const paramsArray = [paramsJson, uiStateJson].filter(param => Boolean(param)); + const paramsArray = [paramsJson, uiStateJson].filter((param) => Boolean(param)); return `tsvb ${paramsArray.join(' ')}`; }, - timelion: params => { + timelion: (params) => { const expression = prepareString('expression', params.expression); const interval = prepareString('interval', params.interval); return `timelion_vis ${expression}${interval}`; }, - markdown: params => { + markdown: (params) => { const { markdown, fontSize, openLinksInNewTab } = params; let escapedMarkdown = ''; if (typeof markdown === 'string' || markdown instanceof String) { @@ -397,7 +395,7 @@ const buildVisConfig: BuildVisConfigFunction = { } return visConfig; }, - metric: schemas => { + metric: (schemas) => { const visConfig = { dimensions: {} } as any; visConfig.dimensions.metrics = schemas.metric; if (schemas.group) { @@ -405,7 +403,7 @@ const buildVisConfig: BuildVisConfigFunction = { } return visConfig; }, - tagcloud: schemas => { + tagcloud: (schemas) => { const visConfig = {} as any; visConfig.metric = schemas.metric[0]; if (schemas.segment) { @@ -413,7 +411,7 @@ const buildVisConfig: BuildVisConfigFunction = { } return visConfig; }, - region_map: schemas => { + region_map: (schemas) => { const visConfig = {} as any; visConfig.metric = schemas.metric[0]; if (schemas.segment) { @@ -421,7 +419,7 @@ const buildVisConfig: BuildVisConfigFunction = { } return visConfig; }, - tile_map: schemas => { + tile_map: (schemas) => { const visConfig = {} as any; visConfig.dimensions = { metric: schemas.metric[0], @@ -430,7 +428,7 @@ const buildVisConfig: BuildVisConfigFunction = { }; return visConfig; }, - pie: schemas => { + pie: (schemas) => { const visConfig = {} as any; visConfig.dimensions = { metric: schemas.metric[0], diff --git a/src/plugins/visualizations/public/legacy/memoize.ts b/src/plugins/visualizations/public/legacy/memoize.ts index fea1b89262081..4d6a735b67c08 100644 --- a/src/plugins/visualizations/public/legacy/memoize.ts +++ b/src/plugins/visualizations/public/legacy/memoize.ts @@ -35,7 +35,7 @@ function memoizeLast any>(func: T): T { let prevCall: MemoizedCall | NeverCalled = neverCalled; // We need to use a `function` here for proper this passing. - const memoizedFunction = function(this: any, ...args: any[]) { + const memoizedFunction = function (this: any, ...args: any[]) { if ( prevCall !== neverCalled && prevCall.this === this && diff --git a/src/plugins/visualizations/public/legacy/vis_update_state.js b/src/plugins/visualizations/public/legacy/vis_update_state.js index e345b9e5b8c9a..edaf388e21060 100644 --- a/src/plugins/visualizations/public/legacy/vis_update_state.js +++ b/src/plugins/visualizations/public/legacy/vis_update_state.js @@ -42,7 +42,7 @@ function convertHeatmapLabelColor(visState) { */ function convertTermAggregation(visState) { if (visState.aggs) { - visState.aggs.forEach(agg => { + visState.aggs.forEach((agg) => { if (agg.type === 'terms' && agg.params && agg.params.orderBy === '_term') { agg.params.orderBy = '_key'; } @@ -60,7 +60,7 @@ function convertPropertyNames(visState) { function convertDateHistogramScaleMetrics(visState) { if (visState.aggs) { - visState.aggs.forEach(agg => { + visState.aggs.forEach((agg) => { if ( agg.type === 'date_histogram' && agg.params && @@ -153,7 +153,7 @@ function convertSeriesParams(visState) { * It will return the updated version as Kibana would expect it. It does not modify * the passed state. */ -export const updateOldState = visState => { +export const updateOldState = (visState) => { if (!visState) return visState; const newState = _.cloneDeep(visState); diff --git a/src/plugins/visualizations/public/persisted_state/persisted_state.ts b/src/plugins/visualizations/public/persisted_state/persisted_state.ts index 3e675574fd678..7465f969f456f 100644 --- a/src/plugins/visualizations/public/persisted_state/persisted_state.ts +++ b/src/plugins/visualizations/public/persisted_state/persisted_state.ts @@ -91,7 +91,7 @@ export class PersistedState extends EventEmitter { } clearAllKeys() { - Object.getOwnPropertyNames(this._changedState).forEach(key => { + Object.getOwnPropertyNames(this._changedState).forEach((key) => { this.set(key, null); }); } @@ -229,7 +229,7 @@ export class PersistedState extends EventEmitter { const sourceObj = merge({}, this._changedState); // handler arguments are (targetValue, sourceValue, key, target, source) - const mergeMethod = function(targetValue: any, sourceValue: any, mergeKey: string) { + const mergeMethod = function (targetValue: any, sourceValue: any, mergeKey: string) { // if not initial state, skip default merge method (ie. return value, see note below) if (!initialState && isEqual(keyPath, self.getIndex(mergeKey))) { // use the sourceValue or fall back to targetValue diff --git a/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts b/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts index c0203a7441a61..0c27c3a2c7782 100644 --- a/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts +++ b/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts @@ -40,7 +40,7 @@ export async function findListItems({ mapSavedObjectApiHits: SavedObjectLoader['mapSavedObjectApiHits']; }) { const extensions = visTypes - .map(v => v.appExtensions?.visualizations) + .map((v) => v.appExtensions?.visualizations) .filter(Boolean) as VisualizationsAppExtension[]; const extensionByType = extensions.reduce((acc, m) => { return m!.docTypes.reduce((_acc, type) => { @@ -49,13 +49,7 @@ export async function findListItems({ }, acc); }, {} as { [visType: string]: VisualizationsAppExtension }); const searchOption = (field: string, ...defaults: string[]) => - _(extensions) - .pluck(field) - .concat(defaults) - .compact() - .flatten() - .uniq() - .value() as string[]; + _(extensions).pluck(field).concat(defaults).compact().flatten().uniq().value() as string[]; const searchOptions = { type: searchOption('docTypes', 'visualization'), searchFields: searchOption('searchFields', 'title^3', 'description'), @@ -71,7 +65,7 @@ export async function findListItems({ return { total, - hits: savedObjects.map(savedObject => { + hits: savedObjects.map((savedObject) => { const config = extensionByType[savedObject.type]; if (config) { diff --git a/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references.ts b/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references.ts index d28853694b653..bdc9038fc6a77 100644 --- a/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references.ts +++ b/src/plugins/visualizations/public/saved_visualizations/saved_visualization_references.ts @@ -35,7 +35,7 @@ export function extractReferences({ updatedAttributes.searchSourceFields as any ); updatedAttributes.searchSourceFields = searchSource; - searchSourceReferences.forEach(r => updatedReferences.push(r)); + searchSourceReferences.forEach((r) => updatedReferences.push(r)); } // Extract saved search @@ -83,7 +83,7 @@ export function injectReferences(savedObject: VisSavedObject, references: SavedO } if (savedObject.savedSearchRefName) { const savedSearchReference = references.find( - reference => reference.name === savedObject.savedSearchRefName + (reference) => reference.name === savedObject.savedSearchRefName ); if (!savedSearchReference) { throw new Error(`Could not find saved search reference "${savedObject.savedSearchRefName}"`); @@ -97,7 +97,7 @@ export function injectReferences(savedObject: VisSavedObject, references: SavedO if (!control.indexPatternRefName) { return; } - const reference = references.find(ref => ref.name === control.indexPatternRefName); + const reference = references.find((ref) => ref.name === control.indexPatternRefName); if (!reference) { throw new Error(`Could not find index pattern reference "${control.indexPatternRefName}"`); } diff --git a/src/plugins/visualizations/public/vis.test.ts b/src/plugins/visualizations/public/vis.test.ts index aba735656b7d9..a0da8d83bed51 100644 --- a/src/plugins/visualizations/public/vis.test.ts +++ b/src/plugins/visualizations/public/vis.test.ts @@ -24,7 +24,7 @@ jest.mock('./services', () => { constructor() {} render(): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(); }); } @@ -62,7 +62,7 @@ jest.mock('./services', () => { }; }); -describe('Vis Class', function() { +describe('Vis Class', function () { let vis: Vis; const stateFixture = { type: 'pie', @@ -80,12 +80,12 @@ describe('Vis Class', function() { params: { isDonut: true }, }; - beforeEach(async function() { + beforeEach(async function () { vis = new Vis('test', stateFixture as any); await vis.setState(stateFixture as any); }); - const verifyVis = function(visToVerify: Vis) { + const verifyVis = function (visToVerify: Vis) { expect(visToVerify).toHaveProperty('data'); expect(visToVerify.data).toHaveProperty('aggs'); expect(visToVerify.data.aggs!.aggs).toHaveLength(3); @@ -96,14 +96,14 @@ describe('Vis Class', function() { expect(visToVerify.params).toHaveProperty('isDonut', true); }; - describe('initialization', function() { - it('should set the state', function() { + describe('initialization', function () { + it('should set the state', function () { verifyVis(vis); }); }); - describe('getState()', function() { - it('should get a state that represents the... er... state', function() { + describe('getState()', function () { + it('should get a state that represents the... er... state', function () { const state = vis.serialize(); expect(state).toHaveProperty('type', 'pie'); @@ -115,12 +115,12 @@ describe('Vis Class', function() { }); }); - describe('isHierarchical()', function() { - it('should return false for non-hierarchical vis (like histogram)', function() { + describe('isHierarchical()', function () { + it('should return false for non-hierarchical vis (like histogram)', function () { expect(vis.isHierarchical()).toBe(false); }); - it('should return true for hierarchical vis (like pie)', function() { + it('should return true for hierarchical vis (like pie)', function () { vis.type.hierarchicalData = true; expect(vis.isHierarchical()).toBe(true); }); diff --git a/src/plugins/visualizations/public/vis.ts b/src/plugins/visualizations/public/vis.ts index 916467ac08f4f..aaab0566af65e 100644 --- a/src/plugins/visualizations/public/vis.ts +++ b/src/plugins/visualizations/public/vis.ts @@ -173,7 +173,7 @@ export class Vis { } serialize(): SerializedVis { - const aggs = this.data.aggs ? this.data.aggs.aggs.map(agg => agg.toJSON()) : []; + const aggs = this.data.aggs ? this.data.aggs.aggs.map((agg) => agg.toJSON()) : []; return { id: this.id, title: this.title, @@ -211,7 +211,9 @@ export class Vis { const newConfigs = [...configStates]; schemas .filter((schema: any) => Array.isArray(schema.defaults) && schema.defaults.length > 0) - .filter((schema: any) => !configStates.find(agg => agg.schema && agg.schema === schema.name)) + .filter( + (schema: any) => !configStates.find((agg) => agg.schema && agg.schema === schema.name) + ) .forEach((schema: any) => { const defaultSchemaConfig = schema.defaults.slice(0, schema.max); defaultSchemaConfig.forEach((d: any) => newConfigs.push(d)); diff --git a/src/plugins/visualizations/public/vis_types/vis_type_alias_registry.ts b/src/plugins/visualizations/public/vis_types/vis_type_alias_registry.ts index 87a72e71fcd75..6f18cbc5026ec 100644 --- a/src/plugins/visualizations/public/vis_types/vis_type_alias_registry.ts +++ b/src/plugins/visualizations/public/vis_types/vis_type_alias_registry.ts @@ -68,8 +68,8 @@ interface VisTypeAliasRegistry { export const visTypeAliasRegistry: VisTypeAliasRegistry = { get: () => [...registry], - add: newVisTypeAlias => { - if (registry.find(visTypeAlias => visTypeAlias.name === newVisTypeAlias.name)) { + add: (newVisTypeAlias) => { + if (registry.find((visTypeAlias) => visTypeAlias.name === newVisTypeAlias.name)) { throw new Error(`${newVisTypeAlias.name} already registered`); } registry.push(newVisTypeAlias); diff --git a/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx b/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx index e074a388fab08..eb64f84ca59c4 100644 --- a/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx +++ b/src/plugins/visualizations/public/wizard/new_vis_modal.test.tsx @@ -54,7 +54,7 @@ describe('NewVisModal', () => { ]; const visTypes: TypesStart = { get: (id: string) => { - return _visTypes.find(vis => vis.name === id) as VisType; + return _visTypes.find((vis) => vis.name === id) as VisType; }, all: () => { return _visTypes as VisType[]; diff --git a/src/plugins/visualizations/public/wizard/type_selection/new_vis_help.tsx b/src/plugins/visualizations/public/wizard/type_selection/new_vis_help.tsx index e84314853ba4c..fc48438904589 100644 --- a/src/plugins/visualizations/public/wizard/type_selection/new_vis_help.tsx +++ b/src/plugins/visualizations/public/wizard/type_selection/new_vis_help.tsx @@ -37,7 +37,7 @@ export function NewVisHelp(props: Props) { defaultMessage="Start creating your visualization by selecting a type for that visualization." />

    - {props.promotedTypes.map(t => ( + {props.promotedTypes.map((t) => (

    {t.promotion!.description} diff --git a/src/plugins/visualizations/public/wizard/type_selection/type_selection.tsx b/src/plugins/visualizations/public/wizard/type_selection/type_selection.tsx index c5f411fc6d933..47757593958d6 100644 --- a/src/plugins/visualizations/public/wizard/type_selection/type_selection.tsx +++ b/src/plugins/visualizations/public/wizard/type_selection/type_selection.tsx @@ -124,7 +124,9 @@ class TypeSelection extends React.Component type.highlighted).length }} + values={{ + resultCount: visTypes.filter((type) => type.highlighted).length, + }} /> )} @@ -153,7 +155,7 @@ class TypeSelection extends React.Component t.promotion)} + promotedTypes={(visTypes as VisTypeAliasListEntry[]).filter((t) => t.promotion)} onPromotionClicked={this.props.onVisTypeSelected} /> @@ -169,7 +171,7 @@ class TypeSelection extends React.Component { - const types = visTypes.all().filter(type => { + const types = visTypes.all().filter((type) => { // Filter out all lab visualizations if lab mode is not enabled if (!this.props.showExperimental && type.stage === 'experimental') { return false; @@ -187,10 +189,10 @@ class TypeSelection extends React.Component; if (!query) { - entries = allTypes.map(type => ({ ...type, highlighted: false })); + entries = allTypes.map((type) => ({ ...type, highlighted: false })); } else { const q = query.toLowerCase(); - entries = allTypes.map(type => { + entries = allTypes.map((type) => { const matchesQuery = type.name.toLowerCase().includes(q) || type.title.toLowerCase().includes(q) || diff --git a/src/plugins/visualizations/server/saved_objects/visualization_migrations.ts b/src/plugins/visualizations/server/saved_objects/visualization_migrations.ts index f6455d0c1e43f..71b286cd91a54 100644 --- a/src/plugins/visualizations/server/saved_objects/visualization_migrations.ts +++ b/src/plugins/visualizations/server/saved_objects/visualization_migrations.ts @@ -21,7 +21,7 @@ import { SavedObjectMigrationFn } from 'kibana/server'; import { cloneDeep, get, omit, has, flow } from 'lodash'; import { DEFAULT_QUERY_LANGUAGE } from '../../../data/common'; -const migrateIndexPattern: SavedObjectMigrationFn = doc => { +const migrateIndexPattern: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (typeof searchSourceJSON !== 'string') { return doc; @@ -64,7 +64,7 @@ const migrateIndexPattern: SavedObjectMigrationFn = doc => { }; // [TSVB] Migrate percentile-rank aggregation (value -> values) -const migratePercentileRankAggregation: SavedObjectMigrationFn = doc => { +const migratePercentileRankAggregation: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); let visState; @@ -77,7 +77,7 @@ const migratePercentileRankAggregation: SavedObjectMigrationFn = doc = if (visState && visState.type === 'metrics') { const series: any[] = get(visState, 'params.series') || []; - series.forEach(part => { + series.forEach((part) => { (part.metrics || []).forEach((metric: any) => { if (metric.type === 'percentile_rank' && has(metric, 'value')) { metric.values = [metric.value]; @@ -100,7 +100,7 @@ const migratePercentileRankAggregation: SavedObjectMigrationFn = doc = }; // [TSVB] Remove stale opperator key -const migrateOperatorKeyTypo: SavedObjectMigrationFn = doc => { +const migrateOperatorKeyTypo: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); let visState; @@ -113,7 +113,7 @@ const migrateOperatorKeyTypo: SavedObjectMigrationFn = doc => { if (visState && visState.type === 'metrics') { const gaugeColorRules: any[] = get(visState, 'params.gauge_color_rules') || []; - gaugeColorRules.forEach(colorRule => { + gaugeColorRules.forEach((colorRule) => { if (colorRule.opperator) { delete colorRule.opperator; } @@ -132,7 +132,7 @@ const migrateOperatorKeyTypo: SavedObjectMigrationFn = doc => { }; // Migrate date histogram aggregation (remove customInterval) -const migrateDateHistogramAggregation: SavedObjectMigrationFn = doc => { +const migrateDateHistogramAggregation: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); let visState; @@ -174,7 +174,7 @@ const migrateDateHistogramAggregation: SavedObjectMigrationFn = doc => return doc; }; -const removeDateHistogramTimeZones: SavedObjectMigrationFn = doc => { +const removeDateHistogramTimeZones: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); if (visStateJSON) { let visState; @@ -272,7 +272,7 @@ const transformFilterStringToQueryObject: SavedObjectMigrationFn = (do // migrate the annotations query string: const annotations: any[] = get(visState, 'params.annotations') || []; - annotations.forEach(item => { + annotations.forEach((item) => { if (!item.query_string) { // we don't need to transform anything if there isn't a filter at all return; @@ -288,7 +288,7 @@ const transformFilterStringToQueryObject: SavedObjectMigrationFn = (do // migrate the series filters const series: any[] = get(visState, 'params.series') || []; - series.forEach(item => { + series.forEach((item) => { if (!item.filter) { // we don't need to transform anything if there isn't a filter at all return; @@ -304,7 +304,7 @@ const transformFilterStringToQueryObject: SavedObjectMigrationFn = (do // series item split filters filter if (item.split_filters) { const splitFilters: any[] = get(item, 'split_filters') || []; - splitFilters.forEach(filter => { + splitFilters.forEach((filter) => { if (!filter.filter) { // we don't need to transform anything if there isn't a filter at all return; @@ -325,7 +325,7 @@ const transformFilterStringToQueryObject: SavedObjectMigrationFn = (do return newDoc; }; -const transformSplitFiltersStringToQueryObject: SavedObjectMigrationFn = doc => { +const transformSplitFiltersStringToQueryObject: SavedObjectMigrationFn = (doc) => { // Migrate split_filters in TSVB objects that weren't migrated in 7.3 // If any filters exist and they are a string, we assume them to be lucene syntax and transform the filter into an object accordingly const newDoc = cloneDeep(doc); @@ -346,13 +346,13 @@ const transformSplitFiltersStringToQueryObject: SavedObjectMigrationFn } // migrate the series split_filter filters const series: any[] = get(visState, 'params.series') || []; - series.forEach(item => { + series.forEach((item) => { // series item split filters filter if (item.split_filters) { const splitFilters: any[] = get(item, 'split_filters') || []; if (splitFilters.length > 0) { // only transform split_filter filters if we have filters - splitFilters.forEach(filter => { + splitFilters.forEach((filter) => { if (typeof filter.filter === 'string') { const filterfilterObject = { query: filter.filter, @@ -370,7 +370,7 @@ const transformSplitFiltersStringToQueryObject: SavedObjectMigrationFn return newDoc; }; -const migrateFiltersAggQuery: SavedObjectMigrationFn = doc => { +const migrateFiltersAggQuery: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); if (visStateJSON) { @@ -413,7 +413,7 @@ const replaceMovAvgToMovFn: SavedObjectMigrationFn = (doc, logger) => if (visState && visState.type === 'metrics') { const series: any[] = get(visState, 'params.series', []); - series.forEach(part => { + series.forEach((part) => { if (part.metrics && Array.isArray(part.metrics)) { part.metrics.forEach((metric: any) => { if (metric.type === 'moving_average') { @@ -483,12 +483,12 @@ const migrateFiltersAggQueryStringQueries: SavedObjectMigrationFn = (d return doc; }; -const addDocReferences: SavedObjectMigrationFn = doc => ({ +const addDocReferences: SavedObjectMigrationFn = (doc) => ({ ...doc, references: doc.references || [], }); -const migrateSavedSearch: SavedObjectMigrationFn = doc => { +const migrateSavedSearch: SavedObjectMigrationFn = (doc) => { const savedSearchId = get(doc, 'attributes.savedSearchId'); if (savedSearchId && doc.references) { @@ -505,7 +505,7 @@ const migrateSavedSearch: SavedObjectMigrationFn = doc => { return doc; }; -const migrateControls: SavedObjectMigrationFn = doc => { +const migrateControls: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); if (visStateJSON) { @@ -536,7 +536,7 @@ const migrateControls: SavedObjectMigrationFn = doc => { return doc; }; -const migrateTableSplits: SavedObjectMigrationFn = doc => { +const migrateTableSplits: SavedObjectMigrationFn = (doc) => { try { const visState = JSON.parse(doc.attributes.visState); if (get(visState, 'type') !== 'table') { @@ -572,7 +572,7 @@ const migrateTableSplits: SavedObjectMigrationFn = doc => { } }; -const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { +const migrateMatchAllQuery: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (searchSourceJSON) { @@ -606,7 +606,7 @@ const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { }; // [TSVB] Default color palette is changing, keep the default for older viz -const migrateTsvbDefaultColorPalettes: SavedObjectMigrationFn = doc => { +const migrateTsvbDefaultColorPalettes: SavedObjectMigrationFn = (doc) => { const visStateJSON = get(doc, 'attributes.visState'); let visState; @@ -619,7 +619,7 @@ const migrateTsvbDefaultColorPalettes: SavedObjectMigrationFn = doc => if (visState && visState.type === 'metrics') { const series: any[] = get(visState, 'params.series') || []; - series.forEach(part => { + series.forEach((part) => { // The default value was not saved before if (!part.split_color_mode) { part.split_color_mode = 'gradient'; diff --git a/src/plugins/visualize/public/application/editor/editor.js b/src/plugins/visualize/public/application/editor/editor.js index db990676d45c3..8e5ab5251015d 100644 --- a/src/plugins/visualize/public/application/editor/editor.js +++ b/src/plugins/visualize/public/application/editor/editor.js @@ -49,7 +49,7 @@ import { getServices } from '../../kibana_services'; import { VISUALIZE_EMBEDDABLE_TYPE } from '../../../../visualizations/public'; export function initEditorDirective(app, deps) { - app.directive('visualizeApp', function() { + app.directive('visualizeApp', function () { return { restrict: 'E', controllerAs: 'visualizeApp', @@ -239,7 +239,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState onTitleDuplicate, returnToOrigin, }; - return doSave(saveOptions).then(response => { + return doSave(saveOptions).then((response) => { // If the save wasn't successful, put the original values back. if (!response.id || response.error) { savedVis.title = currentTitle; @@ -271,7 +271,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState defaultMessage: 'Share Visualization', }), testId: 'shareTopNavButton', - run: anchorElement => { + run: (anchorElement) => { const hasUnappliedChanges = $scope.dirty; const hasUnsavedChanges = $appStatus.dirty; share.toggleShareContextMenu({ @@ -334,7 +334,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState { set: ({ filters }) => stateContainer.transitions.set('filters', filters), get: () => ({ filters: stateContainer.getState().filters }), - state$: stateContainer.state$.pipe(map(state => ({ filters: state.filters }))), + state$: stateContainer.state$.pipe(map((state) => ({ filters: state.filters }))), }, { filters: esFilters.FilterStateStore.APP_STATE, @@ -374,7 +374,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $scope.filters = filterManager.getFilters(); - $scope.onFiltersUpdated = filters => { + $scope.onFiltersUpdated = (filters) => { // The filters will automatically be set when the filterManager emits an update event (see below) filterManager.setFilters(filters); }; @@ -383,12 +383,12 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $scope.$watch( () => visualizeCapabilities.saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability; } ); - const updateSavedQueryFromUrl = savedQueryId => { + const updateSavedQueryFromUrl = (savedQueryId) => { if (!savedQueryId) { delete $scope.savedQuery; @@ -399,7 +399,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState return; } - queryService.savedQueries.getSavedQuery(savedQueryId).then(savedQuery => { + queryService.savedQueries.getSavedQuery(savedQueryId).then((savedQuery) => { $scope.$evalAsync(() => { $scope.updateSavedQuery(savedQuery); }); @@ -410,14 +410,14 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState if (vis.data.indexPattern) { $scope.indexPattern = vis.data.indexPattern; } else { - indexPatterns.getDefault().then(defaultIndexPattern => { + indexPatterns.getDefault().then((defaultIndexPattern) => { $scope.indexPattern = defaultIndexPattern; }); } const initialState = stateContainer.getState(); - const handleLinkedSearch = linked => { + const handleLinkedSearch = (linked) => { if (linked && !savedVis.savedSearchId && savedSearch) { savedVis.savedSearchId = savedSearch.id; vis.data.savedSearchId = savedSearch.id; @@ -459,7 +459,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $scope.timeRange = timefilter.getTime(); - const unsubscribeStateUpdates = stateContainer.subscribe(state => { + const unsubscribeStateUpdates = stateContainer.subscribe((state) => { const newQuery = migrateLegacyQuery(state.query); if (!_.isEqual(state.query, newQuery)) { stateContainer.transitions.set('query', newQuery); @@ -511,7 +511,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $scope.refreshInterval = timefilter.getRefreshInterval(); }, }, - error => addFatalError(fatalErrors, error) + (error) => addFatalError(fatalErrors, error) ) ); subscriptions.add( @@ -521,12 +521,12 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState { next: updateTimeRange, }, - error => addFatalError(fatalErrors, error) + (error) => addFatalError(fatalErrors, error) ) ); subscriptions.add( - chrome.getIsVisible$().subscribe(isVisible => { + chrome.getIsVisible$().subscribe((isVisible) => { $scope.$evalAsync(() => { $scope.isVisible = isVisible; }); @@ -534,7 +534,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState ); // update the searchSource when query updates - $scope.fetch = function() { + $scope.fetch = function () { const { query, linked, filters } = stateContainer.getState(); $scope.query = query; handleLinkedSearch(linked); @@ -553,7 +553,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $scope.filters = filterManager.getFilters(); }, }, - error => addFatalError(fatalErrors, error) + (error) => addFatalError(fatalErrors, error) ) ); subscriptions.add( @@ -563,7 +563,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState { next: $scope.fetch, }, - error => addFatalError(fatalErrors, error) + (error) => addFatalError(fatalErrors, error) ) ); @@ -587,7 +587,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState }); } - $scope.updateQueryAndFetch = function({ query, dateRange }) { + $scope.updateQueryAndFetch = function ({ query, dateRange }) { const isUpdate = (query && !_.isEqual(query, stateContainer.getState().query)) || (dateRange && !_.isEqual(dateRange, $scope.timeRange)); @@ -601,7 +601,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState } }; - $scope.onRefreshChange = function({ isPaused, refreshInterval }) { + $scope.onRefreshChange = function ({ isPaused, refreshInterval }) { timefilter.setRefreshInterval({ pause: isPaused, value: refreshInterval ? refreshInterval : $scope.refreshInterval.value, @@ -614,7 +614,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState filterManager.setFilters(filterManager.getGlobalFilters()); }; - const updateStateFromSavedQuery = savedQuery => { + const updateStateFromSavedQuery = (savedQuery) => { stateContainer.transitions.updateFromSavedQuery(savedQuery); const savedQueryFilters = savedQuery.attributes.filters || []; @@ -632,7 +632,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState } }; - $scope.updateSavedQuery = savedQuery => { + $scope.updateSavedQuery = (savedQuery) => { $scope.savedQuery = savedQuery; updateStateFromSavedQuery(savedQuery); }; @@ -653,7 +653,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState $appStatus.dirty = false; return savedVis.save(saveOptions).then( - function(id) { + function (id) { $scope.$evalAsync(() => { if (id) { toastNotifications.addSuccess({ @@ -701,7 +701,7 @@ function VisualizeAppController($scope, $route, $injector, $timeout, kbnUrlState }); return { id }; }, - error => { + (error) => { // eslint-disable-next-line console.error(error); toastNotifications.addDanger({ diff --git a/src/plugins/visualize/public/application/editor/lib/make_stateful.ts b/src/plugins/visualize/public/application/editor/lib/make_stateful.ts index d071df314d99c..c7163f9b7705d 100644 --- a/src/plugins/visualize/public/application/editor/lib/make_stateful.ts +++ b/src/plugins/visualize/public/application/editor/lib/make_stateful.ts @@ -32,7 +32,7 @@ export function makeStateful( const persistedState = new PersistedState(); // update the appState when the stateful instance changes - const updateOnChange = function() { + const updateOnChange = function () { stateContainer.transitions.set(prop, persistedState.getChanges()); }; @@ -43,7 +43,7 @@ export function makeStateful( const unsubscribePersisted = () => handlerOnChange('off'); // update the stateful object when the app state changes - const persistOnChange = function(state: VisualizeAppState) { + const persistOnChange = function (state: VisualizeAppState) { if (state[prop]) { persistedState.set(state[prop]); } diff --git a/src/plugins/visualize/public/application/editor/lib/visualize_app_state.ts b/src/plugins/visualize/public/application/editor/lib/visualize_app_state.ts index fe2a19b7315c3..698fe0ca8a84f 100644 --- a/src/plugins/visualize/public/application/editor/lib/visualize_app_state.ts +++ b/src/plugins/visualize/public/application/editor/lib/visualize_app_state.ts @@ -59,15 +59,15 @@ export function useVisualizeAppState({ stateDefaults, kbnUrlStateStorage }: Argu const stateContainer = createStateContainer( initialState, { - set: state => (prop, value) => ({ ...state, [prop]: value }), - setVis: state => vis => ({ + set: (state) => (prop, value) => ({ ...state, [prop]: value }), + setVis: (state) => (vis) => ({ ...state, vis: { ...state.vis, ...vis, }, }), - removeSavedQuery: state => defaultQuery => { + removeSavedQuery: (state) => (defaultQuery) => { const { savedQuery, ...rest } = state; return { @@ -75,14 +75,14 @@ export function useVisualizeAppState({ stateDefaults, kbnUrlStateStorage }: Argu query: defaultQuery, }; }, - unlinkSavedSearch: state => ({ query, parentFilters = [] }) => ({ + unlinkSavedSearch: (state) => ({ query, parentFilters = [] }) => ({ ...state, query: query || state.query, filters: union(state.filters, parentFilters), linked: false, }), - updateVisState: state => newVisState => ({ ...state, vis: toObject(newVisState) }), - updateFromSavedQuery: state => savedQuery => ({ + updateVisState: (state) => (newVisState) => ({ ...state, vis: toObject(newVisState) }), + updateFromSavedQuery: (state) => (savedQuery) => ({ ...state, savedQuery: savedQuery.id, query: savedQuery.attributes.query, @@ -94,7 +94,7 @@ export function useVisualizeAppState({ stateDefaults, kbnUrlStateStorage }: Argu storageKey: STATE_STORAGE_KEY, stateContainer: { ...stateContainer, - set: state => { + set: (state) => { if (state) { // syncState utils requires to handle incoming "null" value stateContainer.set(state); diff --git a/src/plugins/visualize/public/application/editor/visualization.js b/src/plugins/visualize/public/application/editor/visualization.js index fbabd6fc87c98..26f61f3f0a2c2 100644 --- a/src/plugins/visualize/public/application/editor/visualization.js +++ b/src/plugins/visualize/public/application/editor/visualization.js @@ -18,7 +18,7 @@ */ export function initVisualizationDirective(app) { - app.directive('visualizationEmbedded', function($timeout) { + app.directive('visualizationEmbedded', function ($timeout) { return { restrict: 'E', scope: { @@ -29,7 +29,7 @@ export function initVisualizationDirective(app) { query: '=', appState: '=', }, - link: function($scope, element) { + link: function ($scope, element) { $scope.renderFunction = async () => { if (!$scope.rendered) { $scope.embeddableHandler.render(element[0]); @@ -43,7 +43,7 @@ export function initVisualizationDirective(app) { }); }; - $scope.$on('render', event => { + $scope.$on('render', (event) => { event.preventDefault(); $timeout(() => { $scope.renderFunction(); diff --git a/src/plugins/visualize/public/application/editor/visualization_editor.js b/src/plugins/visualize/public/application/editor/visualization_editor.js index 381148651a46b..4963d9bc5ed72 100644 --- a/src/plugins/visualize/public/application/editor/visualization_editor.js +++ b/src/plugins/visualize/public/application/editor/visualization_editor.js @@ -20,7 +20,7 @@ import { DefaultEditorController } from '../../../../vis_default_editor/public'; export function initVisEditorDirective(app, deps) { - app.directive('visualizationEditor', function($timeout) { + app.directive('visualizationEditor', function ($timeout) { return { restrict: 'E', scope: { @@ -33,7 +33,7 @@ export function initVisEditorDirective(app, deps) { embeddableHandler: '=', eventEmitter: '=', }, - link: function($scope, element) { + link: function ($scope, element) { const Editor = $scope.vis.type.editor || DefaultEditorController; const editor = new Editor( element[0], @@ -55,7 +55,7 @@ export function initVisEditorDirective(app, deps) { }); }; - $scope.$on('render', event => { + $scope.$on('render', (event) => { event.preventDefault(); $timeout(() => { $scope.renderFunction(); diff --git a/src/plugins/visualize/public/application/legacy_app.js b/src/plugins/visualize/public/application/legacy_app.js index 2cd859ac554f8..c9ccd79ce6a8a 100644 --- a/src/plugins/visualize/public/application/legacy_app.js +++ b/src/plugins/visualize/public/application/legacy_app.js @@ -38,30 +38,30 @@ import { getEditBreadcrumbs, } from './breadcrumbs'; -const getResolvedResults = deps => { +const getResolvedResults = (deps) => { const { core, data, visualizations, createVisEmbeddableFromObject } = deps; const results = {}; - return savedVis => { + return (savedVis) => { results.savedVis = savedVis; const serializedVis = visualizations.convertToSerializedVis(savedVis); return visualizations .createVis(serializedVis.type, serializedVis) - .then(vis => { + .then((vis) => { if (vis.type.setup) { return vis.type.setup(vis).catch(() => vis); } return vis; }) - .then(vis => { + .then((vis) => { results.vis = vis; return createVisEmbeddableFromObject(vis, { timeRange: data.query.timefilter.timefilter.getTime(), filters: data.query.filterManager.getFilters(), }); }) - .then(embeddableHandler => { + .then((embeddableHandler) => { results.embeddableHandler = embeddableHandler; if (results.vis.data.savedSearchId) { return createSavedSearchesLoader({ @@ -73,7 +73,7 @@ const getResolvedResults = deps => { }).get(results.vis.data.savedSearchId); } }) - .then(savedSearch => { + .then((savedSearch) => { if (savedSearch) { results.savedSearch = savedSearch; } @@ -86,14 +86,14 @@ export function initVisualizeApp(app, deps) { initVisualizeAppDirective(app, deps); app.factory('history', () => createHashHistory()); - app.factory('kbnUrlStateStorage', history => + app.factory('kbnUrlStateStorage', (history) => createKbnUrlStateStorage({ history, useHash: deps.core.uiSettings.get('state:storeInSessionStorage'), }) ); - app.config(function($routeProvider) { + app.config(function ($routeProvider) { const defaults = { reloadOnSearch: false, requireUICapability: 'visualize.show', @@ -123,7 +123,7 @@ export function initVisualizeApp(app, deps) { controllerAs: 'listingController', resolve: { createNewVis: () => false, - hasDefaultIndex: history => deps.data.indexPatterns.ensureDefaultIndexPattern(history), + hasDefaultIndex: (history) => deps.data.indexPatterns.ensureDefaultIndexPattern(history), }, }) .when(VisualizeConstants.WIZARD_STEP_1_PAGE_PATH, { @@ -134,7 +134,7 @@ export function initVisualizeApp(app, deps) { controllerAs: 'listingController', resolve: { createNewVis: () => true, - hasDefaultIndex: history => deps.data.indexPatterns.ensureDefaultIndexPattern(history), + hasDefaultIndex: (history) => deps.data.indexPatterns.ensureDefaultIndexPattern(history), }, }) .when(VisualizeConstants.CREATE_PATH, { @@ -142,7 +142,7 @@ export function initVisualizeApp(app, deps) { template: editorTemplate, k7Breadcrumbs: getCreateBreadcrumbs, resolve: { - resolved: function($route, history) { + resolved: function ($route, history) { const { data, savedVisualizations, visualizations, toastNotifications } = deps; const visTypes = visualizations.all(); const visType = find(visTypes, { name: $route.current.params.type }); @@ -162,8 +162,8 @@ export function initVisualizeApp(app, deps) { // This delay is needed to prevent some navigation issues in Firefox/Safari. // see https://github.com/elastic/kibana/issues/65161 - const delay = res => { - return new Promise(resolve => { + const delay = (res) => { + return new Promise((resolve) => { setTimeout(() => resolve(res), 0); }); }; @@ -171,7 +171,7 @@ export function initVisualizeApp(app, deps) { return data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => savedVisualizations.get($route.current.params)) - .then(savedVis => { + .then((savedVis) => { savedVis.searchSourceFields = { index: $route.current.params.indexPattern }; return savedVis; }) @@ -192,13 +192,13 @@ export function initVisualizeApp(app, deps) { template: editorTemplate, k7Breadcrumbs: getEditBreadcrumbs, resolve: { - resolved: function($route, history) { + resolved: function ($route, history) { const { chrome, data, savedVisualizations, toastNotifications } = deps; return data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => savedVisualizations.get($route.current.params.id)) - .then(savedVis => { + .then((savedVis) => { chrome.recentlyAccessed.add(savedVis.getFullPath(), savedVis.title, savedVis.id); return savedVis; }) @@ -240,7 +240,7 @@ export function initVisualizeApp(app, deps) { }) .otherwise({ template: '', - controller: function() { + controller: function () { deps.kibanaLegacy.navigateToDefaultApp(); }, }); diff --git a/src/plugins/visualize/public/application/listing/visualize_listing.js b/src/plugins/visualize/public/application/listing/visualize_listing.js index 7c95fd6a7f4b0..228cfa1e9e492 100644 --- a/src/plugins/visualize/public/application/listing/visualize_listing.js +++ b/src/plugins/visualize/public/application/listing/visualize_listing.js @@ -29,7 +29,7 @@ import { EuiLink } from '@elastic/eui'; import React from 'react'; export function initListingDirective(app, I18nContext) { - app.directive('visualizeListingTable', reactDirective => + app.directive('visualizeListingTable', (reactDirective) => reactDirective(withI18nContext(I18nContext)) ); } @@ -119,26 +119,28 @@ export function VisualizeListingController($scope, createNewVis, kbnUrlStateStor }); } - this.fetchItems = filter => { + this.fetchItems = (filter) => { const isLabsEnabled = uiSettings.get('visualize:enableLabs'); return savedVisualizations .findListItems(filter, savedObjectsPublic.settings.getListingLimit()) - .then(result => { + .then((result) => { this.totalItems = result.total; return { total: result.total, - hits: result.hits.filter(result => isLabsEnabled || result.type.stage !== 'experimental'), + hits: result.hits.filter( + (result) => isLabsEnabled || result.type.stage !== 'experimental' + ), }; }); }; this.deleteSelectedItems = function deleteSelectedItems(selectedItems) { return Promise.all( - selectedItems.map(item => { + selectedItems.map((item) => { return savedObjectsClient.delete(item.savedObjectType, item.id); }) - ).catch(error => { + ).catch((error) => { toastNotifications.addError(error, { title: i18n.translate('visualize.visualizeListingDeleteErrorTitle', { defaultMessage: 'Error deleting visualization', diff --git a/src/plugins/visualize/public/application/listing/visualize_listing_table.js b/src/plugins/visualize/public/application/listing/visualize_listing_table.js index a1cc11c93cafc..fcd62d7ddee73 100644 --- a/src/plugins/visualize/public/application/listing/visualize_listing_table.js +++ b/src/plugins/visualize/public/application/listing/visualize_listing_table.js @@ -46,7 +46,7 @@ class VisualizeListingTable extends Component { tableColumns={this.getTableColumns()} listingLimit={this.props.listingLimit} initialPageSize={this.props.initialPageSize} - selectable={item => item.canDelete} + selectable={(item) => item.canDelete} initialFilter={''} noItemsFragment={this.getNoItemsMessage()} entityName={i18n.translate('visualize.listing.table.entityName', { @@ -224,7 +224,7 @@ VisualizeListingTable.propTypes = { listingLimit: PropTypes.number.isRequired, }; -const withI18nContext = I18nContext => props => ( +const withI18nContext = (I18nContext) => (props) => ( diff --git a/src/setup_node_env/exit_on_warning.js b/src/setup_node_env/exit_on_warning.js index 6321cd7ba8db0..c0a0f0ecc0b83 100644 --- a/src/setup_node_env/exit_on_warning.js +++ b/src/setup_node_env/exit_on_warning.js @@ -20,7 +20,7 @@ if (process.noProcessWarnings !== true) { var ignore = ['MaxListenersExceededWarning']; - process.on('warning', function(warn) { + process.on('warning', function (warn) { if (ignore.includes(warn.name)) return; if (process.traceProcessWarnings === true) { @@ -39,7 +39,7 @@ if (process.noProcessWarnings !== true) { // While the above warning listener would also be called on // unhandledRejection warnings, we can give a better error message if we // handle them separately: - process.on('unhandledRejection', function(reason) { + process.on('unhandledRejection', function (reason) { console.error('Unhandled Promise rejection detected:'); console.error(); console.error(reason); diff --git a/src/setup_node_env/harden.js b/src/setup_node_env/harden.js index 466cbfa0d92cf..dead3db1d60b4 100644 --- a/src/setup_node_env/harden.js +++ b/src/setup_node_env/harden.js @@ -19,6 +19,6 @@ var hook = require('require-in-the-middle'); -hook(['child_process'], function(exports, name) { +hook(['child_process'], function (exports, name) { return require(`./patches/${name}`)(exports); // eslint-disable-line import/no-dynamic-require }); diff --git a/src/setup_node_env/node_version_validator.test.js b/src/setup_node_env/node_version_validator.test.js index 13b95b219944e..3f6597019c2f0 100644 --- a/src/setup_node_env/node_version_validator.test.js +++ b/src/setup_node_env/node_version_validator.test.js @@ -23,8 +23,8 @@ var pkg = require('../../package.json'); var REQUIRED_NODE_JS_VERSION = 'v' + pkg.engines.node; var INVALID_NODE_JS_VERSION = 'v0.10.0'; -describe('NodeVersionValidator', function() { - it('should run the script WITH error', function(done) { +describe('NodeVersionValidator', function () { + it('should run the script WITH error', function (done) { var processVersionOverwrite = "Object.defineProperty(process, 'version', { value: '" + INVALID_NODE_JS_VERSION + @@ -32,7 +32,7 @@ describe('NodeVersionValidator', function() { var command = 'node -e "' + processVersionOverwrite + "require('./node_version_validator.js')\""; - exec(command, { cwd: __dirname }, function(error, stdout, stderr) { + exec(command, { cwd: __dirname }, function (error, stdout, stderr) { expect(error.code).toBe(1); expect(stderr).toBeDefined(); expect(stderr).not.toHaveLength(0); @@ -40,7 +40,7 @@ describe('NodeVersionValidator', function() { }); }); - it('should run the script WITHOUT error', function(done) { + it('should run the script WITHOUT error', function (done) { var processVersionOverwrite = "Object.defineProperty(process, 'version', { value: '" + REQUIRED_NODE_JS_VERSION + @@ -48,7 +48,7 @@ describe('NodeVersionValidator', function() { var command = 'node -e "' + processVersionOverwrite + "require('./node_version_validator.js')\""; - exec(command, { cwd: __dirname }, function(error, stdout, stderr) { + exec(command, { cwd: __dirname }, function (error, stdout, stderr) { expect(error).toBeNull(); expect(stderr).toBeDefined(); expect(stderr).toHaveLength(0); diff --git a/src/setup_node_env/patches/child_process.js b/src/setup_node_env/patches/child_process.js index b89190d8085e6..fb857b2092ee0 100644 --- a/src/setup_node_env/patches/child_process.js +++ b/src/setup_node_env/patches/child_process.js @@ -21,7 +21,7 @@ // `options.env` object passed to the child process function doesn't inherit // from `Object.prototype`. This protects against similar RCE vulnerabilities // as described in CVE-2019-7609 -module.exports = function(cp) { +module.exports = function (cp) { // The `exec` function is currently just a wrapper around `execFile`. So for // now there's no need to patch it. If this changes in the future, our tests // will fail and we can uncomment the line below. diff --git a/src/setup_node_env/root/force.js b/src/setup_node_env/root/force.js index 832f3e77a9f8a..5c5370aec6b15 100644 --- a/src/setup_node_env/root/force.js +++ b/src/setup_node_env/root/force.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(argv) { +module.exports = function (argv) { var rootIndex = argv.indexOf('--allow-root'); var force = rootIndex >= 0; if (force) argv.splice(rootIndex, 1); diff --git a/src/setup_node_env/root/force.test.js b/src/setup_node_env/root/force.test.js index f717d7050f665..2811caa7ef880 100644 --- a/src/setup_node_env/root/force.test.js +++ b/src/setup_node_env/root/force.test.js @@ -19,16 +19,16 @@ var forceRoot = require('./force'); -describe('forceRoot', function() { - it('with flag', function() { +describe('forceRoot', function () { + it('with flag', function () { expect(forceRoot(['--allow-root'])).toBeTruthy(); }); - it('without flag', function() { + it('without flag', function () { expect(forceRoot(['--foo'])).toBeFalsy(); }); - test('remove argument', function() { + test('remove argument', function () { var args = ['--allow-root', 'foo']; forceRoot(args); expect(args.includes('--allow-root')).toBeFalsy(); diff --git a/src/setup_node_env/root/is_root.js b/src/setup_node_env/root/is_root.js index 9d7c3b8675411..e2eaaf6af5154 100644 --- a/src/setup_node_env/root/is_root.js +++ b/src/setup_node_env/root/is_root.js @@ -17,6 +17,6 @@ * under the License. */ -module.exports = function(uid) { +module.exports = function (uid) { return uid === 0; }; diff --git a/src/setup_node_env/root/is_root.test.js b/src/setup_node_env/root/is_root.test.js index 9399893bdc016..388747caff166 100644 --- a/src/setup_node_env/root/is_root.test.js +++ b/src/setup_node_env/root/is_root.test.js @@ -19,12 +19,12 @@ var isRoot = require('./is_root'); -describe('isRoot', function() { - test('0 is root', function() { +describe('isRoot', function () { + test('0 is root', function () { expect(isRoot(0)).toBeTruthy(); }); - test('not 0 is not root', function() { + test('not 0 is not root', function () { expect(isRoot(5)).toBeFalsy(); }); }); diff --git a/src/test_utils/__tests__/get_url.js b/src/test_utils/__tests__/get_url.js index 48b7aa94418f8..c9dd4d5a6d616 100644 --- a/src/test_utils/__tests__/get_url.js +++ b/src/test_utils/__tests__/get_url.js @@ -20,8 +20,8 @@ import expect from '@kbn/expect'; import getUrl from '../get_url'; -describe('getUrl', function() { - it('should convert to a url', function() { +describe('getUrl', function () { + it('should convert to a url', function () { const url = getUrl( { protocol: 'http', @@ -35,7 +35,7 @@ describe('getUrl', function() { expect(url).to.be('http://localhost/foo'); }); - it('should convert to a url with port', function() { + it('should convert to a url with port', function () { const url = getUrl( { protocol: 'http', @@ -50,7 +50,7 @@ describe('getUrl', function() { expect(url).to.be('http://localhost:9220/foo'); }); - it('should convert to a secure hashed url', function() { + it('should convert to a secure hashed url', function () { expect( getUrl( { diff --git a/src/test_utils/get_url.js b/src/test_utils/get_url.js index c9170bad5c90b..fbe16e798fff9 100644 --- a/src/test_utils/get_url.js +++ b/src/test_utils/get_url.js @@ -44,7 +44,7 @@ export default function getUrl(config, app) { } getUrl.noAuth = function getUrlNoAuth(config, app) { - config = _.pick(config, function(val, param) { + config = _.pick(config, function (val, param) { return param !== 'auth'; }); return getUrl(config, app); diff --git a/src/test_utils/public/enzyme_helpers.tsx b/src/test_utils/public/enzyme_helpers.tsx index 43ec49c5c1404..a7bed2ad84956 100644 --- a/src/test_utils/public/enzyme_helpers.tsx +++ b/src/test_utils/public/enzyme_helpers.tsx @@ -127,7 +127,7 @@ export function renderWithIntl( return render(nodeWithIntlProp(node), options); } -export const nextTick = () => new Promise(res => process.nextTick(res)); +export const nextTick = () => new Promise((res) => process.nextTick(res)); export function shallowWithI18nProvider(child: ReactElement) { const wrapped = shallow({child}); diff --git a/src/test_utils/public/image_comparator.js b/src/test_utils/public/image_comparator.js index 00f74f78fdfac..f31a3e9cd646d 100644 --- a/src/test_utils/public/image_comparator.js +++ b/src/test_utils/public/image_comparator.js @@ -78,7 +78,7 @@ export class ImageComparator { document.body.removeChild(sourceCanvas); resolve(mismatch); }; - sourceImage.onerror = e => { + sourceImage.onerror = (e) => { reject(e.message); }; sourceImage.src = 'data:image/svg+xml;base64,' + btoa(sourceData); @@ -151,7 +151,7 @@ export class ImageComparator { resolve(mismatchedPixels); }; - expectedImage.onerror = e => { + expectedImage.onerror = (e) => { reject(e.message); }; diff --git a/src/test_utils/public/mocks/intl.js b/src/test_utils/public/mocks/intl.js index 72c35bb85b1b6..e75b7d71f5fa6 100644 --- a/src/test_utils/public/mocks/intl.js +++ b/src/test_utils/public/mocks/intl.js @@ -20,11 +20,11 @@ export const intl = { formatMessage: jest.fn().mockImplementation(({ defaultMessage }) => defaultMessage), - formatDate: jest.fn().mockImplementation(value => value), - formatTime: jest.fn().mockImplementation(value => value), - formatRelative: jest.fn().mockImplementation(value => value), - formatNumber: jest.fn().mockImplementation(value => value), - formatPlural: jest.fn().mockImplementation(value => value), + formatDate: jest.fn().mockImplementation((value) => value), + formatTime: jest.fn().mockImplementation((value) => value), + formatRelative: jest.fn().mockImplementation((value) => value), + formatNumber: jest.fn().mockImplementation((value) => value), + formatPlural: jest.fn().mockImplementation((value) => value), formatHTMLMessage: jest.fn().mockImplementation(({ defaultMessage }) => defaultMessage), now: jest.fn().mockImplementation(() => new Date(1531834573179)), textComponent: 'span', diff --git a/src/test_utils/public/no_digest_promises.js b/src/test_utils/public/no_digest_promises.js index 43f4c52437871..396d6fb4892f3 100644 --- a/src/test_utils/public/no_digest_promises.js +++ b/src/test_utils/public/no_digest_promises.js @@ -37,8 +37,8 @@ Bluebird.longStackTraces(); let active = false; -uiModules.get('kibana').config(function($provide) { - $provide.decorator('Promise', function($delegate) { +uiModules.get('kibana').config(function ($provide) { + $provide.decorator('Promise', function ($delegate) { return active ? Bluebird : $delegate; }); }); @@ -53,7 +53,7 @@ function deactivate() { export default { activate: activate, deactivate: deactivate, - activateForSuite: function() { + activateForSuite: function () { before(activate); after(deactivate); }, diff --git a/src/test_utils/public/simulate_keys.js b/src/test_utils/public/simulate_keys.js index a876d67325c05..56596508a2181 100644 --- a/src/test_utils/public/simulate_keys.js +++ b/src/test_utils/public/simulate_keys.js @@ -52,7 +52,7 @@ const reverseKeyMap = _.mapValues(_.invert(keyMap), _.ary(_.parseInt, 1)); * @param {[type]} sequence - an array of events * @async */ -export default function($el, sequence) { +export default function ($el, sequence) { const modifierState = { ctrlKey: false, shiftKey: false, @@ -70,7 +70,7 @@ export default function($el, sequence) { } function doList(list) { - return Bluebird.try(function() { + return Bluebird.try(function () { if (!list || !list.length) return; let event = list[0]; @@ -102,7 +102,7 @@ export default function($el, sequence) { default: throw new TypeError('invalid event type "' + event.type + '"'); } - }).then(function() { + }).then(function () { if (_.size(list) > 1) return doList(list.slice(1)); }); } diff --git a/src/test_utils/public/stub_get_active_injector.js b/src/test_utils/public/stub_get_active_injector.js index 2f374ae3d366a..fb72cc5dabb7e 100644 --- a/src/test_utils/public/stub_get_active_injector.js +++ b/src/test_utils/public/stub_get_active_injector.js @@ -39,7 +39,7 @@ import sinon from 'sinon'; */ export function setupInjectorStub() { beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { sinon.stub(chrome, 'dangerouslyGetActiveInjector').returns(Promise.resolve($injector)); }) ); diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js index 29fb4c20f692e..5a81139157cef 100644 --- a/src/test_utils/public/stub_index_pattern.js +++ b/src/test_utils/public/stub_index_pattern.js @@ -33,8 +33,8 @@ import { setFieldFormats } from '../../plugins/data/public/services'; setFieldFormats({ getDefaultInstance: () => ({ - getConverterFor: () => value => value, - convert: value => JSON.stringify(value), + getConverterFor: () => (value) => value, + convert: (value) => JSON.stringify(value), }), }); @@ -45,7 +45,7 @@ export default function StubIndexPattern(pattern, getConfig, timeField, fields, const createFieldList = getIndexPatternFieldListCreator({ fieldFormats: { getDefaultInstance: () => ({ - convert: val => String(val), + convert: (val) => String(val), }), }, toastNotifications: { @@ -75,11 +75,11 @@ export default function StubIndexPattern(pattern, getConfig, timeField, fields, this.fieldsFetcher = { apiClient: { baseUrl: '' } }; this.formatField = this.formatHit.formatField; - this._reindexFields = function() { + this._reindexFields = function () { this.fields = createFieldList(this, this.fields || fields, false); }; - this.stubSetFieldFormat = function(fieldName, id, params) { + this.stubSetFieldFormat = function (fieldName, id, params) { const FieldFormat = registeredFieldFormats.getType(id); this.fieldFormatMap[fieldName] = new FieldFormat(params); this._reindexFields(); diff --git a/tasks/check_plugins.js b/tasks/check_plugins.js index 1ebfed7be737c..20fb8a895af6c 100644 --- a/tasks/check_plugins.js +++ b/tasks/check_plugins.js @@ -33,7 +33,7 @@ export default function checkPlugins(grunt) { return done(); } - const plugins = files.filter(file => { + const plugins = files.filter((file) => { return fs.statSync(path.join(pluginsDir, file)).isDirectory(); }); @@ -41,7 +41,7 @@ export default function checkPlugins(grunt) { grunt.log.error( '===================================================================================================' ); - plugins.forEach(plugin => { + plugins.forEach((plugin) => { grunt.log.error( `The ${plugin} plugin may disrupt the test process. Consider removing it and re-running your tests.` ); diff --git a/tasks/config/availabletasks.js b/tasks/config/availabletasks.js index 9823cedbb289e..7337d5c2a8e27 100644 --- a/tasks/config/availabletasks.js +++ b/tasks/config/availabletasks.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(grunt) { +module.exports = function (grunt) { const config = { availabletasks: { tasks: { diff --git a/tasks/config/karma.js b/tasks/config/karma.js index f87edbf04f220..fa4bdc8ed2266 100644 --- a/tasks/config/karma.js +++ b/tasks/config/karma.js @@ -27,7 +27,7 @@ const TOTAL_CI_SHARDS = 4; const ROOT = dirname(require.resolve('../../package.json')); const buildHash = String(Number.MAX_SAFE_INTEGER); -module.exports = function(grunt) { +module.exports = function (grunt) { function pickBrowser() { if (grunt.option('browser')) { return grunt.option('browser'); @@ -58,14 +58,14 @@ module.exports = function(grunt) { 'http://localhost:5610/test_bundle/karma/globals.js', ...UiSharedDeps.jsDepFilenames.map( - chunkFilename => + (chunkFilename) => `http://localhost:5610/${buildHash}/bundles/kbn-ui-shared-deps/${chunkFilename}` ), `http://localhost:5610/${buildHash}/bundles/kbn-ui-shared-deps/${UiSharedDeps.jsFilename}`, `http://localhost:5610/${buildHash}/built_assets/dlls/vendors_runtime.bundle.dll.js`, ...DllCompiler.getRawDllConfig().chunks.map( - chunk => + (chunk) => `http://localhost:5610/${buildHash}/built_assets/dlls/vendors${chunk}.bundle.dll.js` ), @@ -78,7 +78,7 @@ module.exports = function(grunt) { // included in the karma harness a long some time, if ever // `http://localhost:5610/bundles/kbn-ui-shared-deps/${UiSharedDeps.lightCssDistFilename}`, ...DllCompiler.getRawDllConfig().chunks.map( - chunk => + (chunk) => `http://localhost:5610/${buildHash}/built_assets/dlls/vendors${chunk}.style.dll.css` ), `http://localhost:5610/${buildHash}/bundles/tests.style.css`, @@ -205,7 +205,7 @@ module.exports = function(grunt) { * * [1]: src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js */ - times(TOTAL_CI_SHARDS, i => { + times(TOTAL_CI_SHARDS, (i) => { const n = i + 1; config[`ciShard-${n}`] = { singleRun: true, diff --git a/tasks/config/run.js b/tasks/config/run.js index fc2ece3c72097..22deead1d380e 100644 --- a/tasks/config/run.js +++ b/tasks/config/run.js @@ -25,7 +25,7 @@ const KIBANA_INSTALL_DIR = process.env.KIBANA_INSTALL_DIR || `./build/oss/kibana-${version}-SNAPSHOT-${process.platform}-x86_64`; -module.exports = function(grunt) { +module.exports = function (grunt) { function createKbnServerTask({ runBuild, flags = [] }) { return { options: { @@ -43,7 +43,7 @@ module.exports = function(grunt) { ...flags, // allow the user to override/inject flags by defining cli args starting with `--kbnServer.` - ...grunt.option.flags().reduce(function(flags, flag) { + ...grunt.option.flags().reduce(function (flags, flag) { if (flag.startsWith('--kbnServer.')) { flags.push(`--${flag.slice(12)}`); } diff --git a/tasks/docker_docs.js b/tasks/docker_docs.js index 6104db89b0fae..3a2041abc9301 100644 --- a/tasks/docker_docs.js +++ b/tasks/docker_docs.js @@ -21,8 +21,8 @@ import del from 'del'; import { join } from 'path'; import { execFileSync as exec } from 'child_process'; -export default function(grunt) { - grunt.registerTask('docker:docs', 'Build docs from docker', function() { +export default function (grunt) { + grunt.registerTask('docker:docs', 'Build docs from docker', function () { const rootPath = grunt.config.get('root'); const composePath = join(rootPath, 'tasks/docker_docs/docker-compose.yml'); const htmlDocsDir = join(rootPath, 'html_docs'); diff --git a/tasks/function_test_groups.js b/tasks/function_test_groups.js index 7b7293dc9a037..799b9e9eb8194 100644 --- a/tasks/function_test_groups.js +++ b/tasks/function_test_groups.js @@ -26,10 +26,10 @@ import { safeLoad } from 'js-yaml'; const JOBS_YAML = readFileSync(resolve(__dirname, '../.ci/jobs.yml'), 'utf8'); const TEST_TAGS = safeLoad(JOBS_YAML) - .JOB.filter(id => id.startsWith('kibana-ciGroup')) - .map(id => id.replace(/^kibana-/, '')); + .JOB.filter((id) => id.startsWith('kibana-ciGroup')) + .map((id) => id.replace(/^kibana-/, '')); -const getDefaultArgs = tag => { +const getDefaultArgs = (tag) => { return [ 'scripts/functional_tests', '--include-tag', @@ -66,13 +66,13 @@ export function getFunctionalTestGroupRunConfigs({ kibanaInstallDir } = {}) { grunt.registerTask( 'functionalTests:ensureAllTestsInCiGroup', 'Check that all of the functional tests are in a CI group', - async function() { + async function () { const done = this.async(); try { const result = await execa(process.execPath, [ 'scripts/functional_test_runner', - ...TEST_TAGS.map(tag => `--include-tag=${tag}`), + ...TEST_TAGS.map((tag) => `--include-tag=${tag}`), '--config', 'test/functional/config.js', '--test-stats', diff --git a/tasks/jenkins.js b/tasks/jenkins.js index 33cbb0c6b2e17..4d92ff406a325 100644 --- a/tasks/jenkins.js +++ b/tasks/jenkins.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(grunt) { +module.exports = function (grunt) { grunt.registerTask('jenkins:docs', ['docker:docs']); grunt.registerTask('jenkins:unit', [ diff --git a/tasks/licenses_csv_report.js b/tasks/licenses_csv_report.js index 1550dd2011d2e..746195038379e 100644 --- a/tasks/licenses_csv_report.js +++ b/tasks/licenses_csv_report.js @@ -36,7 +36,7 @@ function escapeValue(value) { function formatCsvValues(fields, values) { return fields - .map(field => { + .map((field) => { const value = values[field]; if (isNull(value) || isUndefined(value)) { @@ -50,7 +50,7 @@ function formatCsvValues(fields, values) { } export default function licensesCSVReport(grunt) { - grunt.registerTask('licenses:csv_report', 'Report of 3rd party dependencies', async function() { + grunt.registerTask('licenses:csv_report', 'Report of 3rd party dependencies', async function () { const fields = ['name', 'version', 'url', 'license']; const done = this.async(); @@ -66,7 +66,7 @@ export default function licensesCSVReport(grunt) { }); const csv = packages - .map(pkg => { + .map((pkg) => { const data = { name: pkg.name, version: pkg.version, diff --git a/tasks/test.js b/tasks/test.js index 5618ebba4e6eb..96ec4d91db325 100644 --- a/tasks/test.js +++ b/tasks/test.js @@ -21,11 +21,11 @@ import _, { keys } from 'lodash'; import { run } from '../utilities/visual_regression'; -module.exports = function(grunt) { +module.exports = function (grunt) { grunt.registerTask( 'test:visualRegression:buildGallery', 'Compare screenshots and generate diff images.', - function() { + function () { const done = this.async(); run(done); } @@ -40,8 +40,8 @@ module.exports = function(grunt) { grunt.registerTask('test:karma-ci', () => { const ciShardTasks = keys(grunt.config.get('karma')) - .filter(key => key.startsWith('ciShard-')) - .map(key => `karma:${key}`); + .filter((key) => key.startsWith('ciShard-')) + .map((key) => `karma:${key}`); grunt.log.ok(`Running UI tests in ${ciShardTasks.length} shards`); grunt.task.run(['run:browserSCSS']); @@ -64,7 +64,7 @@ module.exports = function(grunt) { grunt.registerTask('test:karmaDebug', ['checkPlugins', 'run:karmaTestDebugServer', 'karma:dev']); grunt.registerTask('test:mochaCoverage', ['run:mochaCoverage']); - grunt.registerTask('test', subTask => { + grunt.registerTask('test', (subTask) => { if (subTask) grunt.fail.fatal(`invalid task "test:${subTask}"`); grunt.task.run( @@ -84,7 +84,7 @@ module.exports = function(grunt) { grunt.registerTask('quick-test', ['test:quick']); // historical alias - grunt.registerTask('test:projects', function() { + grunt.registerTask('test:projects', function () { const done = this.async(); runProjectsTests().then(done, done); }); diff --git a/tasks/test_jest.js b/tasks/test_jest.js index bcb05a83675e5..7fce3d061d69a 100644 --- a/tasks/test_jest.js +++ b/tasks/test_jest.js @@ -19,13 +19,13 @@ const { resolve } = require('path'); -module.exports = function(grunt) { - grunt.registerTask('test:jest', function() { +module.exports = function (grunt) { + grunt.registerTask('test:jest', function () { const done = this.async(); runJest(resolve(__dirname, '../scripts/jest.js')).then(done, done); }); - grunt.registerTask('test:jest_integration', function() { + grunt.registerTask('test:jest_integration', function () { const done = this.async(); runJest(resolve(__dirname, '../scripts/jest_integration.js')).then(done, done); }); diff --git a/tasks/verify_dependency_versions.js b/tasks/verify_dependency_versions.js index 7a522a48c4ee7..14ecbb9ba8603 100644 --- a/tasks/verify_dependency_versions.js +++ b/tasks/verify_dependency_versions.js @@ -23,7 +23,7 @@ import xpack from '../x-pack/package.json'; function getMismatches(depType) { return Object.keys(kibana[depType]) - .map(key => { + .map((key) => { const xpackValue = xpack[depType][key]; const kibanaValue = kibana[depType][key]; if (xpackValue && kibanaValue && xpackValue !== kibanaValue && !key.includes('@kbn/')) { @@ -34,7 +34,7 @@ function getMismatches(depType) { }; } }) - .filter(key => !!key); + .filter((key) => !!key); } export default function verifyDependencyVersions(grunt) { diff --git a/test/accessibility/apps/console.ts b/test/accessibility/apps/console.ts index 5d9bcfb73117f..203d359a7c711 100644 --- a/test/accessibility/apps/console.ts +++ b/test/accessibility/apps/console.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'console']); const a11y = getService('a11y'); diff --git a/test/accessibility/apps/dashboard.ts b/test/accessibility/apps/dashboard.ts index 46f407af126b6..c0d73b92d5e5a 100644 --- a/test/accessibility/apps/dashboard.ts +++ b/test/accessibility/apps/dashboard.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'dashboard', 'header', 'home', 'settings']); const a11y = getService('a11y'); const dashboardAddPanel = getService('dashboardAddPanel'); diff --git a/test/accessibility/apps/dashboard_panel.ts b/test/accessibility/apps/dashboard_panel.ts index 0016aa0ee0cc7..03fa76387da1f 100644 --- a/test/accessibility/apps/dashboard_panel.ts +++ b/test/accessibility/apps/dashboard_panel.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'dashboard', 'header', 'home', 'settings']); const a11y = getService('a11y'); const dashboardPanelActions = getService('dashboardPanelActions'); diff --git a/test/accessibility/apps/discover.ts b/test/accessibility/apps/discover.ts index a3ddcf8af666d..4563ffd19dd87 100644 --- a/test/accessibility/apps/discover.ts +++ b/test/accessibility/apps/discover.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'discover', 'header', 'share', 'timePicker']); const retry = getService('retry'); const a11y = getService('a11y'); diff --git a/test/accessibility/apps/home.ts b/test/accessibility/apps/home.ts index e481a32e65a85..f98972ca409d9 100644 --- a/test/accessibility/apps/home.ts +++ b/test/accessibility/apps/home.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'home']); const a11y = getService('a11y'); diff --git a/test/accessibility/apps/management.ts b/test/accessibility/apps/management.ts index cc60e672fe880..b37500f5b15dd 100644 --- a/test/accessibility/apps/management.ts +++ b/test/accessibility/apps/management.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'settings', 'header']); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/accessibility/apps/visualize.ts b/test/accessibility/apps/visualize.ts index 457bf815a3c62..b04ee206ff6bf 100644 --- a/test/accessibility/apps/visualize.ts +++ b/test/accessibility/apps/visualize.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const PageObjects = getPageObjects(['common', 'visualize', 'header']); const a11y = getService('a11y'); const esArchiver = getService('esArchiver'); diff --git a/test/accessibility/config.ts b/test/accessibility/config.ts index bf71fd81aa199..dd366c17a4ba7 100644 --- a/test/accessibility/config.ts +++ b/test/accessibility/config.ts @@ -21,7 +21,7 @@ import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; import { services } from './services'; import { pageObjects } from './page_objects'; -export default async function({ readConfigFile }: FtrConfigProviderContext) { +export default async function ({ readConfigFile }: FtrConfigProviderContext) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); return { diff --git a/test/accessibility/services/a11y/a11y.ts b/test/accessibility/services/a11y/a11y.ts index 72440b648e538..24f16518bc429 100644 --- a/test/accessibility/services/a11y/a11y.ts +++ b/test/accessibility/services/a11y/a11y.ts @@ -69,7 +69,7 @@ export function A11yProvider({ getService }: FtrProviderContext) { include: global ? undefined : [testSubjectToCss('appA11yRoot')], exclude: ([] as string[]) .concat(excludeTestSubj || []) - .map(ts => [testSubjectToCss(ts)]) + .map((ts) => [testSubjectToCss(ts)]) .concat([['.ace_scrollbar']]), }; } diff --git a/test/accessibility/services/a11y/analyze_with_axe.js b/test/accessibility/services/a11y/analyze_with_axe.js index 1801b341f6dad..3cff67fa306dc 100644 --- a/test/accessibility/services/a11y/analyze_with_axe.js +++ b/test/accessibility/services/a11y/analyze_with_axe.js @@ -30,8 +30,8 @@ export function analyzeWithAxe(context, options, callback) { return false; }) .then( - result => callback({ result }), - error => callback({ error }) + (result) => callback({ result }), + (error) => callback({ error }) ); } diff --git a/test/accessibility/services/a11y/axe_report.ts b/test/accessibility/services/a11y/axe_report.ts index ba1e8c739079d..0dbdefc3049c7 100644 --- a/test/accessibility/services/a11y/axe_report.ts +++ b/test/accessibility/services/a11y/axe_report.ts @@ -66,4 +66,4 @@ ${title} [${result.id}]: ${result.description} Help: ${result.helpUrl} Elements: - - ${result.nodes.map(node => node.target).join('\n - ')}`; + - ${result.nodes.map((node) => node.target).join('\n - ')}`; diff --git a/test/api_integration/apis/core/index.js b/test/api_integration/apis/core/index.js index be1ecf9b9c497..c522acaea25a3 100644 --- a/test/api_integration/apis/core/index.js +++ b/test/api_integration/apis/core/index.js @@ -18,7 +18,7 @@ */ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('core', () => { @@ -40,7 +40,7 @@ export default function({ getService }) { await supertest .get('/app/kibana') .set('accept-encoding', 'gzip') - .then(response => { + .then((response) => { expect(response.headers).to.have.property('content-encoding', 'gzip'); }); }); @@ -50,7 +50,7 @@ export default function({ getService }) { .get('/app/kibana') .set('accept-encoding', 'gzip') .set('referer', 'https://some-host.com') - .then(response => { + .then((response) => { expect(response.headers).to.have.property('content-encoding', 'gzip'); }); }); @@ -60,7 +60,7 @@ export default function({ getService }) { .get('/app/kibana') .set('accept-encoding', 'gzip') .set('referer', 'https://other.some-host.com') - .then(response => { + .then((response) => { expect(response.headers).not.to.have.property('content-encoding'); }); }); diff --git a/test/api_integration/apis/elasticsearch/index.js b/test/api_integration/apis/elasticsearch/index.js index 78f00ee84d408..5a3dc47aab9bb 100644 --- a/test/api_integration/apis/elasticsearch/index.js +++ b/test/api_integration/apis/elasticsearch/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); diff --git a/test/api_integration/apis/general/cookies.js b/test/api_integration/apis/general/cookies.js index 27c7ecafc54c0..77f763965f135 100644 --- a/test/api_integration/apis/general/cookies.js +++ b/test/api_integration/apis/general/cookies.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('cookie handling', () => { @@ -27,7 +27,7 @@ export default function({ getService }) { supertest .get('/') .set('cookie', 'test:80=value;test_80=value') - .then(response => { + .then((response) => { expect(response.text).not.to.contain('Invalid cookie header'); })); @@ -36,7 +36,7 @@ export default function({ getService }) { .get('/') .set('cookie', 'a') .expect(400) - .then(response => { + .then((response) => { expect(response.text).to.contain('Invalid cookie header'); })); }); diff --git a/test/api_integration/apis/general/csp.js b/test/api_integration/apis/general/csp.js index 8c191703070d8..ea3c5b2c3024c 100644 --- a/test/api_integration/apis/general/csp.js +++ b/test/api_integration/apis/general/csp.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('csp smoke test', () => { @@ -29,7 +29,7 @@ export default function({ getService }) { expect(response.headers).to.have.property('content-security-policy'); const header = response.headers['content-security-policy']; const parsed = new Map( - header.split(';').map(rule => { + header.split(';').map((rule) => { const parts = rule.trim().split(' '); const key = parts.splice(0, 1)[0]; return [key, parts]; diff --git a/test/api_integration/apis/general/index.js b/test/api_integration/apis/general/index.js index 2420297fb1af9..86b7565cba6de 100644 --- a/test/api_integration/apis/general/index.js +++ b/test/api_integration/apis/general/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('general', () => { loadTestFile(require.resolve('./cookies')); loadTestFile(require.resolve('./csp')); diff --git a/test/api_integration/apis/home/index.js b/test/api_integration/apis/home/index.js index dce194d1e1195..f166d2e985573 100644 --- a/test/api_integration/apis/home/index.js +++ b/test/api_integration/apis/home/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('home apis', () => { loadTestFile(require.resolve('./sample_data')); }); diff --git a/test/api_integration/apis/home/sample_data.js b/test/api_integration/apis/home/sample_data.js index d5f03cc714f2f..16689b5e76ac3 100644 --- a/test/api_integration/apis/home/sample_data.js +++ b/test/api_integration/apis/home/sample_data.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); @@ -28,10 +28,7 @@ export default function({ getService }) { describe('sample data apis', () => { describe('list', () => { it('should return list of sample data sets with installed status', async () => { - const resp = await supertest - .get(`/api/sample_data`) - .set('kbn-xsrf', 'kibana') - .expect(200); + const resp = await supertest.get(`/api/sample_data`).set('kbn-xsrf', 'kibana').expect(200); expect(resp.body).to.be.an('array'); expect(resp.body.length).to.be.above(0); @@ -41,10 +38,7 @@ export default function({ getService }) { describe('install', () => { it('should return 404 if id does not match any sample data sets', async () => { - await supertest - .post(`/api/sample_data/xxxx`) - .set('kbn-xsrf', 'kibana') - .expect(404); + await supertest.post(`/api/sample_data/xxxx`).set('kbn-xsrf', 'kibana').expect(404); }); it('should return 200 if success', async () => { @@ -93,10 +87,7 @@ export default function({ getService }) { describe('uninstall', () => { it('should uninstall sample data', async () => { - await supertest - .delete(`/api/sample_data/flights`) - .set('kbn-xsrf', 'kibana') - .expect(204); + await supertest.delete(`/api/sample_data/flights`).set('kbn-xsrf', 'kibana').expect(204); }); it('should remove elasticsearch index containing sample data', async () => { diff --git a/test/api_integration/apis/index.js b/test/api_integration/apis/index.js index 0c4028905657d..79815199aa20c 100644 --- a/test/api_integration/apis/index.js +++ b/test/api_integration/apis/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('apis', () => { loadTestFile(require.resolve('./core')); loadTestFile(require.resolve('./elasticsearch')); diff --git a/test/api_integration/apis/index_patterns/es_errors/errors.js b/test/api_integration/apis/index_patterns/es_errors/errors.js index e4e18caad0dee..9da29a0d3a3da 100644 --- a/test/api_integration/apis/index_patterns/es_errors/errors.js +++ b/test/api_integration/apis/index_patterns/es_errors/errors.js @@ -30,7 +30,7 @@ import { import { getIndexNotFoundError, getDocNotFoundError } from './lib'; -export default function({ getService }) { +export default function ({ getService }) { const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); diff --git a/test/api_integration/apis/index_patterns/es_errors/index.js b/test/api_integration/apis/index_patterns/es_errors/index.js index 9a9895bec7087..38c67dbfc389f 100644 --- a/test/api_integration/apis/index_patterns/es_errors/index.js +++ b/test/api_integration/apis/index_patterns/es_errors/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('index_patterns/service/lib', () => { loadTestFile(require.resolve('./errors')); }); diff --git a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/errors.js b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/errors.js index cff13e57c7009..cdee9d2be7b7c 100644 --- a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/errors.js +++ b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/errors.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('errors', () => { diff --git a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/index.js b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/index.js index d5f706d648717..58d8ac6ebca2f 100644 --- a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/index.js +++ b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('index_patterns/_fields_for_time_pattern', () => { loadTestFile(require.resolve('./errors')); loadTestFile(require.resolve('./pattern')); diff --git a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/pattern.js b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/pattern.js index 4787b87d520b5..49c1b6e509d6b 100644 --- a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/pattern.js +++ b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/pattern.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -35,7 +35,7 @@ export default function({ getService }) { look_back: 2, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ fields: [ { @@ -74,7 +74,7 @@ export default function({ getService }) { look_back: 1, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ fields: [ { @@ -106,7 +106,7 @@ export default function({ getService }) { meta_fields: JSON.stringify(['meta1', 'meta2']), }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ fields: [ { diff --git a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/query_params.js b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/query_params.js index 2b687a70a6461..0602747766987 100644 --- a/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/query_params.js +++ b/test/api_integration/apis/index_patterns/fields_for_time_pattern_route/query_params.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -32,7 +32,7 @@ export default function({ getService }) { .get('/api/index_patterns/_fields_for_time_pattern') .query({ look_back: 1 }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body.message).to.contain( '[request query.pattern]: expected value of type [string] but got [undefined]' ); @@ -43,7 +43,7 @@ export default function({ getService }) { .get('/api/index_patterns/_fields_for_time_pattern') .query({ pattern: 'pattern-*' }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body.message).to.contain( '[request query.look_back]: expected value of type [number] but got [undefined]' ); @@ -77,7 +77,7 @@ export default function({ getService }) { look_back: 'foo', }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body.message).to.contain( '[request query.look_back]: expected value of type [number] but got [string]' ); @@ -91,7 +91,7 @@ export default function({ getService }) { look_back: 0, }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body.message).to.contain( '[request query.look_back]: Value must be equal to or greater than [1].' ); diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js index 95388919e916a..2095833682bf3 100644 --- a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js +++ b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/conflicts.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -32,7 +32,7 @@ export default function({ getService }) { .get('/api/index_patterns/_fields_for_wildcard') .query({ pattern: 'logs-*' }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ fields: [ { diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js index 350558d4eeffb..fc707e6775c84 100644 --- a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js +++ b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('index_patterns/_fields_for_wildcard route', () => { loadTestFile(require.resolve('./params')); loadTestFile(require.resolve('./conflicts')); diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js index a6a64f3d43fd8..a4dae83b8696d 100644 --- a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js +++ b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/params.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); const randomness = getService('randomness'); @@ -27,10 +27,7 @@ export default function({ getService }) { after(() => esArchiver.unload('index_patterns/basic_index')); it('requires a pattern query param', () => - supertest - .get('/api/index_patterns/_fields_for_wildcard') - .query({}) - .expect(400)); + supertest.get('/api/index_patterns/_fields_for_wildcard').query({}).expect(400)); it('accepts a JSON formatted meta_fields query param', () => supertest diff --git a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js index c4c71abdae125..45a09be6c2deb 100644 --- a/test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js +++ b/test/api_integration/apis/index_patterns/fields_for_wildcard_route/response.js @@ -20,11 +20,11 @@ import expect from '@kbn/expect'; import { sortBy } from 'lodash'; -export default function({ getService }) { +export default function ({ getService }) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); - const ensureFieldsAreSorted = resp => { + const ensureFieldsAreSorted = (resp) => { expect(resp.body.fields).to.eql(sortBy(resp.body.fields, 'name')); }; diff --git a/test/api_integration/apis/index_patterns/index.js b/test/api_integration/apis/index_patterns/index.js index 67d4f04b5e8bf..42f907ff8aec1 100644 --- a/test/api_integration/apis/index_patterns/index.js +++ b/test/api_integration/apis/index_patterns/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('index_patterns', () => { loadTestFile(require.resolve('./es_errors')); loadTestFile(require.resolve('./fields_for_time_pattern_route')); diff --git a/test/api_integration/apis/kql_telemetry/index.js b/test/api_integration/apis/kql_telemetry/index.js index b51d6b0431bd9..bf72fa90ac003 100644 --- a/test/api_integration/apis/kql_telemetry/index.js +++ b/test/api_integration/apis/kql_telemetry/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('KQL', () => { loadTestFile(require.resolve('./kql_telemetry')); }); diff --git a/test/api_integration/apis/kql_telemetry/kql_telemetry.js b/test/api_integration/apis/kql_telemetry/kql_telemetry.js index bc276fd42cc61..a696cd148485f 100644 --- a/test/api_integration/apis/kql_telemetry/kql_telemetry.js +++ b/test/api_integration/apis/kql_telemetry/kql_telemetry.js @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import Bluebird from 'bluebird'; import { get } from 'lodash'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); const es = getService('legacyEs'); @@ -42,7 +42,7 @@ export default function({ getService }) { index: '.kibana', q: 'type:kql-telemetry', }) - .then(response => { + .then((response) => { const kqlTelemetryDoc = get(response, 'hits.hits[0]._source.kql-telemetry'); expect(kqlTelemetryDoc.optInCount).to.be(1); }); @@ -60,7 +60,7 @@ export default function({ getService }) { index: '.kibana', q: 'type:kql-telemetry', }) - .then(response => { + .then((response) => { const kqlTelemetryDoc = get(response, 'hits.hits[0]._source.kql-telemetry'); expect(kqlTelemetryDoc.optOutCount).to.be(1); }); @@ -90,7 +90,7 @@ export default function({ getService }) { }); }); - it('should only accept literal boolean values for the opt_in POST body param', function() { + it('should only accept literal boolean values for the opt_in POST body param', function () { return Bluebird.all([ supertest .post('/api/kibana/kql_opt_in_telemetry') diff --git a/test/api_integration/apis/saved_objects/bulk_create.js b/test/api_integration/apis/saved_objects/bulk_create.js index a0d2717555150..6cb9d5dccdc9a 100644 --- a/test/api_integration/apis/saved_objects/bulk_create.js +++ b/test/api_integration/apis/saved_objects/bulk_create.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -51,7 +51,7 @@ export default function({ getService }) { .post(`/api/saved_objects/_bulk_create`) .send(BULK_REQUESTS) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ saved_objects: [ { @@ -87,7 +87,7 @@ export default function({ getService }) { // eslint-disable-next-line no-unused-vars .send(BULK_REQUESTS.map(({ id, ...rest }) => rest)) .expect(200) - .then(resp => { + .then((resp) => { resp.body.saved_objects.map(({ id }) => expect(id).not.match(/visualization|dashboard/) ); @@ -109,7 +109,7 @@ export default function({ getService }) { .post('/api/saved_objects/_bulk_create') .send(BULK_REQUESTS) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ saved_objects: [ { diff --git a/test/api_integration/apis/saved_objects/bulk_get.js b/test/api_integration/apis/saved_objects/bulk_get.js index 67e511f2bf548..23aa175740b67 100644 --- a/test/api_integration/apis/saved_objects/bulk_get.js +++ b/test/api_integration/apis/saved_objects/bulk_get.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -49,7 +49,7 @@ export default function({ getService }) { .post(`/api/saved_objects/_bulk_get`) .send(BULK_REQUESTS) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ saved_objects: [ { @@ -117,7 +117,7 @@ export default function({ getService }) { .post('/api/saved_objects/_bulk_get') .send(BULK_REQUESTS) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ saved_objects: [ { diff --git a/test/api_integration/apis/saved_objects/bulk_update.js b/test/api_integration/apis/saved_objects/bulk_update.js index 95a96e272a2ce..e3f994ff224e8 100644 --- a/test/api_integration/apis/saved_objects/bulk_update.js +++ b/test/api_integration/apis/saved_objects/bulk_update.js @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import _ from 'lodash'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); diff --git a/test/api_integration/apis/saved_objects/create.js b/test/api_integration/apis/saved_objects/create.js index 6ba03085bc6e5..eddda3aded141 100644 --- a/test/api_integration/apis/saved_objects/create.js +++ b/test/api_integration/apis/saved_objects/create.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -37,7 +37,7 @@ export default function({ getService }) { }, }) .expect(200) - .then(resp => { + .then((resp) => { // loose uuid validation expect(resp.body) .to.have.property('id') @@ -83,7 +83,7 @@ export default function({ getService }) { }, }) .expect(200) - .then(resp => { + .then((resp) => { // loose uuid validation expect(resp.body) .to.have.property('id') diff --git a/test/api_integration/apis/saved_objects/delete.js b/test/api_integration/apis/saved_objects/delete.js index 9335b3bc3df15..3fcbd2029294b 100644 --- a/test/api_integration/apis/saved_objects/delete.js +++ b/test/api_integration/apis/saved_objects/delete.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -33,7 +33,7 @@ export default function({ getService }) { await supertest .delete(`/api/saved_objects/dashboard/be3733a0-9efe-11e7-acb3-3dab96693fab`) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({}); })); @@ -41,7 +41,7 @@ export default function({ getService }) { await supertest .delete(`/api/saved_objects/dashboard/not-a-real-id`) .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 404, error: 'Not Found', @@ -64,7 +64,7 @@ export default function({ getService }) { await supertest .delete(`/api/saved_objects/dashboard/be3733a0-9efe-11e7-acb3-3dab96693fab`) .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 404, error: 'Not Found', diff --git a/test/api_integration/apis/saved_objects/export.js b/test/api_integration/apis/saved_objects/export.js index 9558e82880deb..0c37e6b782a35 100644 --- a/test/api_integration/apis/saved_objects/export.js +++ b/test/api_integration/apis/saved_objects/export.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -37,7 +37,7 @@ export default function({ getService }) { type: ['index-pattern', 'search', 'visualization', 'dashboard'], }) .expect(200) - .then(resp => { + .then((resp) => { const objects = resp.text.split('\n').map(JSON.parse); expect(objects).to.have.length(4); expect(objects[0]).to.have.property('id', '91200a00-9efd-11e7-acb3-3dab96693fab'); @@ -60,7 +60,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(200) - .then(resp => { + .then((resp) => { const objects = resp.text.split('\n').map(JSON.parse); expect(objects).to.have.length(3); expect(objects[0]).to.have.property('id', '91200a00-9efd-11e7-acb3-3dab96693fab'); @@ -85,7 +85,7 @@ export default function({ getService }) { ], }) .expect(200) - .then(resp => { + .then((resp) => { const objects = resp.text.split('\n').map(JSON.parse); expect(objects).to.have.length(4); expect(objects[0]).to.have.property('id', '91200a00-9efd-11e7-acb3-3dab96693fab'); @@ -108,7 +108,7 @@ export default function({ getService }) { type: ['dashboard'], }) .expect(200) - .then(resp => { + .then((resp) => { const objects = resp.text.split('\n').map(JSON.parse); expect(objects).to.have.length(4); expect(objects[0]).to.have.property('id', '91200a00-9efd-11e7-acb3-3dab96693fab'); @@ -132,7 +132,7 @@ export default function({ getService }) { search: 'Requests*', }) .expect(200) - .then(resp => { + .then((resp) => { const objects = resp.text.split('\n').map(JSON.parse); expect(objects).to.have.length(4); expect(objects[0]).to.have.property('id', '91200a00-9efd-11e7-acb3-3dab96693fab'); @@ -159,7 +159,7 @@ export default function({ getService }) { ], }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -188,7 +188,7 @@ export default function({ getService }) { type: ['wigwags'], }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -209,7 +209,7 @@ export default function({ getService }) { ], }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -227,7 +227,7 @@ export default function({ getService }) { await supertest .post('/api/saved_objects/_export') .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -244,7 +244,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.headers['content-disposition']).to.eql( 'attachment; filename="export.ndjson"' ); @@ -303,7 +303,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.headers['content-disposition']).to.eql( 'attachment; filename="export.ndjson"' ); @@ -367,7 +367,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.headers['content-disposition']).to.eql( 'attachment; filename="export.ndjson"' ); @@ -432,7 +432,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -454,7 +454,7 @@ export default function({ getService }) { }, }) .expect(200) - .then(resp => { + .then((resp) => { customVisId = resp.body.id; }); }); @@ -471,7 +471,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -500,7 +500,7 @@ export default function({ getService }) { excludeExportDetails: true, }) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.text).to.eql(''); }); }); diff --git a/test/api_integration/apis/saved_objects/find.js b/test/api_integration/apis/saved_objects/find.js index 54a19602fd414..7a57d182bc812 100644 --- a/test/api_integration/apis/saved_objects/find.js +++ b/test/api_integration/apis/saved_objects/find.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -33,7 +33,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=visualization&fields=title') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -66,7 +66,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=wigwags') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -81,7 +81,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=visualization&page=100&per_page=100') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 100, per_page: 100, @@ -96,7 +96,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=url&search_fields=a') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -113,7 +113,7 @@ export default function({ getService }) { '/api/saved_objects/_find?type=visualization&filter=visualization.attributes.title:"Count of requests"' ) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -155,7 +155,7 @@ export default function({ getService }) { '/api/saved_objects/_find?type=visualization&filter=dashboard.attributes.title:foo' ) .expect(400) - .then(resp => { + .then((resp) => { console.log('body', JSON.stringify(resp.body)); expect(resp.body).to.eql({ error: 'Bad Request', @@ -170,7 +170,7 @@ export default function({ getService }) { '/api/saved_objects/_find?type=dashboard&filter=dashboard.attributes.title:foo { + .then((resp) => { console.log('body', JSON.stringify(resp.body)); expect(resp.body).to.eql({ error: 'Bad Request', @@ -198,7 +198,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=visualization') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -212,7 +212,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=wigwags') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -227,7 +227,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find') .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ error: 'Bad Request', message: @@ -242,7 +242,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=visualization&page=100&per_page=100') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 100, per_page: 100, @@ -257,7 +257,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/_find?type=url&search_fields=a') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -274,7 +274,7 @@ export default function({ getService }) { '/api/saved_objects/_find?type=visualization&filter=visualization.attributes.title:"Count of requests"' ) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ page: 1, per_page: 20, @@ -289,7 +289,7 @@ export default function({ getService }) { '/api/saved_objects/_find?type=visualization&filter=dashboard.attributes.title:foo' ) .expect(400) - .then(resp => { + .then((resp) => { console.log('body', JSON.stringify(resp.body)); expect(resp.body).to.eql({ error: 'Bad Request', diff --git a/test/api_integration/apis/saved_objects/get.js b/test/api_integration/apis/saved_objects/get.js index 6f5991fdefa2b..55dfda251a75a 100644 --- a/test/api_integration/apis/saved_objects/get.js +++ b/test/api_integration/apis/saved_objects/get.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -33,7 +33,7 @@ export default function({ getService }) { await supertest .get(`/api/saved_objects/visualization/dd7caf20-9efd-11e7-acb3-3dab96693fab`) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ id: 'dd7caf20-9efd-11e7-acb3-3dab96693fab', type: 'visualization', @@ -65,7 +65,7 @@ export default function({ getService }) { await supertest .get(`/api/saved_objects/visualization/foobar`) .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ error: 'Not Found', message: 'Saved object [visualization/foobar] not found', @@ -89,7 +89,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/visualization/dd7caf20-9efd-11e7-acb3-3dab96693fab') .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ error: 'Not Found', message: diff --git a/test/api_integration/apis/saved_objects/import.js b/test/api_integration/apis/saved_objects/import.js index 63f4e048eb581..fbacfe458d976 100644 --- a/test/api_integration/apis/saved_objects/import.js +++ b/test/api_integration/apis/saved_objects/import.js @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { join } from 'path'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -36,7 +36,7 @@ export default function({ getService }) { .query({ overwrite: true }) .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 3, @@ -48,7 +48,7 @@ export default function({ getService }) { await supertest .post('/api/saved_objects/_import') .expect(415) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 415, error: 'Unsupported Media Type', @@ -62,7 +62,7 @@ export default function({ getService }) { .post('/api/saved_objects/_import') .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: false, successCount: 0, @@ -104,7 +104,7 @@ export default function({ getService }) { }) .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 3, @@ -121,7 +121,7 @@ export default function({ getService }) { .post('/api/saved_objects/_import') .attach('file', fileBuffer, 'export.ndjson') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: false, successCount: 0, @@ -148,7 +148,7 @@ export default function({ getService }) { .post('/api/saved_objects/_import') .attach('file', Buffer.from(fileChunks.join('\n'), 'utf8'), 'export.ndjson') .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -181,7 +181,7 @@ export default function({ getService }) { .post('/api/saved_objects/_import') .attach('file', Buffer.from(objectsToImport.join('\n'), 'utf8'), 'export.ndjson') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: false, successCount: 0, diff --git a/test/api_integration/apis/saved_objects/index.js b/test/api_integration/apis/saved_objects/index.js index 52fead57c3505..ad6c3749181dd 100644 --- a/test/api_integration/apis/saved_objects/index.js +++ b/test/api_integration/apis/saved_objects/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('saved_objects', () => { loadTestFile(require.resolve('./bulk_create')); loadTestFile(require.resolve('./bulk_get')); diff --git a/test/api_integration/apis/saved_objects/migrations.js b/test/api_integration/apis/saved_objects/migrations.js index 9d908b95ca575..d0ff4cc06c57e 100644 --- a/test/api_integration/apis/saved_objects/migrations.js +++ b/test/api_integration/apis/saved_objects/migrations.js @@ -56,12 +56,12 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': doc => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), + '1.0.0': (doc) => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, bar: { - '1.0.0': doc => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), - '1.3.0': doc => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), - '1.9.0': doc => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), + '1.0.0': (doc) => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), + '1.3.0': (doc) => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), + '1.9.0': (doc) => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), }, }; @@ -172,12 +172,12 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': doc => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), + '1.0.0': (doc) => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, bar: { - '1.0.0': doc => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), - '1.3.0': doc => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), - '1.9.0': doc => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), + '1.0.0': (doc) => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), + '1.3.0': (doc) => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), + '1.9.0': (doc) => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), }, }; @@ -187,8 +187,8 @@ export default ({ getService }) => { await migrateIndex({ callCluster, index, migrations, mappingProperties }); mappingProperties.bar.properties.name = { type: 'keyword' }; - migrations.foo['2.0.1'] = doc => _.set(doc, 'attributes.name', `${doc.attributes.name}v2`); - migrations.bar['2.3.4'] = doc => _.set(doc, 'attributes.name', `NAME ${doc.id}`); + migrations.foo['2.0.1'] = (doc) => _.set(doc, 'attributes.name', `${doc.attributes.name}v2`); + migrations.bar['2.3.4'] = (doc) => _.set(doc, 'attributes.name', `NAME ${doc.id}`); await migrateIndex({ callCluster, index, migrations, mappingProperties }); @@ -267,7 +267,7 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': doc => _.set(doc, 'attributes.name', 'LOTR'), + '1.0.0': (doc) => _.set(doc, 'attributes.name', 'LOTR'), }, }; @@ -284,7 +284,7 @@ export default ({ getService }) => { assert.deepEqual( result .map(({ status, destIndex }) => ({ status, destIndex })) - .sort(a => (a.destIndex ? 0 : 1)), + .sort((a) => (a.destIndex ? 0 : 1)), [ { status: 'migrated', destIndex: '.migration-c_2' }, { status: 'skipped', destIndex: undefined }, @@ -354,7 +354,7 @@ async function migrateIndex({ }) { const typeRegistry = new SavedObjectTypeRegistry(); const types = migrationsToTypes(migrations); - types.forEach(type => typeRegistry.registerType(type)); + types.forEach((type) => typeRegistry.registerType(type)); const documentMigrator = new DocumentMigrator({ kibanaVersion: '99.9.9', @@ -394,7 +394,7 @@ async function fetchDocs({ callCluster, index }) { hits: { hits }, } = await callCluster('search', { index }); return hits - .map(h => ({ + .map((h) => ({ ...h._source, id: h._id, })) diff --git a/test/api_integration/apis/saved_objects/resolve_import_errors.js b/test/api_integration/apis/saved_objects/resolve_import_errors.js index 60d2f42d51d13..aacfcd4382fac 100644 --- a/test/api_integration/apis/saved_objects/resolve_import_errors.js +++ b/test/api_integration/apis/saved_objects/resolve_import_errors.js @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { join } from 'path'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -35,7 +35,7 @@ export default function({ getService }) { .field('retries', '[]') .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 0, @@ -68,7 +68,7 @@ export default function({ getService }) { ) .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 3, @@ -81,7 +81,7 @@ export default function({ getService }) { .post('/api/saved_objects/_resolve_import_errors') .field('retries', '[]') .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -100,7 +100,7 @@ export default function({ getService }) { .field('retries', JSON.stringify([{ type: 'wigwags', id: '1' }])) .attach('file', fileBuffer, 'export.ndjson') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: false, successCount: 0, @@ -128,7 +128,7 @@ export default function({ getService }) { .field('retries', '[]') .attach('file', Buffer.from(fileChunks.join('\n'), 'utf8'), 'export.ndjson') .expect(400) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ statusCode: 400, error: 'Bad Request', @@ -166,7 +166,7 @@ export default function({ getService }) { ) .attach('file', Buffer.from(JSON.stringify(objToInsert), 'utf8'), 'export.ndjson') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: false, successCount: 0, @@ -203,7 +203,7 @@ export default function({ getService }) { .field('retries', '[]') .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 0 }); }); }); @@ -233,7 +233,7 @@ export default function({ getService }) { ) .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 3 }); }); }); @@ -253,7 +253,7 @@ export default function({ getService }) { ) .attach('file', join(__dirname, '../../fixtures/import.ndjson')) .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 1 }); }); }); @@ -294,7 +294,7 @@ export default function({ getService }) { ) .attach('file', Buffer.from(JSON.stringify(objToInsert), 'utf8'), 'export.ndjson') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body).to.eql({ success: true, successCount: 1, @@ -303,7 +303,7 @@ export default function({ getService }) { await supertest .get('/api/saved_objects/visualization/1') .expect(200) - .then(resp => { + .then((resp) => { expect(resp.body.references).to.eql([ { name: 'ref_0', diff --git a/test/api_integration/apis/saved_objects/update.js b/test/api_integration/apis/saved_objects/update.js index d228803f3ecba..d613f46878bb5 100644 --- a/test/api_integration/apis/saved_objects/update.js +++ b/test/api_integration/apis/saved_objects/update.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); const esArchiver = getService('esArchiver'); @@ -37,7 +37,7 @@ export default function({ getService }) { }, }) .expect(200) - .then(resp => { + .then((resp) => { // loose uuid validation expect(resp.body) .to.have.property('id') @@ -115,7 +115,7 @@ export default function({ getService }) { }, }) .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).eql({ statusCode: 404, error: 'Not Found', @@ -145,7 +145,7 @@ export default function({ getService }) { }, }) .expect(404) - .then(resp => { + .then((resp) => { expect(resp.body).eql({ statusCode: 404, error: 'Not Found', diff --git a/test/api_integration/apis/saved_objects_management/find.ts b/test/api_integration/apis/saved_objects_management/find.ts index ef7c5ab22ee66..115399cb57dfa 100644 --- a/test/api_integration/apis/saved_objects_management/find.ts +++ b/test/api_integration/apis/saved_objects_management/find.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { Response } from 'supertest'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const es = getService('legacyEs'); const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); diff --git a/test/api_integration/apis/saved_objects_management/index.ts b/test/api_integration/apis/saved_objects_management/index.ts index 5895940c4bbef..9f13e4fc5975d 100644 --- a/test/api_integration/apis/saved_objects_management/index.ts +++ b/test/api_integration/apis/saved_objects_management/index.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ loadTestFile }: FtrProviderContext) { +export default function ({ loadTestFile }: FtrProviderContext) { describe('saved objects management apis', () => { loadTestFile(require.resolve('./find')); loadTestFile(require.resolve('./relationships')); diff --git a/test/api_integration/apis/saved_objects_management/relationships.ts b/test/api_integration/apis/saved_objects_management/relationships.ts index 00972a97f41e8..bbc691dbc6398 100644 --- a/test/api_integration/apis/saved_objects_management/relationships.ts +++ b/test/api_integration/apis/saved_objects_management/relationships.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { schema } from '@kbn/config-schema'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); @@ -54,7 +54,7 @@ export default function({ getService }: FtrProviderContext) { const defaultTypes = ['visualization', 'index-pattern', 'search', 'dashboard']; const relationshipsUrl = (type: string, id: string, types: string[] = defaultTypes) => { - const typesQuery = types.map(t => `savedObjectTypes=${t}`).join('&'); + const typesQuery = types.map((t) => `savedObjectTypes=${t}`).join('&'); return `${baseApiUrl}/${type}/${id}?${typesQuery}`; }; diff --git a/test/api_integration/apis/saved_objects_management/scroll_count.ts b/test/api_integration/apis/saved_objects_management/scroll_count.ts index 3c29d45244dec..2f102465b121d 100644 --- a/test/api_integration/apis/saved_objects_management/scroll_count.ts +++ b/test/api_integration/apis/saved_objects_management/scroll_count.ts @@ -24,7 +24,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; const apiUrl = '/api/kibana/management/saved_objects/scroll/counts'; const defaultTypes = ['visualization', 'index-pattern', 'search', 'dashboard']; -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest') as SuperTest; const esArchiver = getService('esArchiver'); diff --git a/test/api_integration/apis/scripts/index.js b/test/api_integration/apis/scripts/index.js index f4ede916b8dc7..6f27dee3e045e 100644 --- a/test/api_integration/apis/scripts/index.js +++ b/test/api_integration/apis/scripts/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('scripts', () => { loadTestFile(require.resolve('./languages')); }); diff --git a/test/api_integration/apis/scripts/languages.js b/test/api_integration/apis/scripts/languages.js index 8d1fa4c19d756..0ab3acd211388 100644 --- a/test/api_integration/apis/scripts/languages.js +++ b/test/api_integration/apis/scripts/languages.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('Script Languages API', function getLanguages() { @@ -27,7 +27,7 @@ export default function({ getService }) { supertest .get('/api/kibana/scripts/languages') .expect(200) - .then(response => { + .then((response) => { expect(response.body).to.be.an('array'); })); @@ -36,7 +36,7 @@ export default function({ getService }) { supertest .get('/api/kibana/scripts/languages') .expect(200) - .then(response => { + .then((response) => { expect(response.body).to.contain('expression'); expect(response.body).to.contain('painless'); expect(response.body).to.not.contain('groovy'); diff --git a/test/api_integration/apis/shorten/index.js b/test/api_integration/apis/shorten/index.js index 651868729b69f..aa9c2d08e185c 100644 --- a/test/api_integration/apis/shorten/index.js +++ b/test/api_integration/apis/shorten/index.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); diff --git a/test/api_integration/apis/stats/index.js b/test/api_integration/apis/stats/index.js index f719b20eca388..985c59bac0e5d 100644 --- a/test/api_integration/apis/stats/index.js +++ b/test/api_integration/apis/stats/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('stats', () => { loadTestFile(require.resolve('./stats')); }); diff --git a/test/api_integration/apis/stats/stats.js b/test/api_integration/apis/stats/stats.js index 95b658782f951..a40427fea8b94 100644 --- a/test/api_integration/apis/stats/stats.js +++ b/test/api_integration/apis/stats/stats.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -const assertStatsAndMetrics = body => { +const assertStatsAndMetrics = (body) => { expect(body.kibana.name).to.be.a('string'); expect(body.kibana.uuid).to.be.a('string'); expect(body.kibana.host).to.be.a('string'); @@ -53,7 +53,7 @@ const assertStatsAndMetrics = body => { expect(body.concurrent_connections).to.be.a('number'); }; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana stats api', () => { describe('basic', () => { diff --git a/test/api_integration/apis/status/index.js b/test/api_integration/apis/status/index.js index 5c0b12bf2e229..d9cb161dc3f2b 100644 --- a/test/api_integration/apis/status/index.js +++ b/test/api_integration/apis/status/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('status', () => { loadTestFile(require.resolve('./status')); }); diff --git a/test/api_integration/apis/status/status.js b/test/api_integration/apis/status/status.js index 4982337b8d101..c60d354090cc2 100644 --- a/test/api_integration/apis/status/status.js +++ b/test/api_integration/apis/status/status.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana status api', () => { @@ -39,7 +39,7 @@ export default function({ getService }) { expect(body.status.overall.state).to.be('green'); expect(body.status.statuses).to.be.an('array'); - const kibanaPlugin = body.status.statuses.find(s => { + const kibanaPlugin = body.status.statuses.find((s) => { return s.id.indexOf('plugin:kibana') === 0; }); expect(kibanaPlugin.state).to.be('green'); diff --git a/test/api_integration/apis/suggestions/index.js b/test/api_integration/apis/suggestions/index.js index 3e232d3c6c1e3..20bc1dea2c3c6 100644 --- a/test/api_integration/apis/suggestions/index.js +++ b/test/api_integration/apis/suggestions/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('suggestions', () => { loadTestFile(require.resolve('./suggestions')); }); diff --git a/test/api_integration/apis/suggestions/suggestions.js b/test/api_integration/apis/suggestions/suggestions.js index faa10c1a7e933..d6c0b94de8588 100644 --- a/test/api_integration/apis/suggestions/suggestions.js +++ b/test/api_integration/apis/suggestions/suggestions.js @@ -17,11 +17,11 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); - describe('Suggestions API', function() { + describe('Suggestions API', function () { before(async () => { await esArchiver.load('index_patterns/basic_index'); await esArchiver.load('index_patterns/basic_kibana'); diff --git a/test/api_integration/apis/telemetry/index.js b/test/api_integration/apis/telemetry/index.js index c79f5cb470890..a46edecea204f 100644 --- a/test/api_integration/apis/telemetry/index.js +++ b/test/api_integration/apis/telemetry/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('Telemetry', () => { loadTestFile(require.resolve('./telemetry_local')); loadTestFile(require.resolve('./opt_in')); diff --git a/test/api_integration/apis/telemetry/opt_in.ts b/test/api_integration/apis/telemetry/opt_in.ts index e4654ee3985f3..42bda37b6d0b3 100644 --- a/test/api_integration/apis/telemetry/opt_in.ts +++ b/test/api_integration/apis/telemetry/opt_in.ts @@ -32,7 +32,7 @@ export default function optInTest({ getService }: FtrProviderContext) { const kibanaVersionAccessor = kibanaServer.version; kibanaVersion = await kibanaVersionAccessor.get(); defaultAttributes = - (await getSavedObjectAttributes(supertest).catch(err => { + (await getSavedObjectAttributes(supertest).catch((err) => { if (err.message === 'expected 200 "OK", got 404 "Not Found"') { return null; } diff --git a/test/api_integration/apis/telemetry/telemetry_local.js b/test/api_integration/apis/telemetry/telemetry_local.js index 84bfd8a755c11..2875ff09a9a8d 100644 --- a/test/api_integration/apis/telemetry/telemetry_local.js +++ b/test/api_integration/apis/telemetry/telemetry_local.js @@ -35,7 +35,7 @@ function flatKeys(source) { return _.uniq(_.flattenDeep(recursivelyFlatKeys(source))).sort((a, b) => a.localeCompare(b)); } -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('/api/telemetry/v2/clusters/_stats', () => { @@ -127,7 +127,7 @@ export default function({ getService }) { 'version', ]; - expect(expected.every(m => actual.includes(m))).to.be.ok(); + expect(expected.every((m) => actual.includes(m))).to.be.ok(); }); }); } diff --git a/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts b/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts index 4413c672fb46c..e9a2e794b5a2c 100644 --- a/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts +++ b/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts @@ -39,10 +39,7 @@ export default function optInTest({ getService }: FtrProviderContext) { } } - await supertest - .put('/api/telemetry/v2/userHasSeenNotice') - .set('kbn-xsrf', 'xxx') - .expect(200); + await supertest.put('/api/telemetry/v2/userHasSeenNotice').set('kbn-xsrf', 'xxx').expect(200); const { _source: { telemetry }, diff --git a/test/api_integration/apis/ui_metric/index.js b/test/api_integration/apis/ui_metric/index.js index 1d6b91dbd00ce..ce61f15f9ce36 100644 --- a/test/api_integration/apis/ui_metric/index.js +++ b/test/api_integration/apis/ui_metric/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('UI Metric', () => { loadTestFile(require.resolve('./ui_metric')); }); diff --git a/test/api_integration/apis/ui_metric/ui_metric.js b/test/api_integration/apis/ui_metric/ui_metric.js index 5ddbd8649589c..b7d5c81b538a6 100644 --- a/test/api_integration/apis/ui_metric/ui_metric.js +++ b/test/api_integration/apis/ui_metric/ui_metric.js @@ -20,18 +20,18 @@ import expect from '@kbn/expect'; import { ReportManager, METRIC_TYPE } from '@kbn/analytics'; -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); const es = getService('legacyEs'); - const createStatsMetric = eventName => ({ + const createStatsMetric = (eventName) => ({ eventName, appName: 'myApp', type: METRIC_TYPE.CLICK, count: 1, }); - const createUserAgentMetric = appName => ({ + const createUserAgentMetric = (appName) => ({ appName, type: METRIC_TYPE.USER_AGENT, userAgent: diff --git a/test/api_integration/config.js b/test/api_integration/config.js index 936317e9d95f9..071e7fc6ba3fd 100644 --- a/test/api_integration/config.js +++ b/test/api_integration/config.js @@ -19,7 +19,7 @@ import { services } from './services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const commonConfig = await readConfigFile(require.resolve('../common/config')); const functionalConfig = await readConfigFile(require.resolve('../functional/config')); diff --git a/test/common/config.js b/test/common/config.js index ca80dfb01012f..9b58da4473738 100644 --- a/test/common/config.js +++ b/test/common/config.js @@ -22,7 +22,7 @@ import { format as formatUrl } from 'url'; import { OPTIMIZE_BUNDLE_DIR, esTestConfig, kbnTestConfig, kibanaServerTestUser } from '@kbn/test'; import { services } from './services'; -export default function() { +export default function () { const servers = { kibana: kbnTestConfig.getUrlParts(), elasticsearch: esTestConfig.getUrlParts(), diff --git a/test/common/services/kibana_server/extend_es_archiver.js b/test/common/services/kibana_server/extend_es_archiver.js index d934e6725a9f5..4efdfc4dddf77 100644 --- a/test/common/services/kibana_server/extend_es_archiver.js +++ b/test/common/services/kibana_server/extend_es_archiver.js @@ -26,7 +26,7 @@ export function extendEsArchiver({ esArchiver, kibanaServer, retry, defaults }) return; } - ES_ARCHIVER_LOAD_METHODS.forEach(method => { + ES_ARCHIVER_LOAD_METHODS.forEach((method) => { const originalMethod = esArchiver[method]; esArchiver[method] = async (...args) => { diff --git a/test/common/services/retry/retry_for_success.ts b/test/common/services/retry/retry_for_success.ts index 398cd15f7f7e1..d30f4ebce9c2c 100644 --- a/test/common/services/retry/retry_for_success.ts +++ b/test/common/services/retry/retry_for_success.ts @@ -20,7 +20,7 @@ import { ToolingLog } from '@kbn/dev-utils'; import { inspect } from 'util'; -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const returnTrue = () => true; diff --git a/test/common/services/retry/retry_for_truthy.ts b/test/common/services/retry/retry_for_truthy.ts index 09f5cd4844ff6..e5c189511f913 100644 --- a/test/common/services/retry/retry_for_truthy.ts +++ b/test/common/services/retry/retry_for_truthy.ts @@ -40,7 +40,7 @@ export async function retryForTruthy( methodName, block, onFailureBlock, - onFailure: lastError => { + onFailure: (lastError) => { let msg = `timed out waiting for ${description}`; if (lastError) { @@ -49,6 +49,6 @@ export async function retryForTruthy( throw new Error(msg); }, - accept: result => Boolean(result), + accept: (result) => Boolean(result), }); } diff --git a/test/examples/config.js b/test/examples/config.js index 2be34459d8d06..aedd06c31d413 100644 --- a/test/examples/config.js +++ b/test/examples/config.js @@ -20,7 +20,7 @@ import path from 'path'; import { services } from '../plugin_functional/services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); return { diff --git a/test/examples/embeddables/adding_children.ts b/test/examples/embeddables/adding_children.ts index 9ec4b6cffd31a..25fe7ee607f72 100644 --- a/test/examples/embeddables/adding_children.ts +++ b/test/examples/embeddables/adding_children.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const flyout = getService('flyout'); diff --git a/test/examples/embeddables/hello_world_embeddable.ts b/test/examples/embeddables/hello_world_embeddable.ts index 1d8c651ea3fe6..0691a04694a2f 100644 --- a/test/examples/embeddables/hello_world_embeddable.ts +++ b/test/examples/embeddables/hello_world_embeddable.ts @@ -22,7 +22,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const retry = getService('retry'); diff --git a/test/examples/embeddables/index.ts b/test/examples/embeddables/index.ts index 8ad0961fcc3b6..878b1b9277ba1 100644 --- a/test/examples/embeddables/index.ts +++ b/test/examples/embeddables/index.ts @@ -20,7 +20,7 @@ import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ +export default function ({ getService, getPageObjects, loadTestFile, @@ -29,7 +29,7 @@ export default function({ const appsMenu = getService('appsMenu'); const PageObjects = getPageObjects(['common', 'header']); - describe('embeddable explorer', function() { + describe('embeddable explorer', function () { before(async () => { await browser.setWindowSize(1300, 900); await PageObjects.common.navigateToApp('settings'); diff --git a/test/examples/embeddables/list_container.ts b/test/examples/embeddables/list_container.ts index 9e93d479471e8..8050f57ebb889 100644 --- a/test/examples/embeddables/list_container.ts +++ b/test/examples/embeddables/list_container.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const retry = getService('retry'); diff --git a/test/examples/embeddables/todo_embeddable.ts b/test/examples/embeddables/todo_embeddable.ts index 08e722911997a..fb9e22016dab3 100644 --- a/test/examples/embeddables/todo_embeddable.ts +++ b/test/examples/embeddables/todo_embeddable.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const retry = getService('retry'); diff --git a/test/examples/search/demo_data.ts b/test/examples/search/demo_data.ts index 9774648b8223d..35f49744d1d6e 100644 --- a/test/examples/search/demo_data.ts +++ b/test/examples/search/demo_data.ts @@ -20,7 +20,7 @@ import { FtrProviderContext } from 'test/functional/ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); describe('demo search strategy', () => { diff --git a/test/examples/search/es_search.ts b/test/examples/search/es_search.ts index e67ed07c6c9f9..d868e245ebf82 100644 --- a/test/examples/search/es_search.ts +++ b/test/examples/search/es_search.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from 'test/functional/ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); describe('es search strategy', () => { diff --git a/test/examples/search/index.ts b/test/examples/search/index.ts index 819230f9e6fd9..2fb37afd248e2 100644 --- a/test/examples/search/index.ts +++ b/test/examples/search/index.ts @@ -20,14 +20,14 @@ import { FtrProviderContext } from 'test/functional/ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { +export default function ({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); const appsMenu = getService('appsMenu'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'header']); - describe('search services', function() { + describe('search services', function () { before(async () => { await esArchiver.loadIfNeeded('../functional/fixtures/es_archiver/dashboard/current/data'); await esArchiver.load('../functional/fixtures/es_archiver/dashboard/current/kibana'); @@ -40,7 +40,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide await appsMenu.clickLink('Search Explorer'); }); - after(async function() { + after(async function () { await esArchiver.unload('../functional/fixtures/es_archiver/dashboard/current/data'); await esArchiver.unload('../functional/fixtures/es_archiver/dashboard/current/kibana'); }); diff --git a/test/examples/state_sync/index.ts b/test/examples/state_sync/index.ts index 3c524f0feb619..ea1c7692f64fe 100644 --- a/test/examples/state_sync/index.ts +++ b/test/examples/state_sync/index.ts @@ -20,7 +20,7 @@ import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ +export default function ({ getService, getPageObjects, loadTestFile, @@ -28,7 +28,7 @@ export default function({ const browser = getService('browser'); const PageObjects = getPageObjects(['common']); - describe('state sync examples', function() { + describe('state sync examples', function () { before(async () => { await browser.setWindowSize(1300, 900); await PageObjects.common.navigateToApp('settings'); diff --git a/test/examples/state_sync/todo_app.ts b/test/examples/state_sync/todo_app.ts index 4933d746ca4fd..71b491a05ae2f 100644 --- a/test/examples/state_sync/todo_app.ts +++ b/test/examples/state_sync/todo_app.ts @@ -22,7 +22,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const find = getService('find'); const retry = getService('retry'); diff --git a/test/examples/ui_actions/index.ts b/test/examples/ui_actions/index.ts index d69e6a876cfa2..55137e2acc2b7 100644 --- a/test/examples/ui_actions/index.ts +++ b/test/examples/ui_actions/index.ts @@ -20,7 +20,7 @@ import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ +export default function ({ getService, getPageObjects, loadTestFile, @@ -29,7 +29,7 @@ export default function({ const appsMenu = getService('appsMenu'); const PageObjects = getPageObjects(['common', 'header']); - describe('ui actions explorer', function() { + describe('ui actions explorer', function () { before(async () => { await browser.setWindowSize(1300, 900); await PageObjects.common.navigateToApp('settings'); diff --git a/test/examples/ui_actions/ui_actions.ts b/test/examples/ui_actions/ui_actions.ts index 8fe599a907070..092a05c4ba2a7 100644 --- a/test/examples/ui_actions/ui_actions.ts +++ b/test/examples/ui_actions/ui_actions.ts @@ -22,7 +22,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from 'test/plugin_functional/services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const retry = getService('retry'); diff --git a/test/functional/apps/bundles/index.js b/test/functional/apps/bundles/index.js index 8a25c7cd1fafc..503517a98c69e 100644 --- a/test/functional/apps/bundles/index.js +++ b/test/functional/apps/bundles/index.js @@ -21,10 +21,10 @@ * These supertest-based tests live in the functional test suite because they depend on the optimizer bundles being built * and served */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); - describe('bundle compression', function() { + describe('bundle compression', function () { this.tags('ciGroup12'); let buildNum; diff --git a/test/functional/apps/console/_console.ts b/test/functional/apps/console/_console.ts index 47b8a4a2e9f70..2c2528ab8c41d 100644 --- a/test/functional/apps/console/_console.ts +++ b/test/functional/apps/console/_console.ts @@ -32,7 +32,7 @@ GET _search `.trim(); // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const retry = getService('retry'); const log = getService('log'); const find = getService('find'); diff --git a/test/functional/apps/console/index.js b/test/functional/apps/console/index.js index 7d5caee28e5d4..9e568c0ebbef0 100644 --- a/test/functional/apps/console/index.js +++ b/test/functional/apps/console/index.js @@ -17,13 +17,13 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); - describe('console app', function() { + describe('console app', function () { this.tags('ciGroup1'); - before(async function() { + before(async function () { await browser.setWindowSize(1300, 1100); }); diff --git a/test/functional/apps/context/_context_navigation.js b/test/functional/apps/context/_context_navigation.js index 42c67a37bd4bb..92b109c7263ff 100644 --- a/test/functional/apps/context/_context_navigation.js +++ b/test/functional/apps/context/_context_navigation.js @@ -29,18 +29,20 @@ const TEST_FILTER_COLUMN_NAMES = [ ], ]; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const docTable = getService('docTable'); const PageObjects = getPageObjects(['common', 'context', 'discover', 'timePicker']); // FLAKY: https://github.com/elastic/kibana/issues/62866 describe.skip('context link in discover', function contextSize() { - before(async function() { + before(async function () { await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setDefaultAbsoluteRange(); await Promise.all( - TEST_COLUMN_NAMES.map(columnName => PageObjects.discover.clickFieldListItemAdd(columnName)) + TEST_COLUMN_NAMES.map((columnName) => + PageObjects.discover.clickFieldListItemAdd(columnName) + ) ); for (const [columnName, value] of TEST_FILTER_COLUMN_NAMES) { await PageObjects.discover.clickFieldListItem(columnName); @@ -48,7 +50,7 @@ export default function({ getService, getPageObjects }) { } }); - it('should go back after loading', async function() { + it('should go back after loading', async function () { // navigate to the context view await docTable.clickRowToggle({ rowIndex: 0 }); await (await docTable.getRowActions({ rowIndex: 0 }))[0].click(); diff --git a/test/functional/apps/context/_date_nanos.js b/test/functional/apps/context/_date_nanos.js index bd132e3745caa..cdf2d6c04be83 100644 --- a/test/functional/apps/context/_date_nanos.js +++ b/test/functional/apps/context/_date_nanos.js @@ -23,7 +23,7 @@ const TEST_INDEX_PATTERN = 'date-nanos'; const TEST_DEFAULT_CONTEXT_SIZE = 1; const TEST_STEP_SIZE = 3; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const docTable = getService('docTable'); const security = getService('security'); @@ -31,7 +31,7 @@ export default function({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); describe('context view for date_nanos', () => { - before(async function() { + before(async function () { await security.testUser.setRoles(['kibana_admin', 'kibana_date_nanos']); await esArchiver.loadIfNeeded('date_nanos'); await kibanaServer.uiSettings.replace({ defaultIndex: TEST_INDEX_PATTERN }); @@ -46,7 +46,7 @@ export default function({ getService, getPageObjects }) { await esArchiver.unload('date_nanos'); }); - it('displays predessors - anchor - successors in right order ', async function() { + it('displays predessors - anchor - successors in right order ', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, 'AU_x3-TaGFA8no6Qj999Z'); const actualRowsText = await docTable.getRowsText(); const expectedRowsText = [ @@ -57,7 +57,7 @@ export default function({ getService, getPageObjects }) { expect(actualRowsText).to.eql(expectedRowsText); }); - it('displays correctly when predecessors and successors are loaded', async function() { + it('displays correctly when predecessors and successors are loaded', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, 'AU_x3-TaGFA8no6Qjisd'); await PageObjects.context.clickPredecessorLoadMoreButton(); await PageObjects.context.clickSuccessorLoadMoreButton(); diff --git a/test/functional/apps/context/_date_nanos_custom_timestamp.js b/test/functional/apps/context/_date_nanos_custom_timestamp.js index 7834b29931a65..dbfb77c31dff1 100644 --- a/test/functional/apps/context/_date_nanos_custom_timestamp.js +++ b/test/functional/apps/context/_date_nanos_custom_timestamp.js @@ -23,7 +23,7 @@ const TEST_INDEX_PATTERN = 'date_nanos_custom_timestamp'; const TEST_DEFAULT_CONTEXT_SIZE = 1; const TEST_STEP_SIZE = 3; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const docTable = getService('docTable'); const security = getService('security'); @@ -32,7 +32,7 @@ export default function({ getService, getPageObjects }) { // skipped due to a recent change in ES that caused search_after queries with data containing // custom timestamp formats like in the testdata to fail describe.skip('context view for date_nanos with custom timestamp', () => { - before(async function() { + before(async function () { await security.testUser.setRoles(['kibana_admin', 'kibana_date_nanos_custom']); await esArchiver.loadIfNeeded('date_nanos_custom'); await kibanaServer.uiSettings.replace({ defaultIndex: TEST_INDEX_PATTERN }); @@ -42,7 +42,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('displays predessors - anchor - successors in right order ', async function() { + it('displays predessors - anchor - successors in right order ', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, '1'); const actualRowsText = await docTable.getRowsText(); const expectedRowsText = [ @@ -53,7 +53,7 @@ export default function({ getService, getPageObjects }) { expect(actualRowsText).to.eql(expectedRowsText); }); - after(async function() { + after(async function () { await security.testUser.restoreDefaults(); await esArchiver.unload('date_nanos_custom'); }); diff --git a/test/functional/apps/context/_discover_navigation.js b/test/functional/apps/context/_discover_navigation.js index 9a0130d39bc2f..7c1494fb41ef1 100644 --- a/test/functional/apps/context/_discover_navigation.js +++ b/test/functional/apps/context/_discover_navigation.js @@ -25,7 +25,7 @@ const TEST_FILTER_COLUMN_NAMES = [ ['geo.src', 'IN'], ]; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const docTable = getService('docTable'); const filterBar = getService('filterBar'); @@ -33,11 +33,13 @@ export default function({ getService, getPageObjects }) { // FLAKY: https://github.com/elastic/kibana/issues/53308 describe.skip('context link in discover', function contextSize() { - before(async function() { + before(async function () { await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setDefaultAbsoluteRange(); await Promise.all( - TEST_COLUMN_NAMES.map(columnName => PageObjects.discover.clickFieldListItemAdd(columnName)) + TEST_COLUMN_NAMES.map((columnName) => + PageObjects.discover.clickFieldListItemAdd(columnName) + ) ); for (const [columnName, value] of TEST_FILTER_COLUMN_NAMES) { await PageObjects.discover.clickFieldListItem(columnName); @@ -45,7 +47,7 @@ export default function({ getService, getPageObjects }) { } }); - it('should open the context view with the selected document as anchor', async function() { + it('should open the context view with the selected document as anchor', async function () { // get the timestamp of the first row const firstTimestamp = (await docTable.getFields())[0][0]; @@ -60,12 +62,12 @@ export default function({ getService, getPageObjects }) { }); }); - it('should open the context view with the same columns', async function() { + it('should open the context view with the same columns', async function () { const columnNames = await docTable.getHeaderFields(); expect(columnNames).to.eql(['Time', ...TEST_COLUMN_NAMES]); }); - it('should open the context view with the filters disabled', async function() { + it('should open the context view with the filters disabled', async function () { const hasDisabledFilters = ( await Promise.all( TEST_FILTER_COLUMN_NAMES.map(([columnName, value]) => diff --git a/test/functional/apps/context/_filters.js b/test/functional/apps/context/_filters.js index 721f8a50d0e46..470ef462b9d9d 100644 --- a/test/functional/apps/context/_filters.js +++ b/test/functional/apps/context/_filters.js @@ -25,7 +25,7 @@ const TEST_ANCHOR_FILTER_FIELD = 'geo.src'; const TEST_ANCHOR_FILTER_VALUE = 'IN'; const TEST_COLUMN_NAMES = ['extension', 'geo.src']; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const docTable = getService('docTable'); const filterBar = getService('filterBar'); const retry = getService('retry'); @@ -33,13 +33,13 @@ export default function({ getService, getPageObjects }) { const PageObjects = getPageObjects(['common', 'context']); describe('context filters', function contextSize() { - beforeEach(async function() { + beforeEach(async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, TEST_ANCHOR_ID, { columns: TEST_COLUMN_NAMES, }); }); - it('inclusive filter should be addable via expanded doc table rows', async function() { + it('inclusive filter should be addable via expanded doc table rows', async function () { await docTable.toggleRowExpanded({ isAnchorRow: true }); await retry.try(async () => { @@ -51,13 +51,13 @@ export default function({ getService, getPageObjects }) { ).to.be(true); const fields = await docTable.getFields(); const hasOnlyFilteredRows = fields - .map(row => row[2]) - .every(fieldContent => fieldContent === TEST_ANCHOR_FILTER_VALUE); + .map((row) => row[2]) + .every((fieldContent) => fieldContent === TEST_ANCHOR_FILTER_VALUE); expect(hasOnlyFilteredRows).to.be(true); }); }); - it('inclusive filter should be toggleable via the filter bar', async function() { + it('inclusive filter should be toggleable via the filter bar', async function () { await filterBar.addFilter(TEST_ANCHOR_FILTER_FIELD, 'IS', TEST_ANCHOR_FILTER_VALUE); await PageObjects.context.waitUntilContextLoadingHasFinished(); // disable filter @@ -70,13 +70,13 @@ export default function({ getService, getPageObjects }) { ).to.be(true); const fields = await docTable.getFields(); const hasOnlyFilteredRows = fields - .map(row => row[2]) - .every(fieldContent => fieldContent === TEST_ANCHOR_FILTER_VALUE); + .map((row) => row[2]) + .every((fieldContent) => fieldContent === TEST_ANCHOR_FILTER_VALUE); expect(hasOnlyFilteredRows).to.be(false); }); }); - it('filter for presence should be addable via expanded doc table rows', async function() { + it('filter for presence should be addable via expanded doc table rows', async function () { await docTable.toggleRowExpanded({ isAnchorRow: true }); await retry.try(async () => { diff --git a/test/functional/apps/context/_size.js b/test/functional/apps/context/_size.js index ea9b2c8cf1819..3beb070b50deb 100644 --- a/test/functional/apps/context/_size.js +++ b/test/functional/apps/context/_size.js @@ -24,7 +24,7 @@ const TEST_ANCHOR_ID = 'AU_x3_BrGFA8no6QjjaI'; const TEST_DEFAULT_CONTEXT_SIZE = 7; const TEST_STEP_SIZE = 3; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const retry = getService('retry'); const docTable = getService('docTable'); @@ -32,26 +32,26 @@ export default function({ getService, getPageObjects }) { // FLAKY: https://github.com/elastic/kibana/issues/53888 describe.skip('context size', function contextSize() { - before(async function() { + before(async function () { await kibanaServer.uiSettings.update({ 'context:defaultSize': `${TEST_DEFAULT_CONTEXT_SIZE}`, 'context:step': `${TEST_STEP_SIZE}`, }); }); - it('should default to the `context:defaultSize` setting', async function() { + it('should default to the `context:defaultSize` setting', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, TEST_ANCHOR_ID); - await retry.try(async function() { + await retry.try(async function () { expect(await docTable.getRowsText()).to.have.length(2 * TEST_DEFAULT_CONTEXT_SIZE + 1); }); - await retry.try(async function() { + await retry.try(async function () { const predecessorCountPicker = await PageObjects.context.getPredecessorCountPicker(); expect(await predecessorCountPicker.getAttribute('value')).to.equal( `${TEST_DEFAULT_CONTEXT_SIZE}` ); }); - await retry.try(async function() { + await retry.try(async function () { const successorCountPicker = await PageObjects.context.getSuccessorCountPicker(); expect(await successorCountPicker.getAttribute('value')).to.equal( `${TEST_DEFAULT_CONTEXT_SIZE}` @@ -59,22 +59,22 @@ export default function({ getService, getPageObjects }) { }); }); - it('should increase according to the `context:step` setting when clicking the `load newer` button', async function() { + it('should increase according to the `context:step` setting when clicking the `load newer` button', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, TEST_ANCHOR_ID); await PageObjects.context.clickPredecessorLoadMoreButton(); - await retry.try(async function() { + await retry.try(async function () { expect(await docTable.getRowsText()).to.have.length( 2 * TEST_DEFAULT_CONTEXT_SIZE + TEST_STEP_SIZE + 1 ); }); }); - it('should increase according to the `context:step` setting when clicking the `load older` button', async function() { + it('should increase according to the `context:step` setting when clicking the `load older` button', async function () { await PageObjects.context.navigateTo(TEST_INDEX_PATTERN, TEST_ANCHOR_ID); await PageObjects.context.clickSuccessorLoadMoreButton(); - await retry.try(async function() { + await retry.try(async function () { expect(await docTable.getRowsText()).to.have.length( 2 * TEST_DEFAULT_CONTEXT_SIZE + TEST_STEP_SIZE + 1 ); diff --git a/test/functional/apps/context/index.js b/test/functional/apps/context/index.js index ffd7daf42c642..8e20de8c612f0 100644 --- a/test/functional/apps/context/index.js +++ b/test/functional/apps/context/index.js @@ -17,16 +17,16 @@ * under the License. */ -export default function({ getService, getPageObjects, loadTestFile }) { +export default function ({ getService, getPageObjects, loadTestFile }) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common']); const kibanaServer = getService('kibanaServer'); - describe('context app', function() { + describe('context app', function () { this.tags('ciGroup1'); - before(async function() { + before(async function () { await browser.setWindowSize(1200, 800); await esArchiver.loadIfNeeded('logstash_functional'); await esArchiver.load('visualize'); diff --git a/test/functional/apps/dashboard/bwc_shared_urls.js b/test/functional/apps/dashboard/bwc_shared_urls.js index d5c80ada53ca0..75a4ee436ee8d 100644 --- a/test/functional/apps/dashboard/bwc_shared_urls.js +++ b/test/functional/apps/dashboard/bwc_shared_urls.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['dashboard', 'header']); const dashboardExpect = getService('dashboardExpect'); const pieChart = getService('pieChart'); @@ -51,7 +51,7 @@ export default function({ getService, getPageObjects }) { `viewMode:edit)`; describe('bwc shared urls', function describeIndexTests() { - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); await PageObjects.dashboard.preserveCrossAppState(); @@ -94,7 +94,7 @@ export default function({ getService, getPageObjects }) { }); describe('6.0 urls', () => { - it('loads an unsaved dashboard', async function() { + it('loads an unsaved dashboard', async function () { const url = `${kibanaLegacyBaseUrl}#/dashboard?${urlQuery}`; log.debug(`Navigating to ${url}`); await browser.get(url, true); @@ -108,7 +108,7 @@ export default function({ getService, getPageObjects }) { await dashboardExpect.selectedLegendColorCount('#F9D9F9', 5); }); - it('loads a saved dashboard', async function() { + it('loads a saved dashboard', async function () { await PageObjects.dashboard.saveDashboard('saved with colors', { storeTimeWithDashboard: true, }); @@ -127,7 +127,7 @@ export default function({ getService, getPageObjects }) { await dashboardExpect.selectedLegendColorCount('#F9D9F9', 5); }); - it('uiState in url takes precedence over saved dashboard state', async function() { + it('uiState in url takes precedence over saved dashboard state', async function () { const id = await PageObjects.dashboard.getDashboardIdFromCurrentUrl(); const updatedQuery = urlQuery.replace(/F9D9F9/g, '000000'); const url = `${kibanaLegacyBaseUrl}#/dashboard/${id}?${updatedQuery}`; diff --git a/test/functional/apps/dashboard/create_and_add_embeddables.js b/test/functional/apps/dashboard/create_and_add_embeddables.js index 8180051f56e44..ba715f3472b98 100644 --- a/test/functional/apps/dashboard/create_and_add_embeddables.js +++ b/test/functional/apps/dashboard/create_and_add_embeddables.js @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { VisualizeConstants } from '../../../../src/plugins/visualize/public/application/visualize_constants'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const PageObjects = getPageObjects(['dashboard', 'header', 'visualize', 'settings', 'common']); const browser = getService('browser'); diff --git a/test/functional/apps/dashboard/dashboard_back_button.ts b/test/functional/apps/dashboard/dashboard_back_button.ts index 8a488c1780fcc..59947838ea736 100644 --- a/test/functional/apps/dashboard/dashboard_back_button.ts +++ b/test/functional/apps/dashboard/dashboard_back_button.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['dashboard', 'header', 'common', 'visualize', 'timePicker']); diff --git a/test/functional/apps/dashboard/dashboard_clone.js b/test/functional/apps/dashboard/dashboard_clone.js index 5d49e0cb97088..298cacef22dd5 100644 --- a/test/functional/apps/dashboard/dashboard_clone.js +++ b/test/functional/apps/dashboard/dashboard_clone.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const listingTable = getService('listingTable'); const PageObjects = getPageObjects(['dashboard', 'header', 'common']); @@ -28,11 +28,11 @@ export default function({ getService, getPageObjects }) { const dashboardName = 'Dashboard Clone Test'; const clonedDashboardName = dashboardName + ' Copy'; - before(async function() { + before(async function () { return PageObjects.dashboard.initTests(); }); - it('Clone saves a copy', async function() { + it('Clone saves a copy', async function () { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.addVisualizations( PageObjects.dashboard.getTestVisualizationNames() @@ -45,7 +45,7 @@ export default function({ getService, getPageObjects }) { await listingTable.searchAndExpectItemsCount('dashboard', clonedDashboardName, 1); }); - it('the copy should have all the same visualizations', async function() { + it('the copy should have all the same visualizations', async function () { await PageObjects.dashboard.loadSavedDashboard(clonedDashboardName); await retry.try(async () => { const panelTitles = await PageObjects.dashboard.getPanelTitles(); @@ -61,7 +61,7 @@ export default function({ getService, getPageObjects }) { expect(title).to.be(clonedDashboardName); }); - it('and warns on duplicate name', async function() { + it('and warns on duplicate name', async function () { await PageObjects.dashboard.confirmClone(); await PageObjects.dashboard.expectDuplicateTitleWarningDisplayed({ displayed: true }); }); @@ -73,7 +73,7 @@ export default function({ getService, getPageObjects }) { await listingTable.searchAndExpectItemsCount('dashboard', dashboardName, 1); }); - it('Clones on confirm duplicate title warning', async function() { + it('Clones on confirm duplicate title warning', async function () { await PageObjects.dashboard.loadSavedDashboard(dashboardName); await PageObjects.dashboard.clickClone(); diff --git a/test/functional/apps/dashboard/dashboard_filter_bar.js b/test/functional/apps/dashboard/dashboard_filter_bar.js index f6089871010c3..417b6fb066172 100644 --- a/test/functional/apps/dashboard/dashboard_filter_bar.js +++ b/test/functional/apps/dashboard/dashboard_filter_bar.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const dashboardExpect = getService('dashboardExpect'); const dashboardAddPanel = getService('dashboardAddPanel'); const testSubjects = getService('testSubjects'); @@ -39,12 +39,12 @@ export default function({ getService, getPageObjects }) { await PageObjects.common.navigateToApp('dashboard'); }); - describe('Add a filter bar', function() { + describe('Add a filter bar', function () { before(async () => { await PageObjects.dashboard.gotoDashboardLandingPage(); }); - it('should show on an empty dashboard', async function() { + it('should show on an empty dashboard', async function () { await PageObjects.dashboard.clickNewDashboard(); const hasAddFilter = await testSubjects.exists('addFilter'); expect(hasAddFilter).to.be(true); @@ -57,7 +57,7 @@ export default function({ getService, getPageObjects }) { }); }); - describe('filter editor field list', function() { + describe('filter editor field list', function () { this.tags(['skipFirefox']); before(async () => { @@ -87,7 +87,7 @@ export default function({ getService, getPageObjects }) { }); }); - describe('filter pills', function() { + describe('filter pills', function () { before(async () => { await filterBar.ensureFieldEditorModalIsClosed(); await PageObjects.dashboard.gotoDashboardLandingPage(); @@ -95,12 +95,12 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultDataRange(); }); - it('are not selected by default', async function() { + it('are not selected by default', async function () { const filterCount = await filterBar.getFilterCount(); expect(filterCount).to.equal(0); }); - it('are added when a pie chart slice is clicked', async function() { + it('are added when a pie chart slice is clicked', async function () { await dashboardAddPanel.addVisualization('Rendering Test: pie'); await PageObjects.dashboard.waitForRenderComplete(); await pieChart.filterOnPieSlice('4,886'); @@ -169,7 +169,7 @@ export default function({ getService, getPageObjects }) { }); }); - describe('saved search filtering', function() { + describe('saved search filtering', function () { before(async () => { await filterBar.ensureFieldEditorModalIsClosed(); await PageObjects.dashboard.gotoDashboardLandingPage(); @@ -177,7 +177,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultDataRange(); }); - it('are added when a cell magnifying glass is clicked', async function() { + it('are added when a cell magnifying glass is clicked', async function () { await dashboardAddPanel.addSavedSearch('Rendering-Test:-saved-search'); await PageObjects.dashboard.waitForRenderComplete(); await testSubjects.click('docTableCellFilter'); diff --git a/test/functional/apps/dashboard/dashboard_filtering.js b/test/functional/apps/dashboard/dashboard_filtering.js index 8846a753f3794..cd80f915775c9 100644 --- a/test/functional/apps/dashboard/dashboard_filtering.js +++ b/test/functional/apps/dashboard/dashboard_filtering.js @@ -23,7 +23,7 @@ import expect from '@kbn/expect'; * Test the querying capabilities of dashboard, and make sure visualizations show the expected results, especially * with nested queries and filters on the visualizations themselves. */ -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const dashboardExpect = getService('dashboardExpect'); const pieChart = getService('pieChart'); const queryBar = getService('queryBar'); @@ -37,7 +37,7 @@ export default function({ getService, getPageObjects }) { const dashboardPanelActions = getService('dashboardPanelActions'); const PageObjects = getPageObjects(['common', 'dashboard', 'header', 'visualize', 'timePicker']); - describe('dashboard filtering', function() { + describe('dashboard filtering', function () { this.tags('includeFirefox'); before(async () => { @@ -182,7 +182,7 @@ export default function({ getService, getPageObjects }) { }); }); - describe('disabling a filter unfilters the data on', function() { + describe('disabling a filter unfilters the data on', function () { // Flaky test // https://github.com/elastic/kibana/issues/41087 this.tags('skipFirefox'); diff --git a/test/functional/apps/dashboard/dashboard_grid.js b/test/functional/apps/dashboard/dashboard_grid.js index 8ba63289a9c17..44e0123c49ae2 100644 --- a/test/functional/apps/dashboard/dashboard_grid.js +++ b/test/functional/apps/dashboard/dashboard_grid.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const dashboardPanelActions = getService('dashboardPanelActions'); const PageObjects = getPageObjects(['common', 'dashboard']); - describe('dashboard grid', function() { + describe('dashboard grid', function () { before(async () => { await esArchiver.load('dashboard/current/kibana'); await kibanaServer.uiSettings.replace({ diff --git a/test/functional/apps/dashboard/dashboard_listing.js b/test/functional/apps/dashboard/dashboard_listing.js index 2ab2e107dae2d..175605bfa8253 100644 --- a/test/functional/apps/dashboard/dashboard_listing.js +++ b/test/functional/apps/dashboard/dashboard_listing.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['dashboard', 'header', 'common']); const browser = getService('browser'); const listingTable = getService('listingTable'); @@ -27,17 +27,17 @@ export default function({ getService, getPageObjects }) { describe('dashboard listing page', function describeIndexTests() { const dashboardName = 'Dashboard Listing Test'; - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); }); describe('create prompt', () => { - it('appears when there are no dashboards', async function() { + it('appears when there are no dashboards', async function () { const promptExists = await PageObjects.dashboard.getCreateDashboardPromptExists(); expect(promptExists).to.be(true); }); - it('creates a new dashboard', async function() { + it('creates a new dashboard', async function () { await PageObjects.dashboard.clickCreateDashboardPrompt(); await PageObjects.dashboard.saveDashboard(dashboardName); @@ -45,12 +45,12 @@ export default function({ getService, getPageObjects }) { await listingTable.searchAndExpectItemsCount('dashboard', dashboardName, 1); }); - it('is not shown when there is a dashboard', async function() { + it('is not shown when there is a dashboard', async function () { const promptExists = await PageObjects.dashboard.getCreateDashboardPromptExists(); expect(promptExists).to.be(false); }); - it('is not shown when there are no dashboards shown during a search', async function() { + it('is not shown when there are no dashboards shown during a search', async function () { await listingTable.searchAndExpectItemsCount('dashboard', 'gobeldeguck', 0); const promptExists = await PageObjects.dashboard.getCreateDashboardPromptExists(); @@ -58,8 +58,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('delete', function() { - it('default confirm action is cancel', async function() { + describe('delete', function () { + it('default confirm action is cancel', async function () { await listingTable.searchForItemWithName(dashboardName); await listingTable.checkListingSelectAllCheckbox(); await listingTable.clickDeleteSelected(); @@ -73,7 +73,7 @@ export default function({ getService, getPageObjects }) { await listingTable.searchAndExpectItemsCount('dashboard', dashboardName, 1); }); - it('succeeds on confirmation press', async function() { + it('succeeds on confirmation press', async function () { await listingTable.checkListingSelectAllCheckbox(); await listingTable.clickDeleteSelected(); @@ -83,7 +83,7 @@ export default function({ getService, getPageObjects }) { }); }); - describe('search', function() { + describe('search', function () { before(async () => { await listingTable.clearSearchFilter(); await PageObjects.dashboard.clickNewDashboard(); @@ -91,39 +91,39 @@ export default function({ getService, getPageObjects }) { await PageObjects.dashboard.gotoDashboardLandingPage(); }); - it('matches on the first word', async function() { + it('matches on the first word', async function () { await listingTable.searchForItemWithName('Two'); await listingTable.expectItemsCount('dashboard', 1); }); - it('matches the second word', async function() { + it('matches the second word', async function () { await listingTable.searchForItemWithName('Words'); await listingTable.expectItemsCount('dashboard', 1); }); - it('matches the second word prefix', async function() { + it('matches the second word prefix', async function () { await listingTable.searchForItemWithName('Wor'); await listingTable.expectItemsCount('dashboard', 1); }); - it('does not match mid word', async function() { + it('does not match mid word', async function () { await listingTable.searchForItemWithName('ords'); await listingTable.expectItemsCount('dashboard', 0); }); - it('is case insensitive', async function() { + it('is case insensitive', async function () { await listingTable.searchForItemWithName('two words'); await listingTable.expectItemsCount('dashboard', 1); }); - it('is using AND operator', async function() { + it('is using AND operator', async function () { await listingTable.searchForItemWithName('three words'); await listingTable.expectItemsCount('dashboard', 0); }); }); - describe('search by title', function() { - it('loads a dashboard if title matches', async function() { + describe('search by title', function () { + it('loads a dashboard if title matches', async function () { const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl + '&title=Two%20Words'; // Only works on a hard refresh. @@ -134,7 +134,7 @@ export default function({ getService, getPageObjects }) { expect(onDashboardLandingPage).to.equal(false); }); - it('title match is case insensitive', async function() { + it('title match is case insensitive', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl + '&title=two%20words'; @@ -146,7 +146,7 @@ export default function({ getService, getPageObjects }) { expect(onDashboardLandingPage).to.equal(false); }); - it('stays on listing page if title matches no dashboards', async function() { + it('stays on listing page if title matches no dashboards', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl + '&title=nodashboardsnamedme'; @@ -159,12 +159,12 @@ export default function({ getService, getPageObjects }) { expect(onDashboardLandingPage).to.equal(true); }); - it('preloads search filter bar when there is no match', async function() { + it('preloads search filter bar when there is no match', async function () { const searchFilter = await listingTable.getSearchFilterValue(); expect(searchFilter).to.equal('"nodashboardsnamedme"'); }); - it('stays on listing page if title matches two dashboards', async function() { + it('stays on listing page if title matches two dashboards', async function () { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.saveDashboard('two words', { needsConfirm: true }); await PageObjects.dashboard.gotoDashboardLandingPage(); @@ -179,12 +179,12 @@ export default function({ getService, getPageObjects }) { expect(onDashboardLandingPage).to.equal(true); }); - it('preloads search filter bar when there is more than one match', async function() { + it('preloads search filter bar when there is more than one match', async function () { const searchFilter = await listingTable.getSearchFilterValue(); expect(searchFilter).to.equal('"two words"'); }); - it('matches a title with many special characters', async function() { + it('matches a title with many special characters', async function () { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.saveDashboard('i am !@#$%^&*()_+~`,.<>{}[]; so special'); await PageObjects.dashboard.gotoDashboardLandingPage(); diff --git a/test/functional/apps/dashboard/dashboard_options.js b/test/functional/apps/dashboard/dashboard_options.js index e948e10df2376..4e7c3f4cdc79b 100644 --- a/test/functional/apps/dashboard/dashboard_options.js +++ b/test/functional/apps/dashboard/dashboard_options.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/functional/apps/dashboard/dashboard_query_bar.js b/test/functional/apps/dashboard/dashboard_query_bar.js index 13dea27f606f6..872507d00bdc4 100644 --- a/test/functional/apps/dashboard/dashboard_query_bar.js +++ b/test/functional/apps/dashboard/dashboard_query_bar.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const pieChart = getService('pieChart'); diff --git a/test/functional/apps/dashboard/dashboard_save.js b/test/functional/apps/dashboard/dashboard_save.js index d0da033788689..fe4ad83d8050e 100644 --- a/test/functional/apps/dashboard/dashboard_save.js +++ b/test/functional/apps/dashboard/dashboard_save.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getPageObjects, getService }) { +export default function ({ getPageObjects, getService }) { const PageObjects = getPageObjects(['dashboard', 'header']); const listingTable = getService('listingTable'); @@ -26,11 +26,11 @@ export default function({ getPageObjects, getService }) { const dashboardName = 'Dashboard Save Test'; const dashboardNameEnterKey = 'Dashboard Save Test with Enter Key'; - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); }); - it('warns on duplicate name for new dashboard', async function() { + it('warns on duplicate name for new dashboard', async function () { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.saveDashboard(dashboardName); @@ -44,14 +44,14 @@ export default function({ getPageObjects, getService }) { await PageObjects.dashboard.expectDuplicateTitleWarningDisplayed({ displayed: true }); }); - it('does not save on reject confirmation', async function() { + it('does not save on reject confirmation', async function () { await PageObjects.dashboard.cancelSave(); await PageObjects.dashboard.gotoDashboardLandingPage(); await listingTable.searchAndExpectItemsCount('dashboard', dashboardName, 1); }); - it('Saves on confirm duplicate title warning', async function() { + it('Saves on confirm duplicate title warning', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.enterDashboardTitleAndClickSave(dashboardName, { @@ -70,7 +70,7 @@ export default function({ getPageObjects, getService }) { await listingTable.searchAndExpectItemsCount('dashboard', dashboardName, 2); }); - it('Does not warn when you save an existing dashboard with the title it already has, and that title is a duplicate', async function() { + it('Does not warn when you save an existing dashboard with the title it already has, and that title is a duplicate', async function () { await listingTable.clickItemLink('dashboard', dashboardName); await PageObjects.header.awaitGlobalLoadingIndicatorHidden(); await PageObjects.dashboard.switchToEditMode(); @@ -79,7 +79,7 @@ export default function({ getPageObjects, getService }) { await PageObjects.dashboard.expectDuplicateTitleWarningDisplayed({ displayed: false }); }); - it('Warns you when you Save as New Dashboard, and the title is a duplicate', async function() { + it('Warns you when you Save as New Dashboard, and the title is a duplicate', async function () { await PageObjects.dashboard.switchToEditMode(); await PageObjects.dashboard.enterDashboardTitleAndClickSave(dashboardName, { saveAsNew: true, @@ -90,13 +90,13 @@ export default function({ getPageObjects, getService }) { await PageObjects.dashboard.cancelSave(); }); - it('Does not warn when only the prefix matches', async function() { + it('Does not warn when only the prefix matches', async function () { await PageObjects.dashboard.saveDashboard(dashboardName.split(' ')[0]); await PageObjects.dashboard.expectDuplicateTitleWarningDisplayed({ displayed: false }); }); - it('Warns when case is different', async function() { + it('Warns when case is different', async function () { await PageObjects.dashboard.switchToEditMode(); await PageObjects.dashboard.enterDashboardTitleAndClickSave(dashboardName.toUpperCase(), { waitDialogIsClosed: false, @@ -107,7 +107,7 @@ export default function({ getPageObjects, getService }) { await PageObjects.dashboard.cancelSave(); }); - it('Saves new Dashboard using the Enter key', async function() { + it('Saves new Dashboard using the Enter key', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.enterDashboardTitleAndPressEnter(dashboardNameEnterKey); diff --git a/test/functional/apps/dashboard/dashboard_saved_query.js b/test/functional/apps/dashboard/dashboard_saved_query.js index 99d0aed082e70..cbc9b7216c6c1 100644 --- a/test/functional/apps/dashboard/dashboard_saved_query.js +++ b/test/functional/apps/dashboard/dashboard_saved_query.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'dashboard', 'timePicker']); @@ -29,7 +29,7 @@ export default function({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); describe('dashboard saved queries', function describeIndexTests() { - before(async function() { + before(async function () { await esArchiver.load('dashboard/current/kibana'); await kibanaServer.uiSettings.replace({ defaultIndex: '0bf35f60-3dc9-11e8-8660-4d65aa086b3c', @@ -37,7 +37,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.common.navigateToApp('dashboard'); }); - describe('saved query management component functionality', function() { + describe('saved query management component functionality', function () { before(async () => { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.clickNewDashboard(); diff --git a/test/functional/apps/dashboard/dashboard_snapshots.js b/test/functional/apps/dashboard/dashboard_snapshots.js index 9f26db16f7b5e..787e839aa08a5 100644 --- a/test/functional/apps/dashboard/dashboard_snapshots.js +++ b/test/functional/apps/dashboard/dashboard_snapshots.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects, updateBaselines }) { +export default function ({ getService, getPageObjects, updateBaselines }) { const PageObjects = getPageObjects(['dashboard', 'header', 'visualize', 'common', 'timePicker']); const screenshot = getService('screenshots'); const browser = getService('browser'); @@ -29,7 +29,7 @@ export default function({ getService, getPageObjects, updateBaselines }) { const dashboardAddPanel = getService('dashboardAddPanel'); describe('dashboard snapshots', function describeIndexTests() { - before(async function() { + before(async function () { await esArchiver.load('dashboard/current/kibana'); await kibanaServer.uiSettings.replace({ defaultIndex: '0bf35f60-3dc9-11e8-8660-4d65aa086b3c', @@ -41,7 +41,7 @@ export default function({ getService, getPageObjects, updateBaselines }) { await PageObjects.common.navigateToApp('dashboard'); }); - after(async function() { + after(async function () { await browser.setWindowSize(1300, 900); }); diff --git a/test/functional/apps/dashboard/dashboard_state.js b/test/functional/apps/dashboard/dashboard_state.js index 1b0d5d42968ed..5bba2447cde28 100644 --- a/test/functional/apps/dashboard/dashboard_state.js +++ b/test/functional/apps/dashboard/dashboard_state.js @@ -23,7 +23,7 @@ import { PIE_CHART_VIS_NAME, AREA_CHART_VIS_NAME } from '../../page_objects/dash import { DEFAULT_PANEL_WIDTH } from '../../../../src/plugins/dashboard/public/application/embeddable/dashboard_constants'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects([ 'dashboard', 'visualize', @@ -43,12 +43,12 @@ export default function({ getService, getPageObjects }) { const dashboardAddPanel = getService('dashboardAddPanel'); describe('dashboard state', function describeIndexTests() { - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); await PageObjects.dashboard.preserveCrossAppState(); }); - after(async function() { + after(async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); }); @@ -175,7 +175,7 @@ export default function({ getService, getPageObjects }) { }); describe('Directly modifying url updates dashboard state', () => { - it('for query parameter', async function() { + it('for query parameter', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.clickNewDashboard(); @@ -190,7 +190,7 @@ export default function({ getService, getPageObjects }) { expect(newQuery).to.equal('hi'); }); - it('for panel size parameters', async function() { + it('for panel size parameters', async function () { await dashboardAddPanel.addVisualization(PIE_CHART_VIS_NAME); const currentUrl = await browser.getCurrentUrl(); const currentPanelDimensions = await PageObjects.dashboard.getPanelDimensions(); @@ -217,7 +217,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('when removing a panel', async function() { + it('when removing a panel', async function () { const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl.replace(/panels:\!\(.*\),query/, 'panels:!(),query'); await browser.get(newUrl.toString(), false); @@ -229,7 +229,7 @@ export default function({ getService, getPageObjects }) { }); describe('for embeddable config color parameters on a visualization', () => { - it('updates a pie slice color on a soft refresh', async function() { + it('updates a pie slice color on a soft refresh', async function () { await dashboardAddPanel.addVisualization(PIE_CHART_VIS_NAME); await PageObjects.visChart.openLegendOptionColors('80,000'); await PageObjects.visChart.selectNewLegendColorChoice('#F9D9F9'); @@ -241,7 +241,7 @@ export default function({ getService, getPageObjects }) { await retry.try(async () => { const allPieSlicesColor = await pieChart.getAllPieSliceStyles('80,000'); let whitePieSliceCounts = 0; - allPieSlicesColor.forEach(style => { + allPieSlicesColor.forEach((style) => { if (style.indexOf('rgb(255, 255, 255)') > 0) { whitePieSliceCounts++; } @@ -252,14 +252,14 @@ export default function({ getService, getPageObjects }) { }); // Unskip once https://github.com/elastic/kibana/issues/15736 is fixed. - it.skip('and updates the pie slice legend color', async function() { + it.skip('and updates the pie slice legend color', async function () { await retry.try(async () => { const colorExists = await PageObjects.visChart.doesSelectedLegendColorExist('#FFFFFF'); expect(colorExists).to.be(true); }); }); - it('resets a pie slice color to the original when removed', async function() { + it('resets a pie slice color to the original when removed', async function () { const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl.replace('vis:(colors:(%2780,000%27:%23FFFFFF))', ''); await browser.get(newUrl.toString(), false); @@ -273,7 +273,7 @@ export default function({ getService, getPageObjects }) { }); // Unskip once https://github.com/elastic/kibana/issues/15736 is fixed. - it.skip('resets the legend color as well', async function() { + it.skip('resets the legend color as well', async function () { await retry.try(async () => { const colorExists = await PageObjects.visChart.doesSelectedLegendColorExist('#57c17b'); expect(colorExists).to.be(true); diff --git a/test/functional/apps/dashboard/dashboard_time.js b/test/functional/apps/dashboard/dashboard_time.js index 20d9cc3c695a7..0420448302484 100644 --- a/test/functional/apps/dashboard/dashboard_time.js +++ b/test/functional/apps/dashboard/dashboard_time.js @@ -21,17 +21,17 @@ import expect from '@kbn/expect'; const dashboardName = 'Dashboard Test Time'; -export default function({ getPageObjects, getService }) { +export default function ({ getPageObjects, getService }) { const PageObjects = getPageObjects(['common', 'dashboard', 'header', 'timePicker']); const browser = getService('browser'); describe('dashboard time', () => { - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); await PageObjects.dashboard.preserveCrossAppState(); }); - after(async function() { + after(async function () { await PageObjects.common.navigateToApp('dashboard'); }); @@ -55,14 +55,14 @@ export default function({ getPageObjects, getService }) { }); }); - describe('dashboard with stored timed', function() { - it('is saved with time', async function() { + describe('dashboard with stored timed', function () { + it('is saved with time', async function () { await PageObjects.dashboard.switchToEditMode(); await PageObjects.timePicker.setDefaultAbsoluteRange(); await PageObjects.dashboard.saveDashboard(dashboardName, { storeTimeWithDashboard: true }); }); - it('sets time on open', async function() { + it('sets time on open', async function () { await PageObjects.timePicker.setAbsoluteRange( 'Jan 1, 2019 @ 00:00:00.000', 'Jan 2, 2019 @ 00:00:00.000' @@ -78,7 +78,7 @@ export default function({ getPageObjects, getService }) { // If time is stored with a dashboard, it's supposed to override the current time settings when opened. // However, if the URL also contains time in the global state, then the global state // time should take precedence. - it('should be overwritten by global state', async function() { + it('should be overwritten by global state', async function () { const currentUrl = await browser.getCurrentUrl(); const kibanaBaseUrl = currentUrl.substring(0, currentUrl.indexOf('#')); const id = await PageObjects.dashboard.getDashboardIdFromCurrentUrl(); @@ -92,7 +92,7 @@ export default function({ getPageObjects, getService }) { expect(time.end).to.equal('now'); }); - it('should use saved time, if time is missing in global state, but _g is present in the url', async function() { + it('should use saved time, if time is missing in global state, but _g is present in the url', async function () { const currentUrl = await browser.getCurrentUrl(); const kibanaBaseUrl = currentUrl.substring(0, currentUrl.indexOf('#')); const id = await PageObjects.dashboard.getDashboardIdFromCurrentUrl(); @@ -111,8 +111,8 @@ export default function({ getPageObjects, getService }) { // when it's opened. However, if the user then changes the time, navigates to visualize, then navigates // back to dashboard, the overridden time should be preserved. The time is *only* reset on open, not // during navigation or page refreshes. - describe('time changes', function() { - it('preserved during navigation', async function() { + describe('time changes', function () { + it('preserved during navigation', async function () { await PageObjects.dashboard.loadSavedDashboard(dashboardName); await PageObjects.timePicker.setAbsoluteRange( diff --git a/test/functional/apps/dashboard/dashboard_time_picker.js b/test/functional/apps/dashboard/dashboard_time_picker.js index 3979c233d8db2..975fb5166a8e6 100644 --- a/test/functional/apps/dashboard/dashboard_time_picker.js +++ b/test/functional/apps/dashboard/dashboard_time_picker.js @@ -20,7 +20,7 @@ import { PIE_CHART_VIS_NAME } from '../../page_objects/dashboard_page'; import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const dashboardExpect = getService('dashboardExpect'); const pieChart = getService('pieChart'); const dashboardVisualizations = getService('dashboardVisualizations'); @@ -30,7 +30,7 @@ export default function({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); describe('dashboard time picker', function describeIndexTests() { - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); await PageObjects.dashboard.preserveCrossAppState(); }); diff --git a/test/functional/apps/dashboard/data_shared_attributes.js b/test/functional/apps/dashboard/data_shared_attributes.js index dff10bdb6dbc3..2793c47fc7dba 100644 --- a/test/functional/apps/dashboard/data_shared_attributes.js +++ b/test/functional/apps/dashboard/data_shared_attributes.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -59,7 +59,7 @@ export default function({ getService, getPageObjects }) { await retry.try(async () => { const sharedData = await PageObjects.dashboard.getPanelSharedItemData(); originalPanelTitles = await PageObjects.dashboard.getPanelTitles(); - expect(sharedData.map(item => item.title)).to.eql(originalPanelTitles); + expect(sharedData.map((item) => item.title)).to.eql(originalPanelTitles); }); }); @@ -77,7 +77,7 @@ export default function({ getService, getPageObjects }) { await dashboardPanelActions.setCustomPanelTitle(CUSTOM_VIS_TITLE); await retry.try(async () => { const sharedData = await PageObjects.dashboard.getPanelSharedItemData(); - const foundSharedItemTitle = !!sharedData.find(item => { + const foundSharedItemTitle = !!sharedData.find((item) => { return item.title === CUSTOM_VIS_TITLE; }); expect(foundSharedItemTitle).to.be(true); @@ -88,7 +88,7 @@ export default function({ getService, getPageObjects }) { await dashboardPanelActions.toggleHidePanelTitle(); await retry.try(async () => { const sharedData = await PageObjects.dashboard.getPanelSharedItemData(); - const foundSharedItemTitle = !!sharedData.find(item => { + const foundSharedItemTitle = !!sharedData.find((item) => { return item.title === ''; }); expect(foundSharedItemTitle).to.be(true); @@ -100,7 +100,7 @@ export default function({ getService, getPageObjects }) { await dashboardPanelActions.resetCustomPanelTitle(); await retry.try(async () => { const sharedData = await PageObjects.dashboard.getPanelSharedItemData(); - const foundOriginalSharedItemTitle = !!sharedData.find(item => { + const foundOriginalSharedItemTitle = !!sharedData.find((item) => { return item.title === originalPanelTitles[0]; }); expect(foundOriginalSharedItemTitle).to.be(true); @@ -115,7 +115,7 @@ export default function({ getService, getPageObjects }) { ); await retry.try(async () => { const sharedData = await PageObjects.dashboard.getPanelSharedItemData(); - const foundSharedItemTitle = !!sharedData.find(item => { + const foundSharedItemTitle = !!sharedData.find((item) => { return item.title === CUSTOM_SEARCH_TITLE; }); expect(foundSharedItemTitle).to.be(true); diff --git a/test/functional/apps/dashboard/edit_embeddable_redirects.js b/test/functional/apps/dashboard/edit_embeddable_redirects.js index b45dcc2cedf9b..a366e34b121d9 100644 --- a/test/functional/apps/dashboard/edit_embeddable_redirects.js +++ b/test/functional/apps/dashboard/edit_embeddable_redirects.js @@ -18,7 +18,7 @@ */ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['dashboard', 'header', 'visualize', 'settings', 'common']); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/functional/apps/dashboard/embed_mode.js b/test/functional/apps/dashboard/embed_mode.js index f769498f4d232..65ef75f3f65e1 100644 --- a/test/functional/apps/dashboard/embed_mode.js +++ b/test/functional/apps/dashboard/embed_mode.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -54,7 +54,7 @@ export default function({ getService, getPageObjects }) { }); }); - after(async function() { + after(async function () { const currentUrl = await browser.getCurrentUrl(); const newUrl = currentUrl.replace('&embed=true', ''); // First use the timestamp to cause a hard refresh so the new embed parameter works correctly. diff --git a/test/functional/apps/dashboard/embeddable_rendering.js b/test/functional/apps/dashboard/embeddable_rendering.js index 2ef66f2a36fbc..9ba0c07c744fc 100644 --- a/test/functional/apps/dashboard/embeddable_rendering.js +++ b/test/functional/apps/dashboard/embeddable_rendering.js @@ -27,7 +27,7 @@ import expect from '@kbn/expect'; * broke?). The upside is that this offers very good coverage with a minimal time investment. */ -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const find = getService('find'); const browser = getService('browser'); const esArchiver = getService('esArchiver'); diff --git a/test/functional/apps/dashboard/empty_dashboard.js b/test/functional/apps/dashboard/empty_dashboard.js index c91b7bd1ecee0..e7ebbcf09e828 100644 --- a/test/functional/apps/dashboard/empty_dashboard.js +++ b/test/functional/apps/dashboard/empty_dashboard.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/functional/apps/dashboard/full_screen_mode.js b/test/functional/apps/dashboard/full_screen_mode.js index 17eb6d8f08a9c..c0a2d49b1c202 100644 --- a/test/functional/apps/dashboard/full_screen_mode.js +++ b/test/functional/apps/dashboard/full_screen_mode.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/functional/apps/dashboard/index.js b/test/functional/apps/dashboard/index.js index 3b81a4d974bec..9ae1a2afddcc6 100644 --- a/test/functional/apps/dashboard/index.js +++ b/test/functional/apps/dashboard/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); @@ -40,10 +40,10 @@ export default function({ getService, loadTestFile }) { await esArchiver.unload('logstash_functional'); } - describe('dashboard app', function() { + describe('dashboard app', function () { // This has to be first since the other tests create some embeddables as side affects and our counting assumes // a fresh index. - describe('using current data', function() { + describe('using current data', function () { this.tags('ciGroup2'); before(loadCurrentData); after(unloadCurrentData); @@ -64,7 +64,7 @@ export default function({ getService, loadTestFile }) { loadTestFile(require.resolve('./dashboard_query_bar')); }); - describe('using current data', function() { + describe('using current data', function () { this.tags('ciGroup3'); before(loadCurrentData); after(unloadCurrentData); @@ -86,7 +86,7 @@ export default function({ getService, loadTestFile }) { // Each of these tests call initTests themselves, the way it was originally written. The above tests only load // the data once to save on time. Eventually, all of these tests should just use current data and we can reserve // legacy data only for specifically testing BWC situations. - describe('using legacy data', function() { + describe('using legacy data', function () { this.tags('ciGroup4'); before(loadLogstash); after(unloadLogstash); @@ -97,7 +97,7 @@ export default function({ getService, loadTestFile }) { loadTestFile(require.resolve('./dashboard_state')); }); - describe('using legacy data', function() { + describe('using legacy data', function () { this.tags('ciGroup5'); before(loadLogstash); after(unloadLogstash); diff --git a/test/functional/apps/dashboard/panel_controls.js b/test/functional/apps/dashboard/panel_controls.js index 279adb22a1cfa..748e9fdc5f19d 100644 --- a/test/functional/apps/dashboard/panel_controls.js +++ b/test/functional/apps/dashboard/panel_controls.js @@ -26,7 +26,7 @@ import { } from '../../page_objects/dashboard_page'; import { VisualizeConstants } from '../../../../src/plugins/visualize/public/application/visualize_constants'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const dashboardPanelActions = getService('dashboardPanelActions'); const dashboardAddPanel = getService('dashboardAddPanel'); @@ -43,12 +43,12 @@ export default function({ getService, getPageObjects }) { const dashboardName = 'Dashboard Panel Controls Test'; describe('dashboard panel controls', function viewEditModeTests() { - before(async function() { + before(async function () { await PageObjects.dashboard.initTests(); await PageObjects.dashboard.preserveCrossAppState(); }); - after(async function() { + after(async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); }); @@ -62,7 +62,7 @@ export default function({ getService, getPageObjects }) { intialDimensions = await PageObjects.dashboard.getPanelDimensions(); }); - after(async function() { + after(async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); }); @@ -111,14 +111,14 @@ export default function({ getService, getPageObjects }) { }); }); - describe('panel cloning', function() { + describe('panel cloning', function () { before(async () => { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.timePicker.setHistoricalDataRange(); await dashboardAddPanel.addVisualization(PIE_CHART_VIS_NAME); }); - after(async function() { + after(async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); }); @@ -155,14 +155,14 @@ export default function({ getService, getPageObjects }) { }); }); - describe('panel edit controls', function() { + describe('panel edit controls', function () { before(async () => { await PageObjects.dashboard.clickNewDashboard(); await PageObjects.timePicker.setHistoricalDataRange(); await dashboardAddPanel.addVisualization(PIE_CHART_VIS_NAME); }); - it('are hidden in view mode', async function() { + it('are hidden in view mode', async function () { await PageObjects.dashboard.saveDashboard(dashboardName); await dashboardPanelActions.openContextMenu(); @@ -170,7 +170,7 @@ export default function({ getService, getPageObjects }) { await dashboardPanelActions.expectMissingRemovePanelAction(); }); - it('are shown in edit mode', async function() { + it('are shown in edit mode', async function () { await PageObjects.dashboard.switchToEditMode(); const isContextMenuIconVisible = await dashboardPanelActions.isContextMenuIconVisible(); @@ -201,8 +201,8 @@ export default function({ getService, getPageObjects }) { await browser.get(currentUrl.toString(), false); }); - describe('on an expanded panel', function() { - it('are hidden in view mode', async function() { + describe('on an expanded panel', function () { + it('are hidden in view mode', async function () { await renderable.waitForRender(); await PageObjects.dashboard.saveDashboard(dashboardName); await dashboardPanelActions.openContextMenu(); @@ -214,7 +214,7 @@ export default function({ getService, getPageObjects }) { await dashboardPanelActions.expectMissingRemovePanelAction(); }); - it('in edit mode hides remove icons ', async function() { + it('in edit mode hides remove icons ', async function () { await PageObjects.dashboard.switchToEditMode(); await dashboardPanelActions.openContextMenu(); await dashboardPanelActions.expectExistsEditPanelAction(); @@ -282,8 +282,8 @@ export default function({ getService, getPageObjects }) { }); // Panel expand should also be shown in view mode, but only on mouse hover. - describe('panel expand control', function() { - it('shown in edit mode', async function() { + describe('panel expand control', function () { + it('shown in edit mode', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); await dashboardPanelActions.openContextMenu(); await dashboardPanelActions.expectExistsToggleExpandAction(); diff --git a/test/functional/apps/dashboard/panel_expand_toggle.js b/test/functional/apps/dashboard/panel_expand_toggle.js index 5e7d55706968d..e3343f29922e2 100644 --- a/test/functional/apps/dashboard/panel_expand_toggle.js +++ b/test/functional/apps/dashboard/panel_expand_toggle.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); diff --git a/test/functional/apps/dashboard/time_zones.js b/test/functional/apps/dashboard/time_zones.js index 564eb790eb8d1..b0344a8b69064 100644 --- a/test/functional/apps/dashboard/time_zones.js +++ b/test/functional/apps/dashboard/time_zones.js @@ -20,13 +20,13 @@ import path from 'path'; import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const pieChart = getService('pieChart'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['dashboard', 'timePicker', 'settings', 'common']); - describe('dashboard time zones', function() { + describe('dashboard time zones', function () { this.tags('includeFirefox'); before(async () => { diff --git a/test/functional/apps/dashboard/view_edit.js b/test/functional/apps/dashboard/view_edit.js index c8eb10d43ea83..589a46b7e9d08 100644 --- a/test/functional/apps/dashboard/view_edit.js +++ b/test/functional/apps/dashboard/view_edit.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const queryBar = getService('queryBar'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -38,13 +38,13 @@ export default function({ getService, getPageObjects }) { await PageObjects.dashboard.preserveCrossAppState(); }); - it('create new dashboard opens in edit mode', async function() { + it('create new dashboard opens in edit mode', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.clickNewDashboard(); await PageObjects.dashboard.clickCancelOutOfEditMode(); }); - it('existing dashboard opens in view mode', async function() { + it('existing dashboard opens in view mode', async function () { await PageObjects.dashboard.gotoDashboardLandingPage(); await PageObjects.dashboard.loadSavedDashboard(dashboardName); const inViewMode = await PageObjects.dashboard.getIsInViewMode(); @@ -52,8 +52,8 @@ export default function({ getService, getPageObjects }) { expect(inViewMode).to.equal(true); }); - describe('save', function() { - it('auto exits out of edit mode', async function() { + describe('save', function () { + it('auto exits out of edit mode', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); await PageObjects.dashboard.saveDashboard(dashboardName); const isViewMode = await PageObjects.dashboard.getIsInViewMode(); @@ -61,13 +61,13 @@ export default function({ getService, getPageObjects }) { }); }); - describe('shows lose changes warning', function() { - describe('and loses changes on confirmation', function() { - beforeEach(async function() { + describe('shows lose changes warning', function () { + describe('and loses changes on confirmation', function () { + beforeEach(async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); }); - it('when time changed is stored with dashboard', async function() { + it('when time changed is stored with dashboard', async function () { await PageObjects.timePicker.setDefaultDataRange(); const originalTime = await PageObjects.timePicker.getTimeConfig(); @@ -92,7 +92,7 @@ export default function({ getService, getPageObjects }) { expect(newTime.end).to.equal(originalTime.end); }); - it('when the query is edited and applied', async function() { + it('when the query is edited and applied', async function () { const originalQuery = await queryBar.getQueryString(); await queryBar.setQuery(`${originalQuery}and extra stuff`); await queryBar.submitQuery(); @@ -106,7 +106,7 @@ export default function({ getService, getPageObjects }) { expect(query).to.equal(originalQuery); }); - it('when a filter is deleted', async function() { + it('when a filter is deleted', async function () { // This may seem like a pointless line but there was a bug that only arose when the dashboard // was loaded initially await PageObjects.dashboard.loadSavedDashboard(dashboardName); @@ -129,7 +129,7 @@ export default function({ getService, getPageObjects }) { expect(hasFilter).to.be(true); }); - it('when a new vis is added', async function() { + it('when a new vis is added', async function () { const originalPanelCount = await PageObjects.dashboard.getPanelCount(); await dashboardAddPanel.ensureAddPanelIsShowing(); @@ -152,7 +152,7 @@ export default function({ getService, getPageObjects }) { expect(panelCount).to.eql(originalPanelCount); }); - it('when an existing vis is added', async function() { + it('when an existing vis is added', async function () { const originalPanelCount = await PageObjects.dashboard.getPanelCount(); await dashboardAddPanel.addVisualization('new viz panel'); @@ -166,8 +166,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('and preserves edits on cancel', function() { - it('when time changed is stored with dashboard', async function() { + describe('and preserves edits on cancel', function () { + it('when time changed is stored with dashboard', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); await PageObjects.timePicker.setAbsoluteRange( 'Sep 19, 2013 @ 06:31:44.000', @@ -196,8 +196,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('and preserves edits on cancel', function() { - it('when time changed is stored with dashboard', async function() { + describe('and preserves edits on cancel', function () { + it('when time changed is stored with dashboard', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); await PageObjects.timePicker.setDefaultDataRange(); await PageObjects.dashboard.saveDashboard(dashboardName, true); @@ -222,8 +222,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('Does not show lose changes warning', function() { - it('when time changed is not stored with dashboard', async function() { + describe('Does not show lose changes warning', function () { + it('when time changed is not stored with dashboard', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); await PageObjects.dashboard.saveDashboard(dashboardName, { storeTimeWithDashboard: false }); await PageObjects.dashboard.switchToEditMode(); @@ -237,7 +237,7 @@ export default function({ getService, getPageObjects }) { }); // See https://github.com/elastic/kibana/issues/10110 - this is intentional. - it('when the query is edited but not applied', async function() { + it('when the query is edited but not applied', async function () { await PageObjects.dashboard.gotoDashboardEditMode(dashboardName); const originalQuery = await queryBar.getQueryString(); diff --git a/test/functional/apps/discover/_date_nanos.js b/test/functional/apps/discover/_date_nanos.js index 99a37cc18feaa..1b5c033d67a43 100644 --- a/test/functional/apps/discover/_date_nanos.js +++ b/test/functional/apps/discover/_date_nanos.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common', 'timePicker', 'discover']); const kibanaServer = getService('kibanaServer'); @@ -27,8 +27,8 @@ export default function({ getService, getPageObjects }) { const fromTime = 'Sep 22, 2019 @ 20:31:44.000'; const toTime = 'Sep 23, 2019 @ 03:31:44.000'; - describe('date_nanos', function() { - before(async function() { + describe('date_nanos', function () { + before(async function () { await esArchiver.loadIfNeeded('date_nanos'); await kibanaServer.uiSettings.replace({ defaultIndex: 'date-nanos' }); await security.testUser.setRoles(['kibana_admin', 'kibana_date_nanos']); @@ -41,7 +41,7 @@ export default function({ getService, getPageObjects }) { await esArchiver.unload('date_nanos'); }); - it('should show a timestamp with nanoseconds in the first result row', async function() { + it('should show a timestamp with nanoseconds in the first result row', async function () { const time = await PageObjects.timePicker.getTimeConfig(); expect(time.start).to.be(fromTime); expect(time.end).to.be(toTime); diff --git a/test/functional/apps/discover/_date_nanos_mixed.js b/test/functional/apps/discover/_date_nanos_mixed.js index b88ae87601cc5..63509d85afd3a 100644 --- a/test/functional/apps/discover/_date_nanos_mixed.js +++ b/test/functional/apps/discover/_date_nanos_mixed.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common', 'timePicker', 'discover']); const kibanaServer = getService('kibanaServer'); @@ -27,8 +27,8 @@ export default function({ getService, getPageObjects }) { const fromTime = 'Jan 1, 2019 @ 00:00:00.000'; const toTime = 'Jan 1, 2019 @ 23:59:59.999'; - describe('date_nanos_mixed', function() { - before(async function() { + describe('date_nanos_mixed', function () { + before(async function () { await esArchiver.loadIfNeeded('date_nanos_mixed'); await kibanaServer.uiSettings.replace({ defaultIndex: 'timestamp-*' }); await security.testUser.setRoles(['kibana_admin', 'kibana_date_nanos_mixed']); @@ -41,7 +41,7 @@ export default function({ getService, getPageObjects }) { esArchiver.unload('date_nanos_mixed'); }); - it('shows a list of records of indices with date & date_nanos fields in the right order', async function() { + it('shows a list of records of indices with date & date_nanos fields in the right order', async function () { const rowData1 = await PageObjects.discover.getDocTableIndex(1); expect(rowData1.startsWith('Jan 1, 2019 @ 12:10:30.124000000')).to.be.ok(); const rowData2 = await PageObjects.discover.getDocTableIndex(3); diff --git a/test/functional/apps/discover/_discover.js b/test/functional/apps/discover/_discover.js index cca562d7f2fcd..163022e32c82f 100644 --- a/test/functional/apps/discover/_discover.js +++ b/test/functional/apps/discover/_discover.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const esArchiver = getService('esArchiver'); @@ -31,7 +31,7 @@ export default function({ getService, getPageObjects }) { }; describe('discover test', function describeIndexTests() { - before(async function() { + before(async function () { log.debug('load kibana index with default index pattern'); await esArchiver.load('discover'); @@ -43,10 +43,10 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - describe('query', function() { + describe('query', function () { const queryName1 = 'Query # 1'; - it('should show correct time range string by timepicker', async function() { + it('should show correct time range string by timepicker', async function () { const time = await PageObjects.timePicker.getTimeConfig(); expect(time.start).to.be(PageObjects.timePicker.defaultStartTime); expect(time.end).to.be(PageObjects.timePicker.defaultEndTime); @@ -55,34 +55,34 @@ export default function({ getService, getPageObjects }) { expect(rowData.startsWith('Sep 22, 2015 @ 23:50:13.253')).to.be.ok(); }); - it('save query should show toast message and display query name', async function() { + it('save query should show toast message and display query name', async function () { await PageObjects.discover.saveSearch(queryName1); const actualQueryNameString = await PageObjects.discover.getCurrentQueryName(); expect(actualQueryNameString).to.be(queryName1); }); - it('load query should show query name', async function() { + it('load query should show query name', async function () { await PageObjects.discover.loadSavedSearch(queryName1); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getCurrentQueryName()).to.be(queryName1); }); }); - it('should show the correct hit count', async function() { + it('should show the correct hit count', async function () { const expectedHitCount = '14,004'; - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be(expectedHitCount); }); }); - it('should show correct time range string in chart', async function() { + it('should show correct time range string in chart', async function () { const actualTimeString = await PageObjects.discover.getChartTimespan(); const expectedTimeString = `${PageObjects.timePicker.defaultStartTime} - ${PageObjects.timePicker.defaultEndTime}`; expect(actualTimeString).to.be(expectedTimeString); }); - it('should modify the time range when a bar is clicked', async function() { + it('should modify the time range when a bar is clicked', async function () { await PageObjects.timePicker.setDefaultAbsoluteRange(); await PageObjects.discover.clickHistogramBar(); const time = await PageObjects.timePicker.getTimeConfig(); @@ -92,7 +92,7 @@ export default function({ getService, getPageObjects }) { expect(rowData).to.have.string('Sep 21, 2015 @ 11:59:22.316'); }); - it('should modify the time range when the histogram is brushed', async function() { + it('should modify the time range when the histogram is brushed', async function () { await PageObjects.timePicker.setDefaultAbsoluteRange(); await PageObjects.discover.brushHistogram(); @@ -106,7 +106,7 @@ export default function({ getService, getPageObjects }) { ); }); - it('should show correct initial chart interval of Auto', async function() { + it('should show correct initial chart interval of Auto', async function () { await PageObjects.timePicker.setDefaultAbsoluteRange(); await PageObjects.discover.waitUntilSearchingHasFinished(); const actualInterval = await PageObjects.discover.getChartInterval(); @@ -115,7 +115,7 @@ export default function({ getService, getPageObjects }) { expect(actualInterval).to.be(expectedInterval); }); - it('should show Auto chart interval', async function() { + it('should show Auto chart interval', async function () { const expectedChartInterval = 'Auto'; const actualInterval = await PageObjects.discover.getChartInterval(); @@ -127,18 +127,18 @@ export default function({ getService, getPageObjects }) { expect(isVisible).to.be(false); }); - it('should reload the saved search with persisted query to show the initial hit count', async function() { + it('should reload the saved search with persisted query to show the initial hit count', async function () { // apply query some changes await queryBar.setQuery('test'); await queryBar.submitQuery(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('22'); }); // reset to persisted state await PageObjects.discover.clickResetSavedSearchButton(); const expectedHitCount = '14,004'; - await retry.try(async function() { + await retry.try(async function () { expect(await queryBar.getQueryString()).to.be(''); expect(await PageObjects.discover.getHitCount()).to.be(expectedHitCount); }); @@ -173,16 +173,16 @@ export default function({ getService, getPageObjects }) { await PageObjects.discover.waitUntilSearchingHasFinished(); }); - it('should support querying on nested fields', async function() { + it('should support querying on nested fields', async function () { await queryBar.setQuery('nestedField:{ child: nestedValue }'); await queryBar.submitQuery(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('1'); }); }); }); - describe('data-shared-item', function() { + describe('data-shared-item', function () { it('should have correct data-shared-item title and description', async () => { const expected = { title: 'A Saved Search', @@ -202,7 +202,7 @@ export default function({ getService, getPageObjects }) { }); describe('time zone switch', () => { - it('should show bars in the correct time zone after switching', async function() { + it('should show bars in the correct time zone after switching', async function () { await kibanaServer.uiSettings.replace({ 'dateFormat:tz': 'America/Phoenix' }); await PageObjects.common.navigateToApp('discover'); await PageObjects.header.awaitKibanaChrome(); @@ -217,7 +217,7 @@ export default function({ getService, getPageObjects }) { }); }); describe('usage of discover:searchOnPageLoad', () => { - it('should fetch data from ES initially when discover:searchOnPageLoad is false', async function() { + it('should fetch data from ES initially when discover:searchOnPageLoad is false', async function () { await kibanaServer.uiSettings.replace({ 'discover:searchOnPageLoad': false }); await PageObjects.common.navigateToApp('discover'); await PageObjects.header.awaitKibanaChrome(); @@ -225,7 +225,7 @@ export default function({ getService, getPageObjects }) { expect(await PageObjects.discover.getNrOfFetches()).to.be(0); }); - it('should not fetch data from ES initially when discover:searchOnPageLoad is true', async function() { + it('should not fetch data from ES initially when discover:searchOnPageLoad is true', async function () { await kibanaServer.uiSettings.replace({ 'discover:searchOnPageLoad': true }); await PageObjects.common.navigateToApp('discover'); await PageObjects.header.awaitKibanaChrome(); diff --git a/test/functional/apps/discover/_discover_histogram.js b/test/functional/apps/discover/_discover_histogram.js index 6f6dfa66f825f..e53c953f1514e 100644 --- a/test/functional/apps/discover/_discover_histogram.js +++ b/test/functional/apps/discover/_discover_histogram.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const esArchiver = getService('esArchiver'); const browser = getService('browser'); @@ -33,7 +33,7 @@ export default function({ getService, getPageObjects }) { }; describe('discover histogram', function describeIndexTests() { - before(async function() { + before(async function () { log.debug('load kibana index with default index pattern'); await PageObjects.common.navigateToApp('settings'); await security.testUser.setRoles([ diff --git a/test/functional/apps/discover/_doc_navigation.js b/test/functional/apps/discover/_doc_navigation.js index a1e845d4ce675..f6a092ecb79a8 100644 --- a/test/functional/apps/discover/_doc_navigation.js +++ b/test/functional/apps/discover/_doc_navigation.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const docTable = getService('docTable'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common', 'discover', 'timePicker']); @@ -27,14 +27,14 @@ export default function({ getService, getPageObjects }) { const retry = getService('retry'); describe('doc link in discover', function contextSize() { - before(async function() { + before(async function () { await esArchiver.loadIfNeeded('logstash_functional'); await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setDefaultAbsoluteRange(); await PageObjects.discover.waitForDocTableLoadingComplete(); }); - it('should open the doc view of the selected document', async function() { + it('should open the doc view of the selected document', async function () { // navigate to the doc view await docTable.clickRowToggle({ rowIndex: 0 }); diff --git a/test/functional/apps/discover/_errors.js b/test/functional/apps/discover/_errors.js index 9a7356d8e521a..5113fc8568d52 100644 --- a/test/functional/apps/discover/_errors.js +++ b/test/functional/apps/discover/_errors.js @@ -19,19 +19,19 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common', 'discover']); describe('errors', function describeIndexTests() { - before(async function() { + before(async function () { await esArchiver.loadIfNeeded('logstash_functional'); await esArchiver.load('invalid_scripted_field'); await PageObjects.common.navigateToApp('discover'); }); - after(async function() { + after(async function () { await esArchiver.unload('invalid_scripted_field'); }); diff --git a/test/functional/apps/discover/_field_data.js b/test/functional/apps/discover/_field_data.js index ace9710665f10..f0472fb5a3da5 100644 --- a/test/functional/apps/discover/_field_data.js +++ b/test/functional/apps/discover/_field_data.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -29,7 +29,7 @@ export default function({ getService, getPageObjects }) { describe('discover tab', function describeIndexTests() { this.tags('includeFirefox'); - before(async function() { + before(async function () { await esArchiver.loadIfNeeded('logstash_functional'); await esArchiver.load('discover'); // delete .kibana index and update configDoc @@ -41,10 +41,10 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - describe('field data', function() { - it('search php should show the correct hit count', async function() { + describe('field data', function () { + it('search php should show the correct hit count', async function () { const expectedHitCount = '445'; - await retry.try(async function() { + await retry.try(async function () { await queryBar.setQuery('php'); await queryBar.submitQuery(); const hitCount = await PageObjects.discover.getHitCount(); @@ -52,14 +52,14 @@ export default function({ getService, getPageObjects }) { }); }); - it('the search term should be highlighted in the field data', async function() { + it('the search term should be highlighted in the field data', async function () { // marks is the style that highlights the text in yellow const marks = await PageObjects.discover.getMarks(); expect(marks.length).to.be(50); expect(marks.indexOf('php')).to.be(0); }); - it('search type:apache should show the correct hit count', async function() { + it('search type:apache should show the correct hit count', async function () { const expectedHitCount = '11,156'; await queryBar.setQuery('type:apache'); await queryBar.submitQuery(); @@ -69,13 +69,13 @@ export default function({ getService, getPageObjects }) { }); }); - it('doc view should show Time and _source columns', async function() { + it('doc view should show Time and _source columns', async function () { const expectedHeader = 'Time _source'; const Docheader = await PageObjects.discover.getDocHeader(); expect(Docheader).to.be(expectedHeader); }); - it('doc view should sort ascending', async function() { + it('doc view should sort ascending', async function () { const expectedTimeStamp = 'Sep 20, 2015 @ 00:00:00.000'; await PageObjects.discover.clickDocSortDown(); @@ -90,7 +90,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('a bad syntax query should show an error message', async function() { + it('a bad syntax query should show an error message', async function () { const expectedError = 'Expected ":", "<", "<=", ">", ">=", AND, OR, end of input, ' + 'whitespace but "(" found.'; diff --git a/test/functional/apps/discover/_field_visualize.ts b/test/functional/apps/discover/_field_visualize.ts index f8f290b259b7e..e202dcb7e2af7 100644 --- a/test/functional/apps/discover/_field_visualize.ts +++ b/test/functional/apps/discover/_field_visualize.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const filterBar = getService('filterBar'); const inspector = getService('inspector'); @@ -33,7 +33,7 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { }; describe('discover field visualize button', () => { - before(async function() { + before(async function () { log.debug('load kibana index with default index pattern'); await esArchiver.load('discover'); diff --git a/test/functional/apps/discover/_filter_editor.js b/test/functional/apps/discover/_filter_editor.js index 372f1a5bf3d27..afb59481b23e2 100644 --- a/test/functional/apps/discover/_filter_editor.js +++ b/test/functional/apps/discover/_filter_editor.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const esArchiver = getService('esArchiver'); @@ -31,7 +31,7 @@ export default function({ getService, getPageObjects }) { }; describe('discover filter editor', function describeIndexTests() { - before(async function() { + before(async function () { log.debug('load kibana index with default index pattern'); await esArchiver.loadIfNeeded('discover'); @@ -43,13 +43,13 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - describe('filter editor', function() { - it('should add a phrases filter', async function() { + describe('filter editor', function () { + it('should add a phrases filter', async function () { await filterBar.addFilter('extension.raw', 'is one of', 'jpg'); expect(await filterBar.hasFilter('extension.raw', 'jpg')).to.be(true); }); - it('should show the phrases if you re-open a phrases filter', async function() { + it('should show the phrases if you re-open a phrases filter', async function () { await filterBar.clickEditFilter('extension.raw', 'jpg'); const phrases = await filterBar.getFilterEditorSelectedPhrases(); expect(phrases.length).to.be(1); @@ -60,7 +60,7 @@ export default function({ getService, getPageObjects }) { it('should support filtering on nested fields', async () => { await filterBar.addFilter('nestedField.child', 'is', 'nestedValue'); expect(await filterBar.hasFilter('nestedField.child', 'nestedValue')).to.be(true); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('1'); }); }); diff --git a/test/functional/apps/discover/_indexpattern_without_timefield.ts b/test/functional/apps/discover/_indexpattern_without_timefield.ts index 87a2da7e44a5e..92710548ecb30 100644 --- a/test/functional/apps/discover/_indexpattern_without_timefield.ts +++ b/test/functional/apps/discover/_indexpattern_without_timefield.ts @@ -20,16 +20,16 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common', 'timePicker', 'discover']); - describe('indexpattern without timefield', function() { - before(async function() { + describe('indexpattern without timefield', function () { + before(async function () { await esArchiver.loadIfNeeded('index_pattern_without_timefield'); }); - beforeEach(async function() { + beforeEach(async function () { await PageObjects.common.navigateToApp('discover'); await PageObjects.discover.selectIndexPattern('without-timefield'); }); @@ -38,12 +38,12 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { await esArchiver.unload('index_pattern_without_timefield'); }); - it('should not display a timepicker', async function() { + it('should not display a timepicker', async function () { const timepickerExists = await PageObjects.timePicker.timePickerExists(); expect(timepickerExists).to.be(false); }); - it('should display a timepicker after switching to an index pattern with timefield', async function() { + it('should display a timepicker after switching to an index pattern with timefield', async function () { expect(await PageObjects.timePicker.timePickerExists()).to.be(false); await PageObjects.discover.selectIndexPattern('with-timefield'); expect(await PageObjects.timePicker.timePickerExists()).to.be(true); diff --git a/test/functional/apps/discover/_inspector.js b/test/functional/apps/discover/_inspector.js index b35c6780e2ae9..900ad28e14e69 100644 --- a/test/functional/apps/discover/_inspector.js +++ b/test/functional/apps/discover/_inspector.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['common', 'visualize', 'timePicker']); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -28,7 +28,7 @@ export default function({ getService, getPageObjects }) { const STATS_ROW_NAME_INDEX = 0; const STATS_ROW_VALUE_INDEX = 1; function getHitCount(requestStats) { - const hitsCountStatsRow = requestStats.find(statsRow => { + const hitsCountStatsRow = requestStats.find((statsRow) => { return statsRow[STATS_ROW_NAME_INDEX] === 'Hits (total)'; }); return hitsCountStatsRow[STATS_ROW_VALUE_INDEX]; diff --git a/test/functional/apps/discover/_large_string.js b/test/functional/apps/discover/_large_string.js index 5e9048e2bc481..6142f042c1148 100644 --- a/test/functional/apps/discover/_large_string.js +++ b/test/functional/apps/discover/_large_string.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const log = getService('log'); const retry = getService('retry'); @@ -28,15 +28,15 @@ export default function({ getService, getPageObjects }) { const security = getService('security'); const PageObjects = getPageObjects(['common', 'home', 'settings', 'discover']); - describe('test large strings', function() { - before(async function() { + describe('test large strings', function () { + before(async function () { await security.testUser.setRoles(['kibana_admin', 'kibana_large_strings']); await esArchiver.load('empty_kibana'); await esArchiver.loadIfNeeded('hamlet'); await kibanaServer.uiSettings.replace({ defaultIndex: 'testlargestring' }); }); - it('verify the large string book present', async function() { + it('verify the large string book present', async function () { const ExpectedDoc = 'mybook:Project Gutenberg EBook of Hamlet, by William Shakespeare' + ' This eBook is for the use of anyone anywhere in the United States' + @@ -58,8 +58,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('test large data', function() { - it('search Newsletter should show the correct hit count', async function() { + describe('test large data', function () { + it('search Newsletter should show the correct hit count', async function () { const expectedHitCount = '1'; await queryBar.setQuery('Newsletter'); await queryBar.submitQuery(); @@ -70,7 +70,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('the search term Newsletter should be highlighted in the field data', async function() { + it('the search term Newsletter should be highlighted in the field data', async function () { // marks is the style that highlights the text in yellow const marks = await PageObjects.discover.getMarks(); expect(marks.length).to.be(1); diff --git a/test/functional/apps/discover/_saved_queries.js b/test/functional/apps/discover/_saved_queries.js index 9b50eeda20073..61bb5f7cfee6f 100644 --- a/test/functional/apps/discover/_saved_queries.js +++ b/test/functional/apps/discover/_saved_queries.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -35,7 +35,7 @@ export default function({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); describe('saved queries saved objects', function describeIndexTests() { - before(async function() { + before(async function () { log.debug('load kibana index with default index pattern'); await esArchiver.load('discover'); @@ -47,8 +47,8 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - describe('saved query management component functionality', function() { - before(async function() { + describe('saved query management component functionality', function () { + before(async function () { // set up a query with filters and a time filter log.debug('set up a query with filters to save'); await queryBar.setQuery('response:200'); diff --git a/test/functional/apps/discover/_shared_links.js b/test/functional/apps/discover/_shared_links.js index 8f42633339e48..38d8812fa3103 100644 --- a/test/functional/apps/discover/_shared_links.js +++ b/test/functional/apps/discover/_shared_links.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const log = getService('log'); const esArchiver = getService('esArchiver'); @@ -71,16 +71,16 @@ export default function({ getService, getPageObjects }) { describe('shared links with state in query', async () => { let teardown; - before(async function() { + before(async function () { teardown = await setup({ storeStateInSessionStorage: false }); }); - after(async function() { + after(async function () { await teardown(); }); - describe('permalink', function() { - it('should allow for copying the snapshot URL', async function() { + describe('permalink', function () { + it('should allow for copying the snapshot URL', async function () { const expectedUrl = baseUrl + '/app/discover?_t=1453775307251#' + @@ -96,7 +96,7 @@ export default function({ getService, getPageObjects }) { ); }); - it('should allow for copying the snapshot URL as a short URL', async function() { + it('should allow for copying the snapshot URL as a short URL', async function () { const re = new RegExp(baseUrl + '/goto/[0-9a-f]{32}$'); await PageObjects.share.checkShortenUrl(); await retry.try(async () => { @@ -105,7 +105,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should allow for copying the saved object URL', async function() { + it('should allow for copying the saved object URL', async function () { const expectedUrl = baseUrl + '/app/discover#' + @@ -124,16 +124,16 @@ export default function({ getService, getPageObjects }) { describe('shared links with state in sessionStorage', async () => { let teardown; - before(async function() { + before(async function () { teardown = await setup({ storeStateInSessionStorage: true }); }); - after(async function() { + after(async function () { await teardown(); }); - describe('permalink', function() { - it('should allow for copying the snapshot URL as a short URL and should open it', async function() { + describe('permalink', function () { + it('should allow for copying the snapshot URL as a short URL and should open it', async function () { const re = new RegExp(baseUrl + '/goto/[0-9a-f]{32}$'); await PageObjects.share.checkShortenUrl(); let actualUrl; diff --git a/test/functional/apps/discover/_sidebar.js b/test/functional/apps/discover/_sidebar.js index 6ad4cdb5b0b12..ce7ebff9cce74 100644 --- a/test/functional/apps/discover/_sidebar.js +++ b/test/functional/apps/discover/_sidebar.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'discover', 'timePicker']); describe('discover sidebar', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and update configDoc await kibanaServer.uiSettings.replace({ defaultIndex: 'logstash-*', @@ -44,21 +44,21 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - describe('field filtering', function() { - it('should reveal and hide the filter form when the toggle is clicked', async function() { + describe('field filtering', function () { + it('should reveal and hide the filter form when the toggle is clicked', async function () { await PageObjects.discover.openSidebarFieldFilter(); await PageObjects.discover.closeSidebarFieldFilter(); }); }); - describe('collapse expand', function() { - it('should initially be expanded', async function() { + describe('collapse expand', function () { + it('should initially be expanded', async function () { const width = await PageObjects.discover.getSidebarWidth(); log.debug('expanded sidebar width = ' + width); expect(width > 20).to.be(true); }); - it('should collapse when clicked', async function() { + it('should collapse when clicked', async function () { await PageObjects.discover.toggleSidebarCollapse(); log.debug('PageObjects.discover.getSidebarWidth()'); const width = await PageObjects.discover.getSidebarWidth(); @@ -66,7 +66,7 @@ export default function({ getService, getPageObjects }) { expect(width < 20).to.be(true); }); - it('should expand when clicked', async function() { + it('should expand when clicked', async function () { await PageObjects.discover.toggleSidebarCollapse(); log.debug('PageObjects.discover.getSidebarWidth()'); diff --git a/test/functional/apps/discover/_source_filters.js b/test/functional/apps/discover/_source_filters.js index 74d0da7cdb3e7..b483f4cd67112 100644 --- a/test/functional/apps/discover/_source_filters.js +++ b/test/functional/apps/discover/_source_filters.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'timePicker', 'discover']); describe('source filters', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and update configDoc await kibanaServer.uiSettings.replace({ defaultIndex: 'logstash-*', @@ -48,11 +48,11 @@ export default function({ getService, getPageObjects }) { await PageObjects.common.sleep(1000); }); - it('should not get the field referer', async function() { + it('should not get the field referer', async function () { const fieldNames = await PageObjects.discover.getAllFieldNames(); expect(fieldNames).to.not.contain('referer'); const relatedContentFields = fieldNames.filter( - fieldName => fieldName.indexOf('relatedContent') === 0 + (fieldName) => fieldName.indexOf('relatedContent') === 0 ); expect(relatedContentFields).to.have.length(0); }); diff --git a/test/functional/apps/discover/index.js b/test/functional/apps/discover/index.js index 50f140b99aa1a..fe0d57b23d41d 100644 --- a/test/functional/apps/discover/index.js +++ b/test/functional/apps/discover/index.js @@ -17,14 +17,14 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const esArchiver = getService('esArchiver'); const browser = getService('browser'); - describe('discover app', function() { + describe('discover app', function () { this.tags('ciGroup6'); - before(function() { + before(function () { return browser.setWindowSize(1300, 800); }); diff --git a/test/functional/apps/getting_started/_shakespeare.js b/test/functional/apps/getting_started/_shakespeare.js index b0a572d9a54f9..e727949da5ad3 100644 --- a/test/functional/apps/getting_started/_shakespeare.js +++ b/test/functional/apps/getting_started/_shakespeare.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const esArchiver = getService('esArchiver'); const retry = getService('retry'); @@ -42,7 +42,7 @@ export default function({ getService, getPageObjects }) { // order they are added. let aggIndex = 1; - before(async function() { + before(async function () { log.debug( 'Load empty_kibana and Shakespeare Getting Started data\n' + 'https://www.elastic.co/guide/en/kibana/current/tutorial-load-dataset.html' @@ -57,7 +57,7 @@ export default function({ getService, getPageObjects }) { await security.testUser.restoreDefaults(); }); - it('should create shakespeare index pattern', async function() { + it('should create shakespeare index pattern', async function () { await PageObjects.common.navigateToApp('settings'); log.debug('Create shakespeare index pattern'); await PageObjects.settings.createIndexPattern('shakespeare', null); @@ -71,7 +71,7 @@ export default function({ getService, getPageObjects }) { yet, you’ll see a single big bar that shows the total count of documents that match the default wildcard query. */ - it('should create initial vertical bar chart', async function() { + it('should create initial vertical bar chart', async function () { log.debug('create shakespeare vertical bar chart'); await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVerticalBarChart(); @@ -94,7 +94,7 @@ export default function({ getService, getPageObjects }) { and choose speaker from the field list. You can also give the axis a custom label, Speaking Parts. */ - it('should configure metric Unique Count Speaking Parts', async function() { + it('should configure metric Unique Count Speaking Parts', async function () { log.debug('Metric = Unique Count, speaker, Speaking Parts'); // this first change to the YAxis metric agg uses the default aggIndex of 1 await PageObjects.visEditor.selectYAxisAggregation( @@ -122,7 +122,7 @@ export default function({ getService, getPageObjects }) { also give the axis a custom label, Play Name. 5. Click Apply changes images/apply-changes-button.png to view the results. */ - it('should configure Terms aggregation on play_name', async function() { + it('should configure Terms aggregation on play_name', async function () { await PageObjects.visEditor.clickBucket('X-axis'); log.debug('Aggregation = Terms'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -157,7 +157,7 @@ export default function({ getService, getPageObjects }) { 1. Click Add metrics to add a Y-axis aggregation. 2. Choose the Max aggregation and select the speech_number field. */ - it('should configure Max aggregation metric on speech_number', async function() { + it('should configure Max aggregation metric on speech_number', async function () { await PageObjects.visEditor.clickBucket('Y-axis', 'metrics'); log.debug('Aggregation = Max'); await PageObjects.visEditor.selectYAxisAggregation( @@ -196,7 +196,7 @@ export default function({ getService, getPageObjects }) { 3. Click Options and change the Bar Mode to grouped. 4. Click Apply changes images/apply-changes-button.png. Your chart should now look like this: */ - it('should configure change options to normal bars', async function() { + it('should configure change options to normal bars', async function () { await PageObjects.visEditor.clickMetricsAndAxes(); await PageObjects.visEditor.selectChartMode('normal'); await PageObjects.visEditor.clickGo(); @@ -222,7 +222,7 @@ export default function({ getService, getPageObjects }) { Save this chart with the name Bar Example. */ - it('should change the Y-Axis extents', async function() { + it('should change the Y-Axis extents', async function () { await PageObjects.visEditor.setAxisExtents('50', '250'); await PageObjects.visEditor.clickGo(); diff --git a/test/functional/apps/getting_started/index.js b/test/functional/apps/getting_started/index.js index 41ee71a753712..399d3fe87484b 100644 --- a/test/functional/apps/getting_started/index.js +++ b/test/functional/apps/getting_started/index.js @@ -17,13 +17,13 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); - describe('Getting Started ', function() { + describe('Getting Started ', function () { this.tags(['ciGroup6']); - before(async function() { + before(async function () { await browser.setWindowSize(1200, 800); }); // https://www.elastic.co/guide/en/kibana/current/tutorial-load-dataset.html diff --git a/test/functional/apps/home/_add_data.js b/test/functional/apps/home/_add_data.js index d0812ba091fde..6ba123e579f7a 100644 --- a/test/functional/apps/home/_add_data.js +++ b/test/functional/apps/home/_add_data.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const PageObjects = getPageObjects(['common', 'header', 'home', 'dashboard']); diff --git a/test/functional/apps/home/_home.js b/test/functional/apps/home/_home.js index f8c432962eaef..d939689523e11 100644 --- a/test/functional/apps/home/_home.js +++ b/test/functional/apps/home/_home.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const globalNav = getService('globalNav'); const PageObjects = getPageObjects(['common', 'header', 'home']); diff --git a/test/functional/apps/home/_navigation.ts b/test/functional/apps/home/_navigation.ts index 3c1b0f163ba97..cfe4f9cc3e014 100644 --- a/test/functional/apps/home/_navigation.ts +++ b/test/functional/apps/home/_navigation.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const browser = getService('browser'); const PageObjects = getPageObjects(['common', 'header', 'home', 'timePicker']); const appsMenu = getService('appsMenu'); diff --git a/test/functional/apps/home/_newsfeed.ts b/test/functional/apps/home/_newsfeed.ts index 096e237850c72..aabd243e48f21 100644 --- a/test/functional/apps/home/_newsfeed.ts +++ b/test/functional/apps/home/_newsfeed.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const globalNav = getService('globalNav'); const PageObjects = getPageObjects(['common', 'newsfeed']); diff --git a/test/functional/apps/home/_sample_data.ts b/test/functional/apps/home/_sample_data.ts index cbf162833e876..9d75382ca4452 100644 --- a/test/functional/apps/home/_sample_data.ts +++ b/test/functional/apps/home/_sample_data.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import moment from 'moment'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const retry = getService('retry'); const find = getService('find'); const log = getService('log'); diff --git a/test/functional/apps/home/index.js b/test/functional/apps/home/index.js index 5535a28c892f8..f3f564fbd2919 100644 --- a/test/functional/apps/home/index.js +++ b/test/functional/apps/home/index.js @@ -17,13 +17,13 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); - describe('homepage app', function() { + describe('homepage app', function () { this.tags('ciGroup6'); - before(function() { + before(function () { return browser.setWindowSize(1200, 800); }); diff --git a/test/functional/apps/management/_create_index_pattern_wizard.js b/test/functional/apps/management/_create_index_pattern_wizard.js index 65d852b249ea0..8209f3e1ac9d6 100644 --- a/test/functional/apps/management/_create_index_pattern_wizard.js +++ b/test/functional/apps/management/_create_index_pattern_wizard.js @@ -19,28 +19,28 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['settings', 'common']); - describe('"Create Index Pattern" wizard', function() { - before(async function() { + describe('"Create Index Pattern" wizard', function () { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); }); - describe('step 1 next button', function() { - it('is disabled by default', async function() { + describe('step 1 next button', function () { + it('is disabled by default', async function () { await (await testSubjects.find('createIndexPatternButton')).click(); const btn = await PageObjects.settings.getCreateIndexPatternGoToStep2Button(); const isEnabled = await btn.isEnabled(); expect(isEnabled).not.to.be.ok(); }); - it('is enabled once an index pattern with matching indices has been entered', async function() { + it('is enabled once an index pattern with matching indices has been entered', async function () { await PageObjects.settings.setIndexPatternField(); await PageObjects.common.sleep(1000); const btn = await PageObjects.settings.getCreateIndexPatternGoToStep2Button(); diff --git a/test/functional/apps/management/_handle_alias.js b/test/functional/apps/management/_handle_alias.js index 35c43c4633410..902b49eacdc00 100644 --- a/test/functional/apps/management/_handle_alias.js +++ b/test/functional/apps/management/_handle_alias.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const es = getService('legacyEs'); const retry = getService('retry'); @@ -27,8 +27,8 @@ export default function({ getService, getPageObjects }) { const PageObjects = getPageObjects(['common', 'home', 'settings', 'discover', 'timePicker']); // FLAKY: https://github.com/elastic/kibana/issues/59717 - describe.skip('Index patterns on aliases', function() { - before(async function() { + describe.skip('Index patterns on aliases', function () { + before(async function () { await security.testUser.setRoles(['kibana_admin', 'test_alias_reader']); await esArchiver.loadIfNeeded('alias'); await esArchiver.load('empty_kibana'); @@ -49,27 +49,27 @@ export default function({ getService, getPageObjects }) { }); }); - it('should be able to create index pattern without time field', async function() { + it('should be able to create index pattern without time field', async function () { await PageObjects.settings.createIndexPattern('alias1', null); const patternName = await PageObjects.settings.getIndexPageHeading(); expect(patternName).to.be('alias1*'); }); - it('should be able to discover and verify no of hits for alias1', async function() { + it('should be able to discover and verify no of hits for alias1', async function () { const expectedHitCount = '4'; await PageObjects.common.navigateToApp('discover'); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be(expectedHitCount); }); }); - it('should be able to create index pattern with timefield', async function() { + it('should be able to create index pattern with timefield', async function () { await PageObjects.settings.createIndexPattern('alias2', 'date'); const patternName = await PageObjects.settings.getIndexPageHeading(); expect(patternName).to.be('alias2*'); }); - it('should be able to discover and verify no of hits for alias2', async function() { + it('should be able to discover and verify no of hits for alias2', async function () { const expectedHitCount = '5'; const fromTime = 'Nov 12, 2016 @ 05:00:00.000'; const toTime = 'Nov 19, 2016 @ 05:00:00.000'; @@ -78,7 +78,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.discover.selectIndexPattern('alias2*'); await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be(expectedHitCount); }); }); diff --git a/test/functional/apps/management/_handle_version_conflict.js b/test/functional/apps/management/_handle_version_conflict.js index c2cd846e0da8f..78351b527ab35 100644 --- a/test/functional/apps/management/_handle_version_conflict.js +++ b/test/functional/apps/management/_handle_version_conflict.js @@ -28,7 +28,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const browser = getService('browser'); const es = getService('legacyEs'); @@ -38,12 +38,12 @@ export default function({ getService, getPageObjects }) { const log = getService('log'); describe('index version conflict', function describeIndexTests() { - before(async function() { + before(async function () { await browser.setWindowSize(1200, 800); await esArchiver.load('discover'); }); - it('Should be able to surface version conflict notification while creating scripted field', async function() { + it('Should be able to surface version conflict notification while creating scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -62,13 +62,13 @@ export default function({ getService, getPageObjects }) { expect(response.result).to.be('updated'); await PageObjects.settings.setFieldFormat('url'); await PageObjects.settings.clickSaveScriptedField(); - await retry.try(async function() { + await retry.try(async function () { const message = await PageObjects.common.closeToast(); expect(message).to.contain('Unable'); }); }); - it('Should be able to surface version conflict notification while changing field format', async function() { + it('Should be able to surface version conflict notification while changing field format', async function () { const fieldName = 'geo.srcdest'; await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); @@ -87,7 +87,7 @@ export default function({ getService, getPageObjects }) { log.debug(JSON.stringify(response)); expect(response.result).to.be('updated'); await PageObjects.settings.controlChangeSave(); - await retry.try(async function() { + await retry.try(async function () { //await PageObjects.common.sleep(2000); const message = await PageObjects.common.closeToast(); expect(message).to.contain('Unable'); diff --git a/test/functional/apps/management/_import_objects.js b/test/functional/apps/management/_import_objects.js index cd39f1cf25ccc..6b40837808387 100644 --- a/test/functional/apps/management/_import_objects.js +++ b/test/functional/apps/management/_import_objects.js @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import path from 'path'; import { indexBy } from 'lodash'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common', 'settings', 'header']); @@ -30,7 +30,7 @@ export default function({ getService, getPageObjects }) { describe('import objects', function describeIndexTests() { describe('.ndjson file', () => { - beforeEach(async function() { + beforeEach(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.navigateTo(); @@ -38,11 +38,11 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.clickKibanaSavedObjects(); }); - afterEach(async function() { + afterEach(async function () { await esArchiver.unload('management'); }); - it('should import saved objects', async function() { + it('should import saved objects', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects.ndjson') ); @@ -67,7 +67,7 @@ export default function({ getService, getPageObjects }) { expect(flyout['Log Agents'].relationship).to.eql('Parent'); }); - it('should provide dialog to allow the importing of saved objects with index pattern conflicts', async function() { + it('should provide dialog to allow the importing of saved objects with index pattern conflicts', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_conflicts.ndjson') ); @@ -84,7 +84,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(true); }); - it('should allow the user to override duplicate saved objects', async function() { + it('should allow the user to override duplicate saved objects', async function () { // This data has already been loaded by the "visualize" esArchive. We'll load it again // so that we can override the existing visualization. await PageObjects.settings.importFile( @@ -103,7 +103,7 @@ export default function({ getService, getPageObjects }) { expect(isSuccessful).to.be(true); }); - it('should allow the user to cancel overriding duplicate saved objects', async function() { + it('should allow the user to cancel overriding duplicate saved objects', async function () { // This data has already been loaded by the "visualize" esArchive. We'll load it again // so that we can be prompted to override the existing visualization. await PageObjects.settings.importFile( @@ -122,7 +122,7 @@ export default function({ getService, getPageObjects }) { expect(isSuccessful).to.be(true); }); - it('should import saved objects linked to saved searches', async function() { + it('should import saved objects linked to saved searches', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_saved_search.ndjson') ); @@ -140,7 +140,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(true); }); - it('should not import saved objects linked to saved searches when saved search does not exist', async function() { + it('should not import saved objects linked to saved searches when saved search does not exist', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_connected_to_saved_search.ndjson') ); @@ -152,7 +152,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(false); }); - it('should not import saved objects linked to saved searches when saved search index pattern does not exist', async function() { + it('should not import saved objects linked to saved searches when saved search index pattern does not exist', async function () { const elements = indexBy( await PageObjects.settings.getSavedObjectElementsInTable(), 'title' @@ -209,7 +209,7 @@ export default function({ getService, getPageObjects }) { }); describe('.json file', () => { - beforeEach(async function() { + beforeEach(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.navigateTo(); @@ -217,11 +217,11 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.clickKibanaSavedObjects(); }); - afterEach(async function() { + afterEach(async function () { await esArchiver.unload('management'); }); - it('should import saved objects', async function() { + it('should import saved objects', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects.json') ); @@ -232,7 +232,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(true); }); - it('should provide dialog to allow the importing of saved objects with index pattern conflicts', async function() { + it('should provide dialog to allow the importing of saved objects with index pattern conflicts', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects-conflicts.json') ); @@ -250,7 +250,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(true); }); - it('should allow the user to override duplicate saved objects', async function() { + it('should allow the user to override duplicate saved objects', async function () { // This data has already been loaded by the "visualize" esArchive. We'll load it again // so that we can override the existing visualization. await PageObjects.settings.importFile( @@ -270,7 +270,7 @@ export default function({ getService, getPageObjects }) { expect(isSuccessful).to.be(true); }); - it('should allow the user to cancel overriding duplicate saved objects', async function() { + it('should allow the user to cancel overriding duplicate saved objects', async function () { // This data has already been loaded by the "visualize" esArchive. We'll load it again // so that we can be prompted to override the existing visualization. await PageObjects.settings.importFile( @@ -290,7 +290,7 @@ export default function({ getService, getPageObjects }) { expect(isSuccessful).to.be(true); }); - it('should import saved objects linked to saved searches', async function() { + it('should import saved objects linked to saved searches', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_saved_search.json') ); @@ -308,7 +308,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(true); }); - it('should not import saved objects linked to saved searches when saved search does not exist', async function() { + it('should not import saved objects linked to saved searches when saved search does not exist', async function () { await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_connected_to_saved_search.json') ); @@ -320,7 +320,7 @@ export default function({ getService, getPageObjects }) { expect(isSavedObjectImported).to.be(false); }); - it('should not import saved objects linked to saved searches when saved search index pattern does not exist', async function() { + it('should not import saved objects linked to saved searches when saved search index pattern does not exist', async function () { // First, import the saved search await PageObjects.settings.importFile( path.join(__dirname, 'exports', '_import_objects_saved_search.json') diff --git a/test/functional/apps/management/_index_pattern_create_delete.js b/test/functional/apps/management/_index_pattern_create_delete.js index c44541484b8d8..0277b535919d4 100644 --- a/test/functional/apps/management/_index_pattern_create_delete.js +++ b/test/functional/apps/management/_index_pattern_create_delete.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const browser = getService('browser'); const log = getService('log'); @@ -28,14 +28,14 @@ export default function({ getService, getPageObjects }) { const PageObjects = getPageObjects(['settings', 'common', 'header']); describe('creating and deleting default index', function describeIndexTests() { - before(function() { + before(function () { // Delete .kibana index and then wait for Kibana to re-create it return kibanaServer.uiSettings .replace({}) - .then(function() { + .then(function () { return PageObjects.settings.navigateTo(); }) - .then(function() { + .then(function () { return PageObjects.settings.clickKibanaIndexPatterns(); }); }); @@ -63,25 +63,25 @@ export default function({ getService, getPageObjects }) { describe('index pattern creation', function indexPatternCreation() { let indexPatternId; - before(function() { - return PageObjects.settings.createIndexPattern().then(id => (indexPatternId = id)); + before(function () { + return PageObjects.settings.createIndexPattern().then((id) => (indexPatternId = id)); }); - it('should have index pattern in page header', async function() { + it('should have index pattern in page header', async function () { const patternName = await PageObjects.settings.getIndexPageHeading(); expect(patternName).to.be('logstash-*'); }); it('should have index pattern in url', function url() { return retry.try(function tryingForTime() { - return browser.getCurrentUrl().then(function(currentUrl) { + return browser.getCurrentUrl().then(function (currentUrl) { expect(currentUrl).to.contain(indexPatternId); }); }); }); it('should have expected table headers', function checkingHeader() { - return PageObjects.settings.getTableHeader().then(function(headers) { + return PageObjects.settings.getTableHeader().then(function (headers) { log.debug('header.length = ' + headers.length); const expectedHeaders = [ 'Name', @@ -95,7 +95,7 @@ export default function({ getService, getPageObjects }) { expect(headers.length).to.be(expectedHeaders.length); const comparedHeaders = headers.map(function compareHead(header, i) { - return header.getVisibleText().then(function(text) { + return header.getVisibleText().then(function (text) { expect(text).to.be(expectedHeaders[i]); }); }); @@ -106,9 +106,9 @@ export default function({ getService, getPageObjects }) { }); describe('index pattern deletion', function indexDelete() { - before(function() { + before(function () { const expectedAlertText = 'Delete index pattern?'; - return PageObjects.settings.removeIndexPattern().then(function(alertText) { + return PageObjects.settings.removeIndexPattern().then(function (alertText) { expect(alertText).to.be(expectedAlertText); }); }); @@ -116,7 +116,7 @@ export default function({ getService, getPageObjects }) { it('should return to index pattern list', function indexNotInUrl() { // give the url time to settle return retry.try(function tryingForTime() { - return browser.getCurrentUrl().then(function(currentUrl) { + return browser.getCurrentUrl().then(function (currentUrl) { log.debug('currentUrl = ' + currentUrl); expect(currentUrl).to.contain('management/kibana/indexPatterns'); }); diff --git a/test/functional/apps/management/_index_pattern_filter.js b/test/functional/apps/management/_index_pattern_filter.js index a32024adb5ec7..972f441ca001d 100644 --- a/test/functional/apps/management/_index_pattern_filter.js +++ b/test/functional/apps/management/_index_pattern_filter.js @@ -19,35 +19,35 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const retry = getService('retry'); const PageObjects = getPageObjects(['settings']); describe('index pattern filter', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); }); - beforeEach(async function() { + beforeEach(async function () { await PageObjects.settings.createIndexPattern(); }); - afterEach(async function() { + afterEach(async function () { await PageObjects.settings.removeIndexPattern(); }); - it('should filter indexed fields', async function() { + it('should filter indexed fields', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); await PageObjects.settings.getFieldTypes(); await PageObjects.settings.setFieldTypeFilter('string'); - await retry.try(async function() { + await retry.try(async function () { const fieldTypes = await PageObjects.settings.getFieldTypes(); expect(fieldTypes.length).to.be.above(0); for (const fieldType of fieldTypes) { @@ -57,7 +57,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.setFieldTypeFilter('number'); - await retry.try(async function() { + await retry.try(async function () { const fieldTypes = await PageObjects.settings.getFieldTypes(); expect(fieldTypes.length).to.be.above(0); for (const fieldType of fieldTypes) { diff --git a/test/functional/apps/management/_index_pattern_popularity.js b/test/functional/apps/management/_index_pattern_popularity.js index a713d39f69c26..530b8e1111a0c 100644 --- a/test/functional/apps/management/_index_pattern_popularity.js +++ b/test/functional/apps/management/_index_pattern_popularity.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const log = getService('log'); const PageObjects = getPageObjects(['settings', 'common']); describe('index result popularity', function describeIndexTests() { const fieldName = 'geo.coordinates'; - before(async function() { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.navigateTo(); @@ -47,13 +47,13 @@ export default function({ getService, getPageObjects }) { // Cancel saving the popularity change (we didn't make a change in this case, just checking the value) }); - it('should update the popularity input', async function() { + it('should update the popularity input', async function () { const popularity = await PageObjects.settings.getPopularity(); log.debug('popularity = ' + popularity); expect(popularity).to.be('1'); }); - it('should be reset on cancel', async function() { + it('should be reset on cancel', async function () { // Cancel saving the popularity change await PageObjects.settings.controlChangeCancel(); await PageObjects.settings.openControlsByName(fieldName); @@ -63,7 +63,7 @@ export default function({ getService, getPageObjects }) { expect(popularity).to.be('0'); }); - it('can be saved', async function() { + it('can be saved', async function () { // Saving the popularity change await PageObjects.settings.controlChangeSave(); await PageObjects.settings.openControlsByName(fieldName); diff --git a/test/functional/apps/management/_index_pattern_results_sort.js b/test/functional/apps/management/_index_pattern_results_sort.js index f4d96627561db..562159a319e78 100644 --- a/test/functional/apps/management/_index_pattern_results_sort.js +++ b/test/functional/apps/management/_index_pattern_results_sort.js @@ -19,13 +19,13 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const retry = getService('retry'); const PageObjects = getPageObjects(['settings', 'common']); describe('index result field sort', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); }); @@ -35,7 +35,7 @@ export default function({ getService, getPageObjects }) { heading: 'Name', first: '@message', last: 'xss.raw', - selector: async function() { + selector: async function () { const tableRow = await PageObjects.settings.getTableRow(0, 0); return await tableRow.getVisibleText(); }, @@ -44,49 +44,49 @@ export default function({ getService, getPageObjects }) { heading: 'Type', first: '_source', last: 'string', - selector: async function() { + selector: async function () { const tableRow = await PageObjects.settings.getTableRow(0, 1); return await tableRow.getVisibleText(); }, }, ]; - columns.forEach(function(col) { + columns.forEach(function (col) { describe('sort by heading - ' + col.heading, function indexPatternCreation() { - before(async function() { + before(async function () { await PageObjects.settings.createIndexPattern(); }); - after(async function() { + after(async function () { return await PageObjects.settings.removeIndexPattern(); }); - it('should sort ascending', async function() { + it('should sort ascending', async function () { await PageObjects.settings.sortBy(col.heading); const rowText = await col.selector(); expect(rowText).to.be(col.first); }); - it('should sort descending', async function() { + it('should sort descending', async function () { await PageObjects.settings.sortBy(col.heading); const getText = await col.selector(); expect(getText).to.be(col.last); }); }); }); - describe('field list pagination', function() { + describe('field list pagination', function () { const EXPECTED_FIELD_COUNT = 86; - before(async function() { + before(async function () { await PageObjects.settings.createIndexPattern(); }); - after(async function() { + after(async function () { return await PageObjects.settings.removeIndexPattern(); }); - it('makelogs data should have expected number of fields', async function() { - await retry.try(async function() { + it('makelogs data should have expected number of fields', async function () { + await retry.try(async function () { const TabCount = await PageObjects.settings.getFieldsTabCount(); expect(TabCount).to.be('' + EXPECTED_FIELD_COUNT); }); diff --git a/test/functional/apps/management/_kibana_settings.js b/test/functional/apps/management/_kibana_settings.js index 123c1a938a4f5..2a488a94c6889 100644 --- a/test/functional/apps/management/_kibana_settings.js +++ b/test/functional/apps/management/_kibana_settings.js @@ -19,13 +19,13 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const browser = getService('browser'); const PageObjects = getPageObjects(['settings', 'common', 'dashboard', 'timePicker', 'header']); describe('kibana settings', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); await PageObjects.settings.createIndexPattern(); @@ -38,7 +38,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.removeLogstashIndexPatternIfExist(); }); - it('should allow setting advanced settings', async function() { + it('should allow setting advanced settings', async function () { await PageObjects.settings.clickKibanaSettings(); await PageObjects.settings.setAdvancedSettingsSelect('dateFormat:tz', 'America/Phoenix'); const advancedSetting = await PageObjects.settings.getAdvancedSettings('dateFormat:tz'); @@ -66,7 +66,7 @@ export default function({ getService, getPageObjects }) { expect(storeInSessionStorage).to.be(null); }); - it('when false, dashboard state is unhashed', async function() { + it('when false, dashboard state is unhashed', async function () { await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.clickNewDashboard(); await PageObjects.timePicker.setDefaultAbsoluteRange(); @@ -78,7 +78,7 @@ export default function({ getService, getPageObjects }) { expect(appState.length).to.be.greaterThan(20); }); - it('setting to true change is preserved', async function() { + it('setting to true change is preserved', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaSettings(); await PageObjects.settings.toggleAdvancedSettingCheckbox('state:storeInSessionStorage'); @@ -88,7 +88,7 @@ export default function({ getService, getPageObjects }) { expect(storeInSessionStorage).to.be('true'); }); - it('when true, dashboard state is hashed', async function() { + it('when true, dashboard state is hashed', async function () { await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.clickNewDashboard(); await PageObjects.timePicker.setDefaultAbsoluteRange(); @@ -114,7 +114,7 @@ export default function({ getService, getPageObjects }) { }); }); - after(async function() { + after(async function () { await kibanaServer.uiSettings.replace({ 'dateFormat:tz': 'UTC' }); await browser.refresh(); }); diff --git a/test/functional/apps/management/_mgmt_import_saved_objects.js b/test/functional/apps/management/_mgmt_import_saved_objects.js index 2f9d9f9bfb178..a8a0a19d4962d 100644 --- a/test/functional/apps/management/_mgmt_import_saved_objects.js +++ b/test/functional/apps/management/_mgmt_import_saved_objects.js @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import path from 'path'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const PageObjects = getPageObjects(['common', 'settings', 'header']); @@ -28,17 +28,17 @@ export default function({ getService, getPageObjects }) { //that referenced the saved search was not imported.( https://github.com/elastic/kibana/issues/22238) describe('mgmt saved objects', function describeIndexTests() { - beforeEach(async function() { + beforeEach(async function () { await esArchiver.load('discover'); await PageObjects.settings.navigateTo(); }); - afterEach(async function() { + afterEach(async function () { await esArchiver.unload('discover'); await esArchiver.load('empty_kibana'); }); - it('should import saved objects mgmt', async function() { + it('should import saved objects mgmt', async function () { await PageObjects.settings.clickKibanaSavedObjects(); await PageObjects.settings.importFile( path.join(__dirname, 'exports', 'mgmt_import_objects.json') diff --git a/test/functional/apps/management/_scripted_fields.js b/test/functional/apps/management/_scripted_fields.js index d85d5a952d3ec..2727313ab2336 100644 --- a/test/functional/apps/management/_scripted_fields.js +++ b/test/functional/apps/management/_scripted_fields.js @@ -35,7 +35,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const log = getService('log'); const browser = getService('browser'); @@ -52,10 +52,10 @@ export default function({ getService, getPageObjects }) { 'timePicker', ]); - describe('scripted fields', function() { + describe('scripted fields', function () { this.tags(['skipFirefox']); - before(async function() { + before(async function () { await browser.setWindowSize(1200, 800); // delete .kibana index and then wait for Kibana to re-create it await kibanaServer.uiSettings.replace({}); @@ -69,7 +69,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.removeLogstashIndexPatternIfExist(); }); - it('should not allow saving of invalid scripts', async function() { + it('should not allow saving of invalid scripts', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -87,7 +87,7 @@ export default function({ getService, getPageObjects }) { describe('testing regression for issue #33251', function describeIndexTests() { const scriptedPainlessFieldName = 'ram_Pain_reg'; - it('should create and edit scripted field', async function() { + it('should create and edit scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -103,7 +103,7 @@ export default function({ getService, getPageObjects }) { '1', script ); - await retry.try(async function() { + await retry.try(async function () { expect(parseInt(await PageObjects.settings.getScriptedFieldsTabCount())).to.be( startingCount + 1 ); @@ -121,7 +121,7 @@ export default function({ getService, getPageObjects }) { describe('creating and using Painless numeric scripted fields', function describeIndexTests() { const scriptedPainlessFieldName = 'ram_Pain1'; - it('should create scripted field', async function() { + it('should create scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -139,43 +139,43 @@ export default function({ getService, getPageObjects }) { '1', script ); - await retry.try(async function() { + await retry.try(async function () { expect(parseInt(await PageObjects.settings.getScriptedFieldsTabCount())).to.be( startingCount + 1 ); }); }); - it('should see scripted field value in Discover', async function() { + it('should see scripted field value in Discover', async function () { const fromTime = 'Sep 17, 2015 @ 06:31:44.000'; const toTime = 'Sep 18, 2015 @ 18:31:44.000'; await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName); - await retry.try(async function() { + await retry.try(async function () { await PageObjects.discover.clickFieldListItemAdd(scriptedPainlessFieldName); }); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { const rowData = await PageObjects.discover.getDocTableIndex(1); expect(rowData).to.be('Sep 18, 2015 @ 18:20:57.916\n18'); }); }); - it('should filter by scripted field value in Discover', async function() { + it('should filter by scripted field value in Discover', async function () { await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName); await log.debug('filter by the first value (14) in the expanded scripted field list'); await PageObjects.discover.clickFieldListPlusFilter(scriptedPainlessFieldName, '14'); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('31'); }); }); - it('should visualize scripted field in vertical bar chart', async function() { + it('should visualize scripted field in vertical bar chart', async function () { const expectedChartValues = [ ['14', '31'], ['10', '29'], @@ -211,7 +211,7 @@ export default function({ getService, getPageObjects }) { describe('creating and using Painless string scripted fields', function describeIndexTests() { const scriptedPainlessFieldName2 = 'painString'; - it('should create scripted field', async function() { + it('should create scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -226,44 +226,44 @@ export default function({ getService, getPageObjects }) { '1', "if (doc['response.raw'].value == '200') { return 'good'} else { return 'bad'}" ); - await retry.try(async function() { + await retry.try(async function () { expect(parseInt(await PageObjects.settings.getScriptedFieldsTabCount())).to.be( startingCount + 1 ); }); }); - it('should see scripted field value in Discover', async function() { + it('should see scripted field value in Discover', async function () { const fromTime = 'Sep 17, 2015 @ 06:31:44.000'; const toTime = 'Sep 18, 2015 @ 18:31:44.000'; await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); - await retry.try(async function() { + await retry.try(async function () { await PageObjects.discover.clickFieldListItemAdd(scriptedPainlessFieldName2); }); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { const rowData = await PageObjects.discover.getDocTableIndex(1); expect(rowData).to.be('Sep 18, 2015 @ 18:20:57.916\ngood'); }); }); - it('should filter by scripted field value in Discover', async function() { + it('should filter by scripted field value in Discover', async function () { await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); await log.debug('filter by "bad" in the expanded scripted field list'); await PageObjects.discover.clickFieldListPlusFilter(scriptedPainlessFieldName2, 'bad'); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('27'); }); await filterBar.removeAllFilters(); }); - it('should visualize scripted field in vertical bar chart', async function() { + it('should visualize scripted field in vertical bar chart', async function () { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); await inspector.open(); @@ -277,7 +277,7 @@ export default function({ getService, getPageObjects }) { describe('creating and using Painless boolean scripted fields', function describeIndexTests() { const scriptedPainlessFieldName2 = 'painBool'; - it('should create scripted field', async function() { + it('should create scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -292,44 +292,44 @@ export default function({ getService, getPageObjects }) { '1', "doc['response.raw'].value == '200'" ); - await retry.try(async function() { + await retry.try(async function () { expect(parseInt(await PageObjects.settings.getScriptedFieldsTabCount())).to.be( startingCount + 1 ); }); }); - it('should see scripted field value in Discover', async function() { + it('should see scripted field value in Discover', async function () { const fromTime = 'Sep 17, 2015 @ 06:31:44.000'; const toTime = 'Sep 18, 2015 @ 18:31:44.000'; await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); - await retry.try(async function() { + await retry.try(async function () { await PageObjects.discover.clickFieldListItemAdd(scriptedPainlessFieldName2); }); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { const rowData = await PageObjects.discover.getDocTableIndex(1); expect(rowData).to.be('Sep 18, 2015 @ 18:20:57.916\ntrue'); }); }); - it('should filter by scripted field value in Discover', async function() { + it('should filter by scripted field value in Discover', async function () { await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); await log.debug('filter by "true" in the expanded scripted field list'); await PageObjects.discover.clickFieldListPlusFilter(scriptedPainlessFieldName2, 'true'); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('359'); }); await filterBar.removeAllFilters(); }); - it('should visualize scripted field in vertical bar chart', async function() { + it('should visualize scripted field in vertical bar chart', async function () { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); await inspector.open(); @@ -343,7 +343,7 @@ export default function({ getService, getPageObjects }) { describe('creating and using Painless date scripted fields', function describeIndexTests() { const scriptedPainlessFieldName2 = 'painDate'; - it('should create scripted field', async function() { + it('should create scripted field', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -358,32 +358,32 @@ export default function({ getService, getPageObjects }) { '1', "doc['utc_time'].value.getMillis() + (1000) * 60 * 60" ); - await retry.try(async function() { + await retry.try(async function () { expect(parseInt(await PageObjects.settings.getScriptedFieldsTabCount())).to.be( startingCount + 1 ); }); }); - it('should see scripted field value in Discover', async function() { + it('should see scripted field value in Discover', async function () { const fromTime = 'Sep 17, 2015 @ 19:22:00.000'; const toTime = 'Sep 18, 2015 @ 07:00:00.000'; await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setAbsoluteRange(fromTime, toTime); await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); - await retry.try(async function() { + await retry.try(async function () { await PageObjects.discover.clickFieldListItemAdd(scriptedPainlessFieldName2); }); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { const rowData = await PageObjects.discover.getDocTableIndex(1); expect(rowData).to.be('Sep 18, 2015 @ 06:52:55.953\n2015-09-18 07:00'); }); }); - it('should filter by scripted field value in Discover', async function() { + it('should filter by scripted field value in Discover', async function () { await PageObjects.discover.clickFieldListItem(scriptedPainlessFieldName2); await log.debug('filter by "Sep 17, 2015 @ 23:00" in the expanded scripted field list'); await PageObjects.discover.clickFieldListPlusFilter( @@ -392,13 +392,13 @@ export default function({ getService, getPageObjects }) { ); await PageObjects.header.waitUntilLoadingHasFinished(); - await retry.try(async function() { + await retry.try(async function () { expect(await PageObjects.discover.getHitCount()).to.be('1'); }); await filterBar.removeAllFilters(); }); - it('should visualize scripted field in vertical bar chart', async function() { + it('should visualize scripted field in vertical bar chart', async function () { await PageObjects.discover.clickFieldListItemVisualize(scriptedPainlessFieldName2); await PageObjects.header.waitUntilLoadingHasFinished(); await inspector.open(); diff --git a/test/functional/apps/management/_scripted_fields_filter.js b/test/functional/apps/management/_scripted_fields_filter.js index 20aa1ad27b170..2eb53508c2846 100644 --- a/test/functional/apps/management/_scripted_fields_filter.js +++ b/test/functional/apps/management/_scripted_fields_filter.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const kibanaServer = getService('kibanaServer'); const retry = getService('retry'); const log = getService('log'); @@ -28,7 +28,7 @@ export default function({ getService, getPageObjects }) { const PageObjects = getPageObjects(['settings']); describe('filter scripted fields', function describeIndexTests() { - before(async function() { + before(async function () { // delete .kibana index and then wait for Kibana to re-create it await browser.setWindowSize(1200, 800); await esArchiver.load('management'); @@ -37,14 +37,14 @@ export default function({ getService, getPageObjects }) { }); }); - after(async function() { + after(async function () { await esArchiver.unload('management'); await kibanaServer.uiSettings.replace({}); }); const scriptedPainlessFieldName = 'ram_pain1'; - it('should filter scripted fields', async function() { + it('should filter scripted fields', async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -64,14 +64,14 @@ export default function({ getService, getPageObjects }) { ); // confirm two additional scripted fields were created - await retry.try(async function() { + await retry.try(async function () { const scriptedFieldLangs = await PageObjects.settings.getScriptedFieldLangs(); expect(scriptedFieldLangs.length).to.be(scriptedFieldLangsBefore.length + 1); }); await PageObjects.settings.setScriptedFieldLanguageFilter('painless'); - await retry.try(async function() { + await retry.try(async function () { const scriptedFieldLangs = await PageObjects.settings.getScriptedFieldLangs(); expect(scriptedFieldLangs.length).to.be.above(0); for (const lang of scriptedFieldLangs) { @@ -81,7 +81,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.setScriptedFieldLanguageFilter('expression'); - await retry.try(async function() { + await retry.try(async function () { const scriptedFieldLangs = await PageObjects.settings.getScriptedFieldLangs(); expect(scriptedFieldLangs.length).to.be.above(0); for (const lang of scriptedFieldLangs) { diff --git a/test/functional/apps/management/_scripted_fields_preview.js b/test/functional/apps/management/_scripted_fields_preview.js index 394d0df83d90d..6af289535457e 100644 --- a/test/functional/apps/management/_scripted_fields_preview.js +++ b/test/functional/apps/management/_scripted_fields_preview.js @@ -19,13 +19,13 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const browser = getService('browser'); const PageObjects = getPageObjects(['settings']); const SCRIPTED_FIELD_NAME = 'myScriptedField'; describe('scripted fields preview', () => { - before(async function() { + before(async function () { await browser.setWindowSize(1200, 800); await PageObjects.settings.createIndexPattern(); @@ -43,21 +43,21 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.removeLogstashIndexPatternIfExist(); }); - it('should display script error when script is invalid', async function() { + it('should display script error when script is invalid', async function () { const scriptResults = await PageObjects.settings.executeScriptedField( `i n v a l i d s c r i p t` ); expect(scriptResults).to.contain('search_phase_execution_exception'); }); - it('should display script results when script is valid', async function() { + it('should display script results when script is valid', async function () { const scriptResults = await PageObjects.settings.executeScriptedField( `doc['bytes'].value * 2` ); expect(scriptResults.replace(/\s/g, '')).to.contain('"myScriptedField":[6196'); }); - it('should display additional fields', async function() { + it('should display additional fields', async function () { const scriptResults = await PageObjects.settings.executeScriptedField( `doc['bytes'].value * 2`, ['bytes'] diff --git a/test/functional/apps/management/_test_huge_fields.js b/test/functional/apps/management/_test_huge_fields.js index bc280e51ae048..5691aecdce655 100644 --- a/test/functional/apps/management/_test_huge_fields.js +++ b/test/functional/apps/management/_test_huge_fields.js @@ -19,22 +19,22 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const esArchiver = getService('esArchiver'); const security = getService('security'); const PageObjects = getPageObjects(['common', 'home', 'settings']); - describe('test large number of fields', function() { + describe('test large number of fields', function () { this.tags(['skipCloud']); const EXPECTED_FIELD_COUNT = '10006'; - before(async function() { + before(async function () { await security.testUser.setRoles(['kibana_admin', 'test_testhuge_reader']); await esArchiver.loadIfNeeded('large_fields'); await PageObjects.settings.createIndexPattern('testhuge', 'date'); }); - it('test_huge data should have expected number of fields', async function() { + it('test_huge data should have expected number of fields', async function () { const tabCount = await PageObjects.settings.getFieldsTabCount(); expect(tabCount).to.be(EXPECTED_FIELD_COUNT); }); diff --git a/test/functional/apps/management/index.js b/test/functional/apps/management/index.js index 510466b4bed52..97e7314f9678e 100644 --- a/test/functional/apps/management/index.js +++ b/test/functional/apps/management/index.js @@ -17,10 +17,10 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const esArchiver = getService('esArchiver'); - describe('management', function() { + describe('management', function () { before(async () => { await esArchiver.unload('logstash_functional'); await esArchiver.load('empty_kibana'); @@ -32,7 +32,7 @@ export default function({ getService, loadTestFile }) { await esArchiver.unload('empty_kibana'); }); - describe('', function() { + describe('', function () { this.tags('ciGroup7'); loadTestFile(require.resolve('./_create_index_pattern_wizard')); @@ -45,7 +45,7 @@ export default function({ getService, loadTestFile }) { loadTestFile(require.resolve('./_mgmt_import_saved_objects')); }); - describe('', function() { + describe('', function () { this.tags('ciGroup8'); loadTestFile(require.resolve('./_index_pattern_filter')); diff --git a/test/functional/apps/saved_objects_management/edit_saved_object.ts b/test/functional/apps/saved_objects_management/edit_saved_object.ts index 1a85ff86498dc..06b2e86dd1af9 100644 --- a/test/functional/apps/saved_objects_management/edit_saved_object.ts +++ b/test/functional/apps/saved_objects_management/edit_saved_object.ts @@ -20,9 +20,9 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -export default function({ getPageObjects, getService }: FtrProviderContext) { +export default function ({ getPageObjects, getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common', 'settings']); diff --git a/test/functional/apps/status_page/index.js b/test/functional/apps/status_page/index.js index 74a538c9eca8c..34f2df287dd6b 100644 --- a/test/functional/apps/status_page/index.js +++ b/test/functional/apps/status_page/index.js @@ -19,19 +19,19 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const retry = getService('retry'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common']); - describe('status page', function() { + describe('status page', function () { this.tags('ciGroup1'); beforeEach(async () => { await PageObjects.common.navigateToApp('status_page'); }); - it('should show the kibana plugin as ready', async function() { + it('should show the kibana plugin as ready', async function () { await retry.tryForTime(6000, async () => { const text = await testSubjects.getVisibleText('statusBreakdown'); expect(text.indexOf('plugin:kibana')).to.be.above(-1); diff --git a/test/functional/apps/timelion/_expression_typeahead.js b/test/functional/apps/timelion/_expression_typeahead.js index 047660158574b..d1e974942a362 100644 --- a/test/functional/apps/timelion/_expression_typeahead.js +++ b/test/functional/apps/timelion/_expression_typeahead.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getPageObjects }) { +export default function ({ getPageObjects }) { const PageObjects = getPageObjects(['common', 'timelion', 'settings', 'timePicker']); describe('expression typeahead', () => { diff --git a/test/functional/apps/timelion/index.js b/test/functional/apps/timelion/index.js index 021fa24397850..4a1c1b25bb160 100644 --- a/test/functional/apps/timelion/index.js +++ b/test/functional/apps/timelion/index.js @@ -17,16 +17,16 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); const log = getService('log'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); - describe('timelion app', function() { + describe('timelion app', function () { this.tags('ciGroup1'); - before(async function() { + before(async function () { log.debug('Starting timelion before method'); await browser.setWindowSize(1280, 800); await esArchiver.loadIfNeeded('logstash_functional'); diff --git a/test/functional/apps/visualize/_area_chart.js b/test/functional/apps/visualize/_area_chart.js index b612a19e235bd..ea4db35d75ccf 100644 --- a/test/functional/apps/visualize/_area_chart.js +++ b/test/functional/apps/visualize/_area_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const find = getService('find'); const inspector = getService('inspector'); @@ -61,7 +61,7 @@ export default function({ getService, getPageObjects }) { return PageObjects.visEditor.clickGo(); }; - before(async function() { + before(async function () { await security.testUser.setRoles([ 'kibana_admin', 'long_window_logstash', @@ -70,35 +70,35 @@ export default function({ getService, getPageObjects }) { await initAreaChart(); }); - after(async function() { + after(async function () { await security.testUser.restoreDefaults(); }); - it('should save and load with special characters', async function() { + it('should save and load with special characters', async function () { const vizNamewithSpecialChars = vizName1 + '/?&=%'; await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb( vizNamewithSpecialChars ); }); - it('should save and load with non-ascii characters', async function() { + it('should save and load with non-ascii characters', async function () { const vizNamewithSpecialChars = `${vizName1} with Umlaut ä`; await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb( vizNamewithSpecialChars ); }); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct chart', async function() { + it('should show correct chart', async function () { const xAxisLabels = [ '2015-09-20 00:00', '2015-09-21 00:00', @@ -147,7 +147,7 @@ export default function({ getService, getPageObjects }) { expect(paths).to.eql(expectedAreaChartData); }); - it('should show correct data', async function() { + it('should show correct data', async function () { const expectedTableData = [ ['2015-09-20 00:00', '37'], ['2015-09-20 03:00', '202'], @@ -295,10 +295,7 @@ export default function({ getService, getPageObjects }) { after(async () => { const url = await browser.getCurrentUrl(); - const embedUrl = url - .split('/visualize#') - .pop() - .replace('embed=true', ''); + const embedUrl = url.split('/visualize#').pop().replace('embed=true', ''); await PageObjects.common.navigateToUrl('visualize', embedUrl, { useActualUrl: true }); }); }); diff --git a/test/functional/apps/visualize/_chart_types.ts b/test/functional/apps/visualize/_chart_types.ts index b69ed3fff3ebb..8aa8b9c32e967 100644 --- a/test/functional/apps/visualize/_chart_types.ts +++ b/test/functional/apps/visualize/_chart_types.ts @@ -22,19 +22,19 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const log = getService('log'); const PageObjects = getPageObjects(['common', 'visualize']); let isOss = true; - describe('chart types', function() { - before(async function() { + describe('chart types', function () { + before(async function () { log.debug('navigateToApp visualize'); isOss = await PageObjects.common.isOss(); await PageObjects.visualize.navigateToNewVisualization(); }); - it('should show the correct chart types', async function() { + it('should show the correct chart types', async function () { let expectedChartTypes = [ 'Area', 'Controls', @@ -57,10 +57,10 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { ]; if (!isOss) { expectedChartTypes.push('Maps', 'Lens'); - expectedChartTypes = _.remove(expectedChartTypes, function(n) { + expectedChartTypes = _.remove(expectedChartTypes, function (n) { return n !== 'Coordinate Map'; }); - expectedChartTypes = _.remove(expectedChartTypes, function(n) { + expectedChartTypes = _.remove(expectedChartTypes, function (n) { return n !== 'Region Map'; }); expectedChartTypes.sort(); diff --git a/test/functional/apps/visualize/_data_table.js b/test/functional/apps/visualize/_data_table.js index ec0d2f0579ccc..a1389a69666ae 100644 --- a/test/functional/apps/visualize/_data_table.js +++ b/test/functional/apps/visualize/_data_table.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const inspector = getService('inspector'); const testSubjects = getService('testSubjects'); @@ -30,7 +30,7 @@ export default function({ getService, getPageObjects }) { describe('data table', function indexPatternCreation() { const vizName1 = 'Visualization DataTable'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickDataTable'); @@ -63,18 +63,18 @@ export default function({ getService, getPageObjects }) { expect(interval).to.be('2000'); }); - it('should be able to save and load', async function() { + it('should be able to save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct data', function() { + it('should show correct data', function () { const expectedChartData = [ ['0B', '2,088'], ['1.953KB', '2,748'], @@ -88,7 +88,7 @@ export default function({ getService, getPageObjects }) { ['17.578KB', '137'], ]; - return retry.try(async function() { + return retry.try(async function () { await inspector.open(); await inspector.expectTableData(expectedChartData); await inspector.close(); diff --git a/test/functional/apps/visualize/_data_table_nontimeindex.js b/test/functional/apps/visualize/_data_table_nontimeindex.js index 3db3cd094a81b..4ae66d14ec30d 100644 --- a/test/functional/apps/visualize/_data_table_nontimeindex.js +++ b/test/functional/apps/visualize/_data_table_nontimeindex.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const inspector = getService('inspector'); const retry = getService('retry'); @@ -30,7 +30,7 @@ export default function({ getService, getPageObjects }) { describe.skip('data table with index without time filter', function indexPatternCreation() { const vizName1 = 'Visualization DataTable without time filter'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickDataTable'); @@ -64,18 +64,18 @@ export default function({ getService, getPageObjects }) { expect(interval).to.be('2000'); }); - it('should be able to save and load', async function() { + it('should be able to save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct data', function() { + it('should show correct data', function () { const expectedChartData = [ ['0B', '2,088'], ['1.953KB', '2,748'], @@ -89,7 +89,7 @@ export default function({ getService, getPageObjects }) { ['17.578KB', '137'], ]; - return retry.try(async function() { + return retry.try(async function () { await inspector.open(); await inspector.expectTableData(expectedChartData); await inspector.close(); diff --git a/test/functional/apps/visualize/_data_table_notimeindex_filters.ts b/test/functional/apps/visualize/_data_table_notimeindex_filters.ts index eb83e80e2bbe1..9fb6d793eb7d9 100644 --- a/test/functional/apps/visualize/_data_table_notimeindex_filters.ts +++ b/test/functional/apps/visualize/_data_table_notimeindex_filters.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const log = getService('log'); const filterBar = getService('filterBar'); const renderable = getService('renderable'); @@ -38,7 +38,7 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { describe('data table with index without time filter filters', function indexPatternCreation() { const vizName1 = 'Visualization DataTable w/o time filter'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickDataTable'); @@ -58,7 +58,7 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { await PageObjects.visEditor.clickGo(); }); - it('should be able to save and load', async function() { + it('should be able to save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); @@ -71,7 +71,7 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { }); // test to cover bug #54548 - add this visualization to a dashboard and filter - it('should add to dashboard and allow filtering', async function() { + it('should add to dashboard and allow filtering', async function () { await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.clickNewDashboard(); await dashboardAddPanel.addVisualization(vizName1); diff --git a/test/functional/apps/visualize/_embedding_chart.js b/test/functional/apps/visualize/_embedding_chart.js index 940aa3eb5d462..5316bf51fd48c 100644 --- a/test/functional/apps/visualize/_embedding_chart.js +++ b/test/functional/apps/visualize/_embedding_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const filterBar = getService('filterBar'); const log = getService('log'); const renderable = getService('renderable'); @@ -34,7 +34,7 @@ export default function({ getService, getPageObjects }) { describe('embedding', () => { describe('a data table', () => { - before(async function() { + before(async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickDataTable(); await PageObjects.visualize.clickNewSearch(); diff --git a/test/functional/apps/visualize/_experimental_vis.js b/test/functional/apps/visualize/_experimental_vis.js index 22d36d671cb68..e87a36434b231 100644 --- a/test/functional/apps/visualize/_experimental_vis.js +++ b/test/functional/apps/visualize/_experimental_vis.js @@ -23,7 +23,7 @@ export default ({ getService, getPageObjects }) => { const log = getService('log'); const PageObjects = getPageObjects(['visualize']); - describe('experimental visualizations in visualize app ', function() { + describe('experimental visualizations in visualize app ', function () { describe('experimental visualizations', () => { beforeEach(async () => { log.debug('navigateToApp visualize'); diff --git a/test/functional/apps/visualize/_gauge_chart.js b/test/functional/apps/visualize/_gauge_chart.js index d7a30f39250f3..aa94e596319c2 100644 --- a/test/functional/apps/visualize/_gauge_chart.js +++ b/test/functional/apps/visualize/_gauge_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const inspector = getService('inspector'); @@ -39,11 +39,11 @@ export default function({ getService, getPageObjects }) { before(initGaugeVis); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show Count', function() { + it('should show Count', function () { const expectedCount = ['14,004', 'Count']; // initial metric of "Count" is selected by default @@ -53,7 +53,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Split Gauges', async function() { + it('should show Split Gauges', async function () { log.debug('Bucket = Split Group'); await PageObjects.visEditor.clickBucket('Split group'); log.debug('Aggregation = Terms'); @@ -78,7 +78,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show correct values for fields with fieldFormatters', async function() { + it('should show correct values for fields with fieldFormatters', async function () { const expectedTexts = ['2,904', 'win 8: Count', '0B', 'win 8: Min bytes']; await PageObjects.visEditor.selectAggregation('Terms'); @@ -95,7 +95,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should format the metric correctly in percentage mode', async function() { + it('should format the metric correctly in percentage mode', async function () { await initGaugeVis(); await PageObjects.visEditor.clickMetricEditor(); await PageObjects.visEditor.selectAggregation('Average', 'metrics'); diff --git a/test/functional/apps/visualize/_heatmap_chart.js b/test/functional/apps/visualize/_heatmap_chart.js index 842599fa1d0a1..98a0104629c85 100644 --- a/test/functional/apps/visualize/_heatmap_chart.js +++ b/test/functional/apps/visualize/_heatmap_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const inspector = getService('inspector'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); @@ -27,7 +27,7 @@ export default function({ getService, getPageObjects }) { describe('heatmap chart', function indexPatternCreation() { const vizName1 = 'Visualization HeatmapChart'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickHeatmapChart'); @@ -44,18 +44,18 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); }); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct data', async function() { + it('should show correct data', async function () { // this is only the first page of the tabular data. const expectedChartData = [ ['2015-09-20 00:00', '37'], @@ -85,13 +85,13 @@ export default function({ getService, getPageObjects }) { await inspector.close(); }); - it('should show 4 color ranges as default colorNumbers param', async function() { + it('should show 4 color ranges as default colorNumbers param', async function () { const legends = await PageObjects.visChart.getLegendEntries(); const expectedLegends = ['0 - 400', '400 - 800', '800 - 1,200', '1,200 - 1,600']; expect(legends).to.eql(expectedLegends); }); - it('should show 6 color ranges if changed on options', async function() { + it('should show 6 color ranges if changed on options', async function () { await PageObjects.visEditor.clickOptionsTab(); await PageObjects.visEditor.changeHeatmapColorNumbers(6); await PageObjects.visEditor.clickGo(); @@ -108,7 +108,7 @@ export default function({ getService, getPageObjects }) { ]; expect(legends).to.eql(expectedLegends); }); - it('should show 6 custom color ranges', async function() { + it('should show 6 custom color ranges', async function () { await PageObjects.visEditor.clickOptionsTab(); await PageObjects.visEditor.clickEnableCustomRanges(); await PageObjects.visEditor.clickAddRange(); diff --git a/test/functional/apps/visualize/_histogram_request_start.js b/test/functional/apps/visualize/_histogram_request_start.js index a74fa8856a3b3..f6440cfbd76ff 100644 --- a/test/functional/apps/visualize/_histogram_request_start.js +++ b/test/functional/apps/visualize/_histogram_request_start.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const PageObjects = getPageObjects([ @@ -30,8 +30,8 @@ export default function({ getService, getPageObjects }) { 'timePicker', ]); - describe('histogram agg onSearchRequestStart', function() { - before(async function() { + describe('histogram agg onSearchRequestStart', function () { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickDataTable'); @@ -46,8 +46,8 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.selectField('machine.ram'); }); - describe('interval parameter uses autoBounds', function() { - it('should use provided value when number of generated buckets is less than histogram:maxBars', async function() { + describe('interval parameter uses autoBounds', function () { + it('should use provided value when number of generated buckets is less than histogram:maxBars', async function () { const providedInterval = 2400000000; log.debug(`Interval = ${providedInterval}`); await PageObjects.visEditor.setInterval(providedInterval, { type: 'numeric' }); @@ -63,7 +63,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should scale value to round number when number of generated buckets is greater than histogram:maxBars', async function() { + it('should scale value to round number when number of generated buckets is greater than histogram:maxBars', async function () { const providedInterval = 100; log.debug(`Interval = ${providedInterval}`); await PageObjects.visEditor.setInterval(providedInterval, { type: 'numeric' }); diff --git a/test/functional/apps/visualize/_inspector.js b/test/functional/apps/visualize/_inspector.js index 256c0362226e5..104184050e838 100644 --- a/test/functional/apps/visualize/_inspector.js +++ b/test/functional/apps/visualize/_inspector.js @@ -17,14 +17,14 @@ * under the License. */ -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const inspector = getService('inspector'); const filterBar = getService('filterBar'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); describe('inspector', function describeIndexTests() { - before(async function() { + before(async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVerticalBarChart(); await PageObjects.visualize.clickNewSearch(); @@ -33,7 +33,7 @@ export default function({ getService, getPageObjects }) { }); describe('inspector table', function indexPatternCreation() { - it('should update table header when columns change', async function() { + it('should update table header when columns change', async function () { await inspector.open(); await inspector.expectTableHeaders(['Count']); await inspector.close(); @@ -48,8 +48,8 @@ export default function({ getService, getPageObjects }) { await inspector.close(); }); - describe('filtering on inspector table values', function() { - before(async function() { + describe('filtering on inspector table values', function () { + before(async function () { log.debug('Add X-axis terms agg on machine.os.raw'); await PageObjects.visEditor.clickBucket('X-axis'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -59,18 +59,18 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); }); - beforeEach(async function() { + beforeEach(async function () { await inspector.open(); await PageObjects.visChart.waitForVisualizationRenderingStabilized(); }); - afterEach(async function() { + afterEach(async function () { await inspector.close(); await filterBar.removeFilter('machine.os.raw'); await PageObjects.visChart.waitForVisualizationRenderingStabilized(); }); - it('should allow filtering for values', async function() { + it('should allow filtering for values', async function () { await inspector.expectTableData([ ['win 8', '2,904', '13,031,579,645.108'], ['win xp', '2,858', '13,073,190,186.423'], @@ -81,7 +81,7 @@ export default function({ getService, getPageObjects }) { await inspector.expectTableData([['win 8', '2,904', '13,031,579,645.108']]); }); - it('should allow filtering out values', async function() { + it('should allow filtering out values', async function () { await inspector.filterOutTableCell(1, 1); await inspector.expectTableData([ ['win xp', '2,858', '13,073,190,186.423'], @@ -90,7 +90,7 @@ export default function({ getService, getPageObjects }) { ]); }); - it('should allow filtering for other values', async function() { + it('should allow filtering for other values', async function () { await inspector.filterForTableCell(1, 3); await inspector.expectTableData([ ['win 7', '2,814', '13,186,695,551.251'], @@ -99,7 +99,7 @@ export default function({ getService, getPageObjects }) { ]); }); - it('should allow filtering out other values', async function() { + it('should allow filtering out other values', async function () { await inspector.filterOutTableCell(1, 3); await inspector.expectTableData([ ['win 8', '2,904', '13,031,579,645.108'], diff --git a/test/functional/apps/visualize/_lab_mode.js b/test/functional/apps/visualize/_lab_mode.js index 73a23e5535918..b356d01cdb63b 100644 --- a/test/functional/apps/visualize/_lab_mode.js +++ b/test/functional/apps/visualize/_lab_mode.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const PageObjects = getPageObjects(['common', 'header', 'discover', 'settings']); diff --git a/test/functional/apps/visualize/_line_chart.js b/test/functional/apps/visualize/_line_chart.js index e8be1bf4c41c4..5c510617fbb01 100644 --- a/test/functional/apps/visualize/_line_chart.js +++ b/test/functional/apps/visualize/_line_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const inspector = getService('inspector'); const retry = getService('retry'); @@ -32,10 +32,10 @@ export default function({ getService, getPageObjects }) { 'timePicker', ]); - describe('line charts', function() { + describe('line charts', function () { const vizName1 = 'Visualization LineChart'; - const initLineChart = async function() { + const initLineChart = async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickLineChart'); @@ -59,7 +59,7 @@ export default function({ getService, getPageObjects }) { await inspector.close(); }); - it('should show correct chart', async function() { + it('should show correct chart', async function () { // this test only verifies the numerical part of this data // it could also check the legend to verify the extensions const expectedChartData = ['jpg 9,109', 'css 2,159', 'png 1,373', 'gif 918', 'php 445']; @@ -87,11 +87,11 @@ export default function({ getService, getPageObjects }) { log.debug('Done'); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct chart order by Term', async function() { + it('should show correct chart order by Term', async function () { // this test only verifies the numerical part of this data // it could also check the legend to verify the extensions const expectedChartData = ['png 1,373', 'php 445', 'jpg 9,109', 'gif 918', 'css 2,159']; @@ -99,7 +99,7 @@ export default function({ getService, getPageObjects }) { log.debug('Order By = Term'); await PageObjects.visEditor.selectOrderByMetric(2, '_key'); await PageObjects.visEditor.clickGo(); - await retry.try(async function() { + await retry.try(async function () { const data = await PageObjects.visChart.getLineChartData(); log.debug('data=' + data); const tolerance = 10; // the y-axis scale is 10000 so 10 is 0.1% @@ -122,7 +122,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show correct data, ordered by Term', async function() { + it('should show correct data, ordered by Term', async function () { const expectedChartData = [ ['png', '1,373'], ['php', '445'], @@ -150,7 +150,7 @@ export default function({ getService, getPageObjects }) { await inspector.open(); await inspector.openInspectorRequestsView(); const requestStatsBefore = await inspector.getTableData(); - const requestTimestampBefore = requestStatsBefore.filter(r => + const requestTimestampBefore = requestStatsBefore.filter((r) => r[0].includes('Request timestamp') )[0][1]; @@ -159,7 +159,7 @@ export default function({ getService, getPageObjects }) { // get the latest timestamp from request stats const requestStatsAfter = await inspector.getTableData(); - const requestTimestampAfter = requestStatsAfter.filter(r => + const requestTimestampAfter = requestStatsAfter.filter((r) => r[0].includes('Request timestamp') )[0][1]; log.debug( @@ -174,7 +174,7 @@ export default function({ getService, getPageObjects }) { expect(requestTimestampBefore).not.to.equal(requestTimestampAfter); }); - it('should be able to save and load', async function() { + it('should be able to save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); diff --git a/test/functional/apps/visualize/_linked_saved_searches.ts b/test/functional/apps/visualize/_linked_saved_searches.ts index ea42f7c671985..b0edcb68f3efc 100644 --- a/test/functional/apps/visualize/_linked_saved_searches.ts +++ b/test/functional/apps/visualize/_linked_saved_searches.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const filterBar = getService('filterBar'); const retry = getService('retry'); const PageObjects = getPageObjects([ diff --git a/test/functional/apps/visualize/_markdown_vis.js b/test/functional/apps/visualize/_markdown_vis.js index 649fe0a8e4c2e..21b472edecd41 100644 --- a/test/functional/apps/visualize/_markdown_vis.js +++ b/test/functional/apps/visualize/_markdown_vis.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getPageObjects, getService }) { +export default function ({ getPageObjects, getService }) { const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'header']); const find = getService('find'); const inspector = getService('inspector'); @@ -30,7 +30,7 @@ export default function({ getPageObjects, getService }) { `; describe('markdown app in visualize app', () => { - before(async function() { + before(async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickMarkdownWidget(); await PageObjects.visEditor.setMarkdownTxt(markdown); @@ -38,22 +38,22 @@ export default function({ getPageObjects, getService }) { }); describe('markdown vis', () => { - it('should not have inspector enabled', async function() { + it('should not have inspector enabled', async function () { await inspector.expectIsNotEnabled(); }); - it('should render markdown as html', async function() { + it('should render markdown as html', async function () { const h1Txt = await PageObjects.visChart.getMarkdownBodyDescendentText('h1'); expect(h1Txt).to.equal('Heading 1'); }); - it('should not render html in markdown as html', async function() { + it('should not render html in markdown as html', async function () { const expected = 'Heading 1\n

    Inline HTML that should not be rendered as html

    '; const actual = await PageObjects.visChart.getMarkdownText(); expect(actual).to.equal(expected); }); - it('should auto apply changes if auto mode is turned on', async function() { + it('should auto apply changes if auto mode is turned on', async function () { const markdown2 = '## Heading 2'; await PageObjects.visEditor.toggleAutoMode(); await PageObjects.visEditor.setMarkdownTxt(markdown2); @@ -62,7 +62,7 @@ export default function({ getPageObjects, getService }) { expect(h1Txt).to.equal('Heading 2'); }); - it('should resize the editor', async function() { + it('should resize the editor', async function () { const editorSidebar = await find.byCssSelector('.visEditor__collapsibleSidebar'); const initialSize = await editorSidebar.getSize(); await PageObjects.visEditor.sizeUpEditor(); diff --git a/test/functional/apps/visualize/_metric_chart.js b/test/functional/apps/visualize/_metric_chart.js index dab9d2213b764..e02dac11d9e98 100644 --- a/test/functional/apps/visualize/_metric_chart.js +++ b/test/functional/apps/visualize/_metric_chart.js @@ -19,15 +19,15 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const filterBar = getService('filterBar'); const inspector = getService('inspector'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); - describe('metric chart', function() { - before(async function() { + describe('metric chart', function () { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickMetric'); @@ -36,11 +36,11 @@ export default function({ getService, getPageObjects }) { await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show Count', async function() { + it('should show Count', async function () { const expectedCount = ['14,004', 'Count']; // initial metric of "Count" is selected by default @@ -50,7 +50,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Average', async function() { + it('should show Average', async function () { const avgMachineRam = ['13,104,036,080.615', 'Average machine.ram']; await PageObjects.visEditor.clickMetricEditor(); log.debug('Aggregation = Average'); @@ -64,7 +64,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Sum', async function() { + it('should show Sum', async function () { const sumPhpMemory = ['85,865,880', 'Sum of phpmemory']; log.debug('Aggregation = Sum'); await PageObjects.visEditor.selectAggregation('Sum', 'metrics'); @@ -77,7 +77,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Median', async function() { + it('should show Median', async function () { const medianBytes = ['5,565.263', 'Median bytes']; // For now, only comparing the text label part of the metric log.debug('Aggregation = Median'); @@ -92,7 +92,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Min', async function() { + it('should show Min', async function () { const minTimestamp = ['Sep 20, 2015 @ 00:00:00.000', 'Min @timestamp']; log.debug('Aggregation = Min'); await PageObjects.visEditor.selectAggregation('Min', 'metrics'); @@ -105,7 +105,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Max', async function() { + it('should show Max', async function () { const maxRelatedContentArticleModifiedTime = [ 'Apr 4, 2015 @ 00:54:41.000', 'Max relatedContent.article:modified_time', @@ -121,7 +121,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Unique Count', async function() { + it('should show Unique Count', async function () { const uniqueCountClientip = ['1,000', 'Unique count of clientip']; log.debug('Aggregation = Unique Count'); await PageObjects.visEditor.selectAggregation('Unique Count', 'metrics'); @@ -134,7 +134,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Percentiles', async function() { + it('should show Percentiles', async function () { const percentileMachineRam = [ '2,147,483,648', '1st percentile of machine.ram', @@ -163,7 +163,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show Percentile Ranks', async function() { + it('should show Percentile Ranks', async function () { const percentileRankBytes = ['2.036%', 'Percentile rank 99 of "memory"']; log.debug('Aggregation = Percentile Ranks'); await PageObjects.visEditor.selectAggregation('Percentile Ranks', 'metrics'); @@ -178,8 +178,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('with filters', function() { - it('should prevent filtering without buckets', async function() { + describe('with filters', function () { + it('should prevent filtering without buckets', async function () { let filterCount = 0; await retry.try(async function tryingForTime() { // click first metric bucket @@ -189,7 +189,7 @@ export default function({ getService, getPageObjects }) { expect(filterCount).to.equal(0); }); - it('should allow filtering with buckets', async function() { + it('should allow filtering with buckets', async function () { log.debug('Bucket = Split Group'); await PageObjects.visEditor.clickBucket('Split group'); log.debug('Aggregation = Terms'); diff --git a/test/functional/apps/visualize/_pie_chart.js b/test/functional/apps/visualize/_pie_chart.js index 313a4e39e5030..b68a88c4f97f3 100644 --- a/test/functional/apps/visualize/_pie_chart.js +++ b/test/functional/apps/visualize/_pie_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const filterBar = getService('filterBar'); const pieChart = getService('pieChart'); @@ -33,9 +33,9 @@ export default function({ getService, getPageObjects }) { 'timePicker', ]); - describe('pie chart', function() { + describe('pie chart', function () { const vizName1 = 'Visualization PieChart'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickPieChart'); @@ -56,22 +56,22 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); }); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show 10 slices in pie chart', async function() { + it('should show 10 slices in pie chart', async function () { pieChart.expectPieSliceCount(10); }); - it('should show correct data', async function() { + it('should show correct data', async function () { const expectedTableData = [ ['0', '55'], ['40,000', '50'], @@ -91,7 +91,7 @@ export default function({ getService, getPageObjects }) { }); describe('other bucket', () => { - it('should show other and missing bucket', async function() { + it('should show other and missing bucket', async function () { const expectedTableData = ['win 8', 'win xp', 'win 7', 'ios', 'Missing', 'Other']; await PageObjects.visualize.navigateToNewVisualization(); @@ -291,7 +291,7 @@ export default function({ getService, getPageObjects }) { }); describe('empty time window', () => { - it('should show no data message when no data on selected timerange', async function() { + it('should show no data message when no data on selected timerange', async function () { await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickPieChart'); await PageObjects.visualize.clickPieChart(); @@ -442,7 +442,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.visChart.waitForVisualization(); }); - it('should still showing pie chart when a subseries have zero data', async function() { + it('should still showing pie chart when a subseries have zero data', async function () { await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickPieChart'); await PageObjects.visualize.clickPieChart(); diff --git a/test/functional/apps/visualize/_point_series_options.js b/test/functional/apps/visualize/_point_series_options.js index b31e39849d9ba..d08bfe3b90913 100644 --- a/test/functional/apps/visualize/_point_series_options.js +++ b/test/functional/apps/visualize/_point_series_options.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const kibanaServer = getService('kibanaServer'); @@ -70,8 +70,8 @@ export default function({ getService, getPageObjects }) { describe('point series', function describeIndexTests() { before(initChart); - describe('secondary value axis', function() { - it('should show correct chart', async function() { + describe('secondary value axis', function () { + it('should show correct chart', async function () { const expectedChartValues = [ [ 37, @@ -148,14 +148,14 @@ export default function({ getService, getPageObjects }) { }); }); - it('should put secondary axis on the right', async function() { + it('should put secondary axis on the right', async function () { const length = await PageObjects.visChart.getRightValueAxes(); expect(length).to.be(1); }); }); - describe('multiple chart types', function() { - it('should change average series type to histogram', async function() { + describe('multiple chart types', function () { + it('should change average series type to histogram', async function () { await PageObjects.visEditor.setSeriesType(1, 'histogram'); await PageObjects.visEditor.clickGo(); const length = await PageObjects.visChart.getHistogramSeries(); @@ -163,28 +163,28 @@ export default function({ getService, getPageObjects }) { }); }); - describe('grid lines', function() { - before(async function() { + describe('grid lines', function () { + before(async function () { await PageObjects.visEditor.clickOptionsTab(); }); - it('should show category grid lines', async function() { + it('should show category grid lines', async function () { await PageObjects.visEditor.toggleGridCategoryLines(); await PageObjects.visEditor.clickGo(); const gridLines = await PageObjects.visChart.getGridLines(); expect(gridLines.length).to.be(9); - gridLines.forEach(gridLine => { + gridLines.forEach((gridLine) => { expect(gridLine.y).to.be(0); }); }); - it('should show value axis grid lines', async function() { + it('should show value axis grid lines', async function () { await PageObjects.visEditor.setGridValueAxis('ValueAxis-2'); await PageObjects.visEditor.toggleGridCategoryLines(); await PageObjects.visEditor.clickGo(); const gridLines = await PageObjects.visChart.getGridLines(); expect(gridLines.length).to.be(9); - gridLines.forEach(gridLine => { + gridLines.forEach((gridLine) => { expect(gridLine.x).to.be(0); }); }); @@ -222,11 +222,11 @@ export default function({ getService, getPageObjects }) { }); }); - describe('custom labels and axis titles', function() { + describe('custom labels and axis titles', function () { const visName = 'Visualization Point Series Test'; const customLabel = 'myLabel'; const axisTitle = 'myTitle'; - before(async function() { + before(async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickLineChart(); await PageObjects.visualize.clickNewSearch(); @@ -236,19 +236,19 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickYAxisOptions('ValueAxis-1'); }); - it('should render a custom label when one is set', async function() { + it('should render a custom label when one is set', async function () { const title = await PageObjects.visChart.getYAxisTitle(); expect(title).to.be(customLabel); }); - it('should render a custom axis title when one is set, overriding the custom label', async function() { + it('should render a custom axis title when one is set, overriding the custom label', async function () { await PageObjects.visEditor.setAxisTitle(axisTitle); await PageObjects.visEditor.clickGo(); const title = await PageObjects.visChart.getYAxisTitle(); expect(title).to.be(axisTitle); }); - it('should preserve saved axis titles after a vis is saved and reopened', async function() { + it('should preserve saved axis titles after a vis is saved and reopened', async function () { await PageObjects.visualize.saveVisualizationExpectSuccess(visName); await PageObjects.visChart.waitForVisualization(); await PageObjects.visualize.loadSavedVisualization(visName); @@ -264,16 +264,16 @@ export default function({ getService, getPageObjects }) { }); }); - describe('timezones', function() { + describe('timezones', function () { const expectedLabels = ['2015-09-20 00:00', '2015-09-21 00:00', '2015-09-22 00:00']; - it('should show round labels in default timezone', async function() { + it('should show round labels in default timezone', async function () { await initChart(); const labels = await PageObjects.visChart.getXAxisLabels(); expect(labels.join()).to.contain(expectedLabels.join()); }); - it('should show round labels in different timezone', async function() { + it('should show round labels in different timezone', async function () { await kibanaServer.uiSettings.replace({ 'dateFormat:tz': 'America/Phoenix' }); await browser.refresh(); await PageObjects.header.awaitKibanaChrome(); @@ -284,7 +284,7 @@ export default function({ getService, getPageObjects }) { expect(labels.join()).to.contain(expectedLabels.join()); }); - it('should show different labels in different timezone', async function() { + it('should show different labels in different timezone', async function () { const fromTime = 'Sep 22, 2015 @ 09:05:47.415'; const toTime = 'Sep 22, 2015 @ 16:08:34.554'; // note that we're setting the absolute time range while we're in 'America/Phoenix' tz diff --git a/test/functional/apps/visualize/_region_map.js b/test/functional/apps/visualize/_region_map.js index 2467a54061643..f2fe1527c97c2 100644 --- a/test/functional/apps/visualize/_region_map.js +++ b/test/functional/apps/visualize/_region_map.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { - describe('vector map', function() { +export default function ({ getService, getPageObjects }) { + describe('vector map', function () { const inspector = getService('inspector'); const log = getService('log'); const find = getService('find'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'timePicker']); - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickRegionMap'); @@ -43,11 +43,11 @@ export default function({ getService, getPageObjects }) { }); describe('vector map', function indexPatternCreation() { - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show results after clicking play (join on states)', async function() { + it('should show results after clicking play (join on states)', async function () { const expectedData = [ ['CN', '2,592'], ['IN', '2,373'], @@ -60,7 +60,7 @@ export default function({ getService, getPageObjects }) { await inspector.close(); }); - it('should change results after changing layer to world', async function() { + it('should change results after changing layer to world', async function () { await PageObjects.visEditor.clickOptionsTab(); await PageObjects.visEditor.setSelectByOptionText( 'regionMapOptionsSelectLayer', @@ -104,7 +104,7 @@ export default function({ getService, getPageObjects }) { const $ = await selectField.parseDomContent(); const optionsText = $('option') .toArray() - .map(option => $(option).text()); + .map((option) => $(option).text()); expect(optionsText.includes('road_map')).to.be(true); }); diff --git a/test/functional/apps/visualize/_shared_item.js b/test/functional/apps/visualize/_shared_item.js index da7583112f45f..0efe05caf9b3b 100644 --- a/test/functional/apps/visualize/_shared_item.js +++ b/test/functional/apps/visualize/_shared_item.js @@ -19,25 +19,25 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const PageObjects = getPageObjects(['common', 'visualize']); describe('data-shared-item', function indexPatternCreation() { - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.common.navigateToApp('visualize'); }); - it('should have the correct data-shared-item title and description, and sharedItemContainer should exist', async function() { + it('should have the correct data-shared-item title and description, and sharedItemContainer should exist', async function () { const expected = { title: 'Shared-Item Visualization AreaChart', description: 'AreaChart', }; await PageObjects.visualize.clickVisualizationByName('Shared-Item Visualization AreaChart'); - await retry.try(async function() { + await retry.try(async function () { const { title, description } = await PageObjects.common.getSharedItemTitleAndDescription(); expect(title).to.eql(expected.title); expect(description).to.eql(expected.description); diff --git a/test/functional/apps/visualize/_tag_cloud.js b/test/functional/apps/visualize/_tag_cloud.js index a527e9bcad42f..b5c575edb8a0a 100644 --- a/test/functional/apps/visualize/_tag_cloud.js +++ b/test/functional/apps/visualize/_tag_cloud.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const filterBar = getService('filterBar'); const log = getService('log'); const inspector = getService('inspector'); @@ -37,11 +37,11 @@ export default function({ getService, getPageObjects }) { 'tagCloud', ]); - describe('tag cloud chart', function() { + describe('tag cloud chart', function () { const vizName1 = 'Visualization tagCloud'; const termsField = 'machine.ram'; - before(async function() { + before(async function () { log.debug('navigateToApp visualize'); await PageObjects.visualize.navigateToNewVisualization(); log.debug('clickTagCloud'); @@ -60,11 +60,11 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct tag cloud data', async function() { + it('should show correct tag cloud data', async function () { const data = await PageObjects.tagCloud.getTextTag(); log.debug(data); expect(data).to.eql([ @@ -76,7 +76,7 @@ export default function({ getService, getPageObjects }) { ]); }); - it('should collapse the sidebar', async function() { + it('should collapse the sidebar', async function () { const editorSidebar = await find.byCssSelector('.visEditorSidebar'); await PageObjects.visEditor.clickEditorSidebarCollapse(); // Give d3 tag cloud some time to rearrange tags @@ -86,7 +86,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickEditorSidebarCollapse(); }); - it('should still show all tags after sidebar has been collapsed', async function() { + it('should still show all tags after sidebar has been collapsed', async function () { await PageObjects.visEditor.clickEditorSidebarCollapse(); // Give d3 tag cloud some time to rearrange tags await PageObjects.common.sleep(1000); @@ -104,7 +104,7 @@ export default function({ getService, getPageObjects }) { ]); }); - it('should still show all tags after browser was resized very small', async function() { + it('should still show all tags after browser was resized very small', async function () { await browser.setWindowSize(200, 200); await PageObjects.common.sleep(1000); await browser.setWindowSize(1200, 800); @@ -119,21 +119,21 @@ export default function({ getService, getPageObjects }) { ]); }); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should show the tags and relative size', function() { - return PageObjects.tagCloud.getTextSizes().then(function(results) { + it('should show the tags and relative size', function () { + return PageObjects.tagCloud.getTextSizes().then(function (results) { log.debug('results here ' + results); expect(results).to.eql(['72px', '63px', '25px', '32px', '18px']); }); }); - it('should show correct data', async function() { + it('should show correct data', async function () { const expectedTableData = [ ['32,212,254,720', '737'], ['21,474,836,480', '728'], @@ -147,8 +147,8 @@ export default function({ getService, getPageObjects }) { await inspector.expectTableData(expectedTableData); }); - describe('formatted field', function() { - before(async function() { + describe('formatted field', function () { + before(async function () { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); await PageObjects.settings.clickIndexPatternLogstash(); @@ -165,7 +165,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.visChart.waitForVisualization(); }); - after(async function() { + after(async function () { await filterBar.removeFilter(termsField); await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaIndexPatterns(); @@ -176,13 +176,13 @@ export default function({ getService, getPageObjects }) { await PageObjects.settings.controlChangeSave(); }); - it('should format tags with field formatter', async function() { + it('should format tags with field formatter', async function () { const data = await PageObjects.tagCloud.getTextTag(); log.debug(data); expect(data).to.eql(['30GB', '20GB', '19GB', '18GB', '17GB']); }); - it('should apply filter with unformatted value', async function() { + it('should apply filter with unformatted value', async function () { await PageObjects.tagCloud.selectTagCloudTag('30GB'); await PageObjects.header.waitUntilLoadingHasFinished(); const data = await PageObjects.tagCloud.getTextTag(); diff --git a/test/functional/apps/visualize/_tile_map.js b/test/functional/apps/visualize/_tile_map.js index eefd5c6c8a8af..1a9ac5000b1ba 100644 --- a/test/functional/apps/visualize/_tile_map.js +++ b/test/functional/apps/visualize/_tile_map.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const inspector = getService('inspector'); @@ -35,9 +35,9 @@ export default function({ getService, getPageObjects }) { 'tileMap', ]); - describe('tile map visualize app', function() { + describe('tile map visualize app', function () { describe('incomplete config', function describeIndexTests() { - before(async function() { + before(async function () { await browser.setWindowSize(1280, 1000); log.debug('navigateToApp visualize'); @@ -57,7 +57,7 @@ export default function({ getService, getPageObjects }) { }); describe('complete config', function describeIndexTests() { - before(async function() { + before(async function () { await browser.setWindowSize(1280, 1000); log.debug('navigateToApp visualize'); @@ -84,7 +84,7 @@ export default function({ getService, getPageObjects }) { log.debug('comparing expected: ', expected); log.debug('with actual: ', actual); - const roundedValues = actual.map(row => { + const roundedValues = actual.map((row) => { // Parse last element in each row as JSON and floor the lat/long value const coords = JSON.parse(row[row.length - 1]); row[row.length - 1] = { @@ -98,11 +98,11 @@ export default function({ getService, getPageObjects }) { } describe('tile map chart', function indexPatternCreation() { - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct tile map data on default zoom level', async function() { + it('should show correct tile map data on default zoom level', async function () { const expectedTableData = [ ['-', '9', '5,787', { lat: 37, lon: -104 }], ['-', 'd', '5,600', { lat: 37, lon: -82 }], @@ -123,13 +123,13 @@ export default function({ getService, getPageObjects }) { compareTableData(actualTableData, expectedTableData); }); - it('should not be able to zoom out beyond 0', async function() { + it('should not be able to zoom out beyond 0', async function () { await PageObjects.tileMap.zoomAllTheWayOut(); const enabled = await PageObjects.tileMap.getMapZoomOutEnabled(); expect(enabled).to.be(false); }); - it('Fit data bounds should zoom to level 3', async function() { + it('Fit data bounds should zoom to level 3', async function () { const expectedPrecision2DataTable = [ ['-', 'dr4', '127', { lat: 40, lon: -76 }], ['-', 'dr7', '92', { lat: 41, lon: -74 }], @@ -236,7 +236,7 @@ export default function({ getService, getPageObjects }) { let last = false; const toastDefaultLife = 6000; - before(async function() { + before(async function () { await browser.setWindowSize(1280, 1000); log.debug('navigateToApp visualize'); @@ -254,11 +254,11 @@ export default function({ getService, getPageObjects }) { } }); - beforeEach(async function() { + beforeEach(async function () { await PageObjects.tileMap.clickMapZoomIn(waitForLoading); }); - afterEach(async function() { + afterEach(async function () { if (!last) { await PageObjects.common.sleep(toastDefaultLife); await PageObjects.tileMap.clickMapZoomOut(waitForLoading); diff --git a/test/functional/apps/visualize/_tsvb_chart.ts b/test/functional/apps/visualize/_tsvb_chart.ts index e9cf8235ff3f4..f1c5c916a89bf 100644 --- a/test/functional/apps/visualize/_tsvb_chart.ts +++ b/test/functional/apps/visualize/_tsvb_chart.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const log = getService('log'); const inspector = getService('inspector'); diff --git a/test/functional/apps/visualize/_tsvb_markdown.ts b/test/functional/apps/visualize/_tsvb_markdown.ts index d37404a3d60cb..fae60fe019433 100644 --- a/test/functional/apps/visualize/_tsvb_markdown.ts +++ b/test/functional/apps/visualize/_tsvb_markdown.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getPageObjects, getService }: FtrProviderContext) { +export default function ({ getPageObjects, getService }: FtrProviderContext) { const { visualBuilder, timePicker } = getPageObjects(['visualBuilder', 'timePicker']); const retry = getService('retry'); @@ -30,7 +30,7 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { await visualBuilder.setMarkdownDataVariable('', variableName); await visualBuilder.markdownSwitchSubTab('markdown'); const rerenderedTable = await visualBuilder.getMarkdownTableVariables(); - rerenderedTable.forEach(row => { + rerenderedTable.forEach((row) => { // eslint-disable-next-line no-unused-expressions variableName === 'label' ? expect(row.key).to.include.string(checkedValue) @@ -91,9 +91,9 @@ export default function({ getPageObjects, getService }: FtrProviderContext) { await visualBuilder.enterMarkdown(TABLE); const text = await visualBuilder.getMarkdownText(); - const tableValues = text.split('\n').map(row => row.split(' '))[1]; // [46, 46] + const tableValues = text.split('\n').map((row) => row.split(' '))[1]; // [46, 46] - tableValues.forEach(value => { + tableValues.forEach((value) => { expect(value).to.be.equal(DATA); }); }); diff --git a/test/functional/apps/visualize/_tsvb_table.ts b/test/functional/apps/visualize/_tsvb_table.ts index 5808212559b18..9c21103c85d0b 100644 --- a/test/functional/apps/visualize/_tsvb_table.ts +++ b/test/functional/apps/visualize/_tsvb_table.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getPageObjects }: FtrProviderContext) { +export default function ({ getPageObjects }: FtrProviderContext) { const { visualBuilder, visualize, visChart } = getPageObjects([ 'visualBuilder', 'visualize', diff --git a/test/functional/apps/visualize/_tsvb_time_series.ts b/test/functional/apps/visualize/_tsvb_time_series.ts index ac89c2b55e514..e0d512c1f4861 100644 --- a/test/functional/apps/visualize/_tsvb_time_series.ts +++ b/test/functional/apps/visualize/_tsvb_time_series.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getPageObjects, getService }: FtrProviderContext) { +export default function ({ getPageObjects, getService }: FtrProviderContext) { const { visualize, visualBuilder } = getPageObjects(['visualBuilder', 'visualize']); const retry = getService('retry'); const log = getService('log'); diff --git a/test/functional/apps/visualize/_vega_chart.js b/test/functional/apps/visualize/_vega_chart.js index 7a19bde341cdd..4442e1f969b4b 100644 --- a/test/functional/apps/visualize/_vega_chart.js +++ b/test/functional/apps/visualize/_vega_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['timePicker', 'visualize', 'visChart', 'vegaChart']); const filterBar = getService('filterBar'); const inspector = getService('inspector'); @@ -35,25 +35,21 @@ export default function({ getService, getPageObjects }) { describe('vega chart', () => { describe('initial render', () => { - it('should not have inspector enabled', async function() { + it('should not have inspector enabled', async function () { await inspector.expectIsNotEnabled(); }); - it.skip('should have some initial vega spec text', async function() { + it.skip('should have some initial vega spec text', async function () { const vegaSpec = await PageObjects.vegaChart.getSpec(); - expect(vegaSpec) - .to.contain('{') - .and.to.contain('data'); + expect(vegaSpec).to.contain('{').and.to.contain('data'); expect(vegaSpec.length).to.be.above(500); }); - it('should have view and control containers', async function() { + it('should have view and control containers', async function () { const view = await PageObjects.vegaChart.getViewContainer(); expect(view).to.be.ok(); const size = await view.getSize(); - expect(size) - .to.have.property('width') - .and.to.have.property('height'); + expect(size).to.have.property('width').and.to.have.property('height'); expect(size.width).to.be.above(0); expect(size.height).to.be.above(0); @@ -72,7 +68,7 @@ export default function({ getService, getPageObjects }) { await filterBar.removeAllFilters(); }); - it.skip('should render different data in response to filter change', async function() { + it.skip('should render different data in response to filter change', async function () { await PageObjects.vegaChart.expectVisToMatchScreenshot('vega_chart'); await filterBar.addFilter('@tags.raw', 'is', 'error'); await PageObjects.vegaChart.expectVisToMatchScreenshot('vega_chart_filtered'); diff --git a/test/functional/apps/visualize/_vertical_bar_chart.js b/test/functional/apps/visualize/_vertical_bar_chart.js index 04969a07eef6f..f1d83908b9b6d 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart.js +++ b/test/functional/apps/visualize/_vertical_bar_chart.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const inspector = getService('inspector'); @@ -27,9 +27,9 @@ export default function({ getService, getPageObjects }) { const filterBar = getService('filterBar'); const PageObjects = getPageObjects(['visualize', 'visEditor', 'visChart', 'timePicker']); - describe('vertical bar chart', function() { + describe('vertical bar chart', function () { describe('bar charts x axis tick labels', () => { - it('should show tick labels also after rotation of the chart', async function() { + it('should show tick labels also after rotation of the chart', async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVerticalBarChart(); await PageObjects.visualize.clickNewSearch(); @@ -54,7 +54,7 @@ export default function({ getService, getPageObjects }) { expect(leftLabels.length).to.be.greaterThan(bottomLabels.length * (2 / 3)); }); - it('should not filter out first label after rotation of the chart', async function() { + it('should not filter out first label after rotation of the chart', async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVerticalBarChart(); await PageObjects.visualize.clickNewSearch(); @@ -77,7 +77,7 @@ export default function({ getService, getPageObjects }) { }); describe('bar charts range on x axis', () => { - it('should individual bars for each configured range', async function() { + it('should individual bars for each configured range', async function () { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVerticalBarChart(); await PageObjects.visualize.clickNewSearch(); @@ -96,7 +96,7 @@ export default function({ getService, getPageObjects }) { }); // FLAKY: https://github.com/elastic/kibana/issues/22322 - describe.skip('vertical bar chart flaky part', function() { + describe.skip('vertical bar chart flaky part', function () { const vizName1 = 'Visualization VerticalBarChart'; const initBarChart = async () => { @@ -118,18 +118,18 @@ export default function({ getService, getPageObjects }) { before(initBarChart); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct chart', async function() { + it('should show correct chart', async function () { const expectedChartValues = [ 37, 202, @@ -168,7 +168,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show correct data', async function() { + it('should show correct data', async function () { // this is only the first page of the tabular data. const expectedChartData = [ ['2015-09-20 00:00', '37'], @@ -483,7 +483,7 @@ export default function({ getService, getPageObjects }) { }); describe('vertical bar in percent mode', async () => { - it('should show ticks with percentage values', async function() { + it('should show ticks with percentage values', async function () { const axisId = 'ValueAxis-1'; await PageObjects.visEditor.clickMetricsAndAxes(); await PageObjects.visEditor.clickYAxisOptions(axisId); @@ -497,10 +497,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with Split series', function() { + describe('vertical bar with Split series', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.clickBucket('Split series'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -534,10 +534,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with multiple splits', function() { + describe('vertical bar with multiple splits', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.clickBucket('Split series'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -572,7 +572,7 @@ export default function({ getService, getPageObjects }) { expect(legendEntries).to.eql(expectedEntries); }); - it('should show correct series when disabling first agg', async function() { + it('should show correct series when disabling first agg', async function () { // this will avoid issues with the play tooltip covering the disable agg button await testSubjects.scrollIntoView('metricsAggGroup'); await PageObjects.visEditor.toggleDisabledAgg(3); @@ -584,10 +584,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with derivative', function() { + describe('vertical bar with derivative', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.toggleOpenEditor(1); await PageObjects.visEditor.selectAggregation('Derivative', 'metrics'); diff --git a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js index 2743f6bb38feb..42dfd791321a1 100644 --- a/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js +++ b/test/functional/apps/visualize/_vertical_bar_chart_nontimeindex.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const log = getService('log'); const retry = getService('retry'); const inspector = getService('inspector'); const PageObjects = getPageObjects(['common', 'visualize', 'header', 'visEditor', 'visChart']); // FLAKY: https://github.com/elastic/kibana/issues/22322 - describe.skip('vertical bar chart with index without time filter', function() { + describe.skip('vertical bar chart with index without time filter', function () { const vizName1 = 'Visualization VerticalBarChart without time filter'; const initBarChart = async () => { @@ -50,18 +50,18 @@ export default function({ getService, getPageObjects }) { before(initBarChart); - it('should save and load', async function() { + it('should save and load', async function () { await PageObjects.visualize.saveVisualizationExpectSuccessAndBreadcrumb(vizName1); await PageObjects.visualize.loadSavedVisualization(vizName1); await PageObjects.visChart.waitForVisualization(); }); - it('should have inspector enabled', async function() { + it('should have inspector enabled', async function () { await inspector.expectIsEnabled(); }); - it('should show correct chart', async function() { + it('should show correct chart', async function () { const expectedChartValues = [ 37, 202, @@ -100,7 +100,7 @@ export default function({ getService, getPageObjects }) { }); }); - it('should show correct data', async function() { + it('should show correct data', async function () { // this is only the first page of the tabular data. const expectedChartData = [ ['2015-09-20 00:00', '37'], @@ -248,10 +248,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with split series', function() { + describe('vertical bar with split series', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.clickBucket('Split series'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -268,10 +268,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with multiple splits', function() { + describe('vertical bar with multiple splits', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.clickBucket('Split series'); await PageObjects.visEditor.selectAggregation('Terms'); @@ -309,7 +309,7 @@ export default function({ getService, getPageObjects }) { expect(legendEntries).to.eql(expectedEntries); }); - it('should show correct series when disabling first agg', async function() { + it('should show correct series when disabling first agg', async function () { await PageObjects.visEditor.toggleDisabledAgg(3); await PageObjects.visEditor.clickGo(); await PageObjects.header.waitUntilLoadingHasFinished(); @@ -320,10 +320,10 @@ export default function({ getService, getPageObjects }) { }); }); - describe('vertical bar with derivative', function() { + describe('vertical bar with derivative', function () { before(initBarChart); - it('should show correct series', async function() { + it('should show correct series', async function () { await PageObjects.visEditor.toggleOpenEditor(2, 'false'); await PageObjects.visEditor.toggleOpenEditor(1); await PageObjects.visEditor.selectAggregation('Derivative', 'metrics'); diff --git a/test/functional/apps/visualize/_visualize_listing.js b/test/functional/apps/visualize/_visualize_listing.js index dc07301a8ad50..e7e62cfe424a9 100644 --- a/test/functional/apps/visualize/_visualize_listing.js +++ b/test/functional/apps/visualize/_visualize_listing.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['visualize', 'visEditor']); const listingTable = getService('listingTable'); @@ -25,20 +25,20 @@ export default function({ getService, getPageObjects }) { describe.skip('visualize listing page', function describeIndexTests() { const vizName = 'Visualize Listing Test'; - describe('create and delete', function() { - before(async function() { + describe('create and delete', function () { + before(async function () { await PageObjects.visualize.gotoVisualizationLandingPage(); await PageObjects.visualize.deleteAllVisualizations(); }); - it('create new viz', async function() { + it('create new viz', async function () { // type markdown is used for simplicity await PageObjects.visualize.createSimpleMarkdownViz(vizName); await PageObjects.visualize.gotoVisualizationLandingPage(); await listingTable.expectItemsCount('visualize', 1); }); - it('delete all viz', async function() { + it('delete all viz', async function () { await PageObjects.visualize.createSimpleMarkdownViz(vizName + '1'); await PageObjects.visualize.createSimpleMarkdownViz(vizName + '2'); await PageObjects.visualize.gotoVisualizationLandingPage(); @@ -50,8 +50,8 @@ export default function({ getService, getPageObjects }) { }); }); - describe('search', function() { - before(async function() { + describe('search', function () { + before(async function () { // create one new viz await PageObjects.visualize.gotoVisualizationLandingPage(); await PageObjects.visualize.navigateToNewVisualization(); @@ -62,32 +62,32 @@ export default function({ getService, getPageObjects }) { await PageObjects.visualize.gotoVisualizationLandingPage(); }); - it('matches on the first word', async function() { + it('matches on the first word', async function () { await listingTable.searchForItemWithName('Hello'); await listingTable.expectItemsCount('visualize', 1); }); - it('matches the second word', async function() { + it('matches the second word', async function () { await listingTable.searchForItemWithName('World'); await listingTable.expectItemsCount('visualize', 1); }); - it('matches the second word prefix', async function() { + it('matches the second word prefix', async function () { await listingTable.searchForItemWithName('Wor'); await listingTable.expectItemsCount('visualize', 1); }); - it('does not match mid word', async function() { + it('does not match mid word', async function () { await listingTable.searchForItemWithName('orld'); await listingTable.expectItemsCount('visualize', 0); }); - it('is case insensitive', async function() { + it('is case insensitive', async function () { await listingTable.searchForItemWithName('hello world'); await listingTable.expectItemsCount('visualize', 1); }); - it('is using AND operator', async function() { + it('is using AND operator', async function () { await listingTable.searchForItemWithName('hello banana'); await listingTable.expectItemsCount('visualize', 0); }); diff --git a/test/functional/apps/visualize/index.ts b/test/functional/apps/visualize/index.ts index 06d560530c28a..bd427577cd787 100644 --- a/test/functional/apps/visualize/index.ts +++ b/test/functional/apps/visualize/index.ts @@ -20,7 +20,7 @@ import { FtrProviderContext } from '../../ftr_provider_context.d'; // eslint-disable-next-line @typescript-eslint/no-namespace, import/no-default-export -export default function({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { +export default function ({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); const log = getService('log'); const esArchiver = getService('esArchiver'); @@ -42,7 +42,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide isOss = await PageObjects.common.isOss(); }); - describe('', function() { + describe('', function () { this.tags('ciGroup9'); loadTestFile(require.resolve('./_embedding_chart')); @@ -53,7 +53,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide loadTestFile(require.resolve('./_data_table_notimeindex_filters')); }); - describe('', function() { + describe('', function () { this.tags('ciGroup10'); loadTestFile(require.resolve('./_inspector')); @@ -65,7 +65,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide loadTestFile(require.resolve('./_metric_chart')); }); - describe('', function() { + describe('', function () { this.tags('ciGroup11'); loadTestFile(require.resolve('./_line_chart')); @@ -82,7 +82,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide } }); - describe('', function() { + describe('', function () { this.tags('ciGroup12'); loadTestFile(require.resolve('./_tag_cloud')); diff --git a/test/functional/apps/visualize/input_control_vis/chained_controls.js b/test/functional/apps/visualize/input_control_vis/chained_controls.js index b5231f3161377..179ffa5125a9a 100644 --- a/test/functional/apps/visualize/input_control_vis/chained_controls.js +++ b/test/functional/apps/visualize/input_control_vis/chained_controls.js @@ -19,14 +19,14 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const filterBar = getService('filterBar'); const PageObjects = getPageObjects(['common', 'visualize', 'visEditor', 'header', 'timePicker']); const testSubjects = getService('testSubjects'); const find = getService('find'); const comboBox = getService('comboBox'); - describe('chained controls', function() { + describe('chained controls', function () { this.tags('includeFirefox'); before(async () => { @@ -38,12 +38,7 @@ export default function({ getService, getPageObjects }) { it('should disable child control when parent control is not set', async () => { const parentControlMenu = await comboBox.getOptionsList('listControlSelect0'); - expect( - parentControlMenu - .trim() - .split('\n') - .join() - ).to.equal('BD,BR,CN,ID,IN,JP,NG,PK,RU,US'); + expect(parentControlMenu.trim().split('\n').join()).to.equal('BD,BR,CN,ID,IN,JP,NG,PK,RU,US'); const childControlInput = await find.byCssSelector('[data-test-subj="inputControl1"] input'); const isDisabled = await childControlInput.getAttribute('disabled'); @@ -54,12 +49,9 @@ export default function({ getService, getPageObjects }) { await comboBox.set('listControlSelect0', 'BR'); const childControlMenu = await comboBox.getOptionsList('listControlSelect1'); - expect( - childControlMenu - .trim() - .split('\n') - .join() - ).to.equal('14.61.182.136,3.174.21.181,6.183.121.70,71.241.97.89,9.69.255.135'); + expect(childControlMenu.trim().split('\n').join()).to.equal( + '14.61.182.136,3.174.21.181,6.183.121.70,71.241.97.89,9.69.255.135' + ); }); it('should create a seperate filter pill for parent control and child control', async () => { diff --git a/test/functional/apps/visualize/input_control_vis/dynamic_options.js b/test/functional/apps/visualize/input_control_vis/dynamic_options.js index d78c780a728a7..b19f64511a23b 100644 --- a/test/functional/apps/visualize/input_control_vis/dynamic_options.js +++ b/test/functional/apps/visualize/input_control_vis/dynamic_options.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['common', 'visualize', 'visEditor', 'header', 'timePicker']); const comboBox = getService('comboBox'); @@ -34,23 +34,13 @@ export default function({ getService, getPageObjects }) { it('should fetch new options when string field is filtered', async () => { const initialOptions = await comboBox.getOptionsList('listControlSelect0'); - expect( - initialOptions - .trim() - .split('\n') - .join() - ).to.equal('BD,BR,CN,ID,IN,JP,NG,PK,RU,US'); + expect(initialOptions.trim().split('\n').join()).to.equal('BD,BR,CN,ID,IN,JP,NG,PK,RU,US'); await comboBox.filterOptionsList('listControlSelect0', 'R'); await PageObjects.header.waitUntilLoadingHasFinished(); const updatedOptions = await comboBox.getOptionsList('listControlSelect0'); - expect( - updatedOptions - .trim() - .split('\n') - .join() - ).to.equal('AR,BR,FR,GR,IR,KR,RO,RU,RW,TR'); + expect(updatedOptions.trim().split('\n').join()).to.equal('AR,BR,FR,GR,IR,KR,RO,RU,RW,TR'); }); it('should not fetch new options when non-string is filtered', async () => { @@ -58,23 +48,17 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); const initialOptions = await comboBox.getOptionsList('listControlSelect0'); - expect( - initialOptions - .trim() - .split('\n') - .join() - ).to.equal('135.206.117.161,177.194.175.66,18.55.141.62,243.158.217.196,32.146.206.24'); + expect(initialOptions.trim().split('\n').join()).to.equal( + '135.206.117.161,177.194.175.66,18.55.141.62,243.158.217.196,32.146.206.24' + ); await comboBox.filterOptionsList('listControlSelect0', '17'); await PageObjects.header.waitUntilLoadingHasFinished(); const updatedOptions = await comboBox.getOptionsList('listControlSelect0'); - expect( - updatedOptions - .trim() - .split('\n') - .join() - ).to.equal('135.206.117.161,177.194.175.66,243.158.217.196'); + expect(updatedOptions.trim().split('\n').join()).to.equal( + '135.206.117.161,177.194.175.66,243.158.217.196' + ); }); }); @@ -90,23 +74,13 @@ export default function({ getService, getPageObjects }) { it('should fetch new options when string field is filtered', async () => { const initialOptions = await comboBox.getOptionsList('listControlSelect1'); - expect( - initialOptions - .trim() - .split('\n') - .join() - ).to.equal('BD,BR,CN,ID,IN,JP,MX,NG,PK,US'); + expect(initialOptions.trim().split('\n').join()).to.equal('BD,BR,CN,ID,IN,JP,MX,NG,PK,US'); await comboBox.filterOptionsList('listControlSelect1', 'R'); await PageObjects.header.waitUntilLoadingHasFinished(); const updatedOptions = await comboBox.getOptionsList('listControlSelect1'); - expect( - updatedOptions - .trim() - .split('\n') - .join() - ).to.equal('AR,BR,FR,GR,IR,KR,RO,RS,RU,TR'); + expect(updatedOptions.trim().split('\n').join()).to.equal('AR,BR,FR,GR,IR,KR,RO,RS,RU,TR'); }); }); }); diff --git a/test/functional/apps/visualize/input_control_vis/index.js b/test/functional/apps/visualize/input_control_vis/index.js index 3b7712b64af83..fd63fb5f04e3a 100644 --- a/test/functional/apps/visualize/input_control_vis/index.js +++ b/test/functional/apps/visualize/input_control_vis/index.js @@ -17,8 +17,8 @@ * under the License. */ -export default function({ loadTestFile }) { - describe('input controls', function() { +export default function ({ loadTestFile }) { + describe('input controls', function () { loadTestFile(require.resolve('./input_control_options')); loadTestFile(require.resolve('./dynamic_options')); loadTestFile(require.resolve('./chained_controls')); diff --git a/test/functional/apps/visualize/input_control_vis/input_control_options.js b/test/functional/apps/visualize/input_control_vis/input_control_options.js index 8e8891ac585b3..a17eeaca16002 100644 --- a/test/functional/apps/visualize/input_control_vis/input_control_options.js +++ b/test/functional/apps/visualize/input_control_vis/input_control_options.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const filterBar = getService('filterBar'); const PageObjects = getPageObjects(['common', 'visualize', 'visEditor', 'header', 'timePicker']); const testSubjects = getService('testSubjects'); @@ -45,7 +45,7 @@ export default function({ getService, getPageObjects }) { await PageObjects.visEditor.clickGo(); }); - it('should not have inspector enabled', async function() { + it('should not have inspector enabled', async function () { await inspector.expectIsNotEnabled(); }); @@ -61,12 +61,7 @@ export default function({ getService, getPageObjects }) { describe('updateFiltersOnChange is false', () => { it('should contain dropdown with terms aggregation results as options', async () => { const menu = await comboBox.getOptionsList('listControlSelect0'); - expect( - menu - .trim() - .split('\n') - .join() - ).to.equal('ios,osx,win 7,win 8,win xp'); + expect(menu.trim().split('\n').join()).to.equal('ios,osx,win 7,win 8,win xp'); }); it('should display staging control buttons', async () => { @@ -191,12 +186,7 @@ export default function({ getService, getPageObjects }) { // Expect control to have values for selected time filter const menu = await comboBox.getOptionsList('listControlSelect0'); - expect( - menu - .trim() - .split('\n') - .join() - ).to.equal('osx,win 7,win 8,win xp'); + expect(menu.trim().split('\n').join()).to.equal('osx,win 7,win 8,win xp'); }); }); }); diff --git a/test/functional/apps/visualize/input_control_vis/input_control_range.ts b/test/functional/apps/visualize/input_control_vis/input_control_range.ts index 8f079f5cc430d..f52a812d4d50c 100644 --- a/test/functional/apps/visualize/input_control_vis/input_control_range.ts +++ b/test/functional/apps/visualize/input_control_vis/input_control_range.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../ftr_provider_context'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const find = getService('find'); diff --git a/test/functional/config.coverage.js b/test/functional/config.coverage.js index a3594bdb3b4e1..bc7ac924cc8f2 100644 --- a/test/functional/config.coverage.js +++ b/test/functional/config.coverage.js @@ -17,7 +17,7 @@ * under the License. */ -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const defaultConfig = await readConfigFile(require.resolve('./config')); return { diff --git a/test/functional/config.edge.js b/test/functional/config.edge.js index ed68b41e8c89a..e80754af4144d 100644 --- a/test/functional/config.edge.js +++ b/test/functional/config.edge.js @@ -17,7 +17,7 @@ * under the License. */ -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const defaultConfig = await readConfigFile(require.resolve('./config')); return { diff --git a/test/functional/config.firefox.js b/test/functional/config.firefox.js index fdf99732fca59..ab25d561f04c4 100644 --- a/test/functional/config.firefox.js +++ b/test/functional/config.firefox.js @@ -17,7 +17,7 @@ * under the License. */ -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const defaultConfig = await readConfigFile(require.resolve('./config')); return { diff --git a/test/functional/config.ie.js b/test/functional/config.ie.js index 2c32ccb69db03..bc47ce707003e 100644 --- a/test/functional/config.ie.js +++ b/test/functional/config.ie.js @@ -17,7 +17,7 @@ * under the License. */ -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const defaultConfig = await readConfigFile(require.resolve('./config')); return { diff --git a/test/functional/config.js b/test/functional/config.js index fee7a6f249f53..52806e8ca68ea 100644 --- a/test/functional/config.js +++ b/test/functional/config.js @@ -20,7 +20,7 @@ import { pageObjects } from './page_objects'; import { services } from './services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const commonConfig = await readConfigFile(require.resolve('../common/config')); return { diff --git a/test/functional/page_objects/console_page.ts b/test/functional/page_objects/console_page.ts index d8eb692a25044..f67a2722da367 100644 --- a/test/functional/page_objects/console_page.ts +++ b/test/functional/page_objects/console_page.ts @@ -27,7 +27,7 @@ export function ConsolePageProvider({ getService }: FtrProviderContext) { class ConsolePage { public async getVisibleTextFromAceEditor(editor: WebElementWrapper) { const lines = await editor.findAllByClassName('ace_line_group'); - const linesText = await Promise.all(lines.map(async line => await line.getVisibleText())); + const linesText = await Promise.all(lines.map(async (line) => await line.getVisibleText())); return linesText.join('\n'); } diff --git a/test/functional/page_objects/dashboard_page.ts b/test/functional/page_objects/dashboard_page.ts index 7775d448a7b16..92482a3779771 100644 --- a/test/functional/page_objects/dashboard_page.ts +++ b/test/functional/page_objects/dashboard_page.ts @@ -191,9 +191,9 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide public async expectToolbarPaginationDisplayed({ displayed = true }) { const subjects = ['btnPrevPage', 'btnNextPage', 'toolBarPagerText']; if (displayed) { - await Promise.all(subjects.map(async subj => await testSubjects.existOrFail(subj))); + await Promise.all(subjects.map(async (subj) => await testSubjects.existOrFail(subj))); } else { - await Promise.all(subjects.map(async subj => await testSubjects.missingOrFail(subj))); + await Promise.all(subjects.map(async (subj) => await testSubjects.missingOrFail(subj))); } } @@ -381,13 +381,13 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide public async getPanelTitles() { log.debug('in getPanelTitles'); const titleObjects = await testSubjects.findAll('dashboardPanelTitle'); - return await Promise.all(titleObjects.map(async title => await title.getVisibleText())); + return await Promise.all(titleObjects.map(async (title) => await title.getVisibleText())); } public async getPanelDimensions() { const panels = await find.allByCssSelector('.react-grid-item'); // These are gridster-defined elements and classes return await Promise.all( - panels.map(async panel => { + panels.map(async (panel) => { const size = await panel.getSize(); return { width: size.width, @@ -416,11 +416,11 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide } public getTestVisualizationNames() { - return this.getTestVisualizations().map(visualization => visualization.name); + return this.getTestVisualizations().map((visualization) => visualization.name); } public getTestVisualizationDescriptions() { - return this.getTestVisualizations().map(visualization => visualization.description); + return this.getTestVisualizations().map((visualization) => visualization.description); } public async getDashboardPanels() { @@ -487,7 +487,7 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide const $ = await sharedItemscontainer.parseDomContent(); return $('[data-shared-item]') .toArray() - .map(item => { + .map((item) => { return { title: $(item).attr('data-title'), description: $(item).attr('data-description'), @@ -515,7 +515,7 @@ export function DashboardPageProvider({ getService, getPageObjects }: FtrProvide checkList.push({ name, isPresent }); } - return checkList.filter(viz => viz.isPresent === false).map(viz => viz.name); + return checkList.filter((viz) => viz.isPresent === false).map((viz) => viz.name); } public async getPanelDrilldownCount(panelIndex = 0): Promise { diff --git a/test/functional/page_objects/discover_page.ts b/test/functional/page_objects/discover_page.ts index 831c76dd8fe46..4e2e06eaecf96 100644 --- a/test/functional/page_objects/discover_page.ts +++ b/test/functional/page_objects/discover_page.ts @@ -142,11 +142,7 @@ export function DiscoverPageProvider({ getService, getPageObjects }: FtrProvider public async clickHistogramBar() { const el = await elasticChart.getCanvas(); - await browser - .getActions() - .move({ x: 0, y: 20, origin: el._webElement }) - .click() - .perform(); + await browser.getActions().move({ x: 0, y: 20, origin: el._webElement }).click().perform(); } public async brushHistogram() { @@ -214,7 +210,7 @@ export function DiscoverPageProvider({ getService, getPageObjects }: FtrProvider const $ = await table.parseDomContent(); return $('mark') .toArray() - .map(mark => $(mark).text()); + .map((mark) => $(mark).text()); } public async toggleSidebarCollapse() { @@ -226,11 +222,7 @@ export function DiscoverPageProvider({ getService, getPageObjects }: FtrProvider const $ = await sidebar.parseDomContent(); return $('.dscSidebar__item[attr-field]') .toArray() - .map(field => - $(field) - .find('span.eui-textTruncate') - .text() - ); + .map((field) => $(field).find('span.eui-textTruncate').text()); } public async getSidebarWidth() { diff --git a/test/functional/page_objects/settings_page.ts b/test/functional/page_objects/settings_page.ts index 1315b86f9c93c..9cf7a48cb3d88 100644 --- a/test/functional/page_objects/settings_page.ts +++ b/test/functional/page_objects/settings_page.ts @@ -220,21 +220,21 @@ export function SettingsPageProvider({ getService, getPageObjects }: FtrProvider async getFieldNames() { const fieldNameCells = await testSubjects.findAll('editIndexPattern > indexedFieldName'); - return await mapAsync(fieldNameCells, async cell => { + return await mapAsync(fieldNameCells, async (cell) => { return (await cell.getVisibleText()).trim(); }); } async getFieldTypes() { const fieldNameCells = await testSubjects.findAll('editIndexPattern > indexedFieldType'); - return await mapAsync(fieldNameCells, async cell => { + return await mapAsync(fieldNameCells, async (cell) => { return (await cell.getVisibleText()).trim(); }); } async getScriptedFieldLangs() { const fieldNameCells = await testSubjects.findAll('editIndexPattern > scriptedFieldLang'); - return await mapAsync(fieldNameCells, async cell => { + return await mapAsync(fieldNameCells, async (cell) => { return (await cell.getVisibleText()).trim(); }); } @@ -699,7 +699,7 @@ export function SettingsPageProvider({ getService, getPageObjects }: FtrProvider async getSavedObjectElementsInTable() { const rows = await testSubjects.findAll('~savedObjectsTableRow'); - return mapAsync(rows, async row => { + return mapAsync(rows, async (row) => { const checkbox = await row.findByCssSelector('[data-test-subj*="checkboxSelectRow"]'); // return the object type aria-label="index patterns" const objectType = await row.findByTestSubject('objectType'); @@ -740,7 +740,7 @@ export function SettingsPageProvider({ getService, getPageObjects }: FtrProvider async getRelationshipFlyout() { const rows = await testSubjects.findAll('relationshipsTableRow'); - return mapAsync(rows, async row => { + return mapAsync(rows, async (row) => { const objectType = await row.findByTestSubject('relationshipsObjectType'); const relationship = await row.findByTestSubject('directRelationship'); const titleElement = await row.findByTestSubject('relationshipsTitle'); diff --git a/test/functional/page_objects/tag_cloud_page.ts b/test/functional/page_objects/tag_cloud_page.ts index 7d87caa39b2fb..5a830d2e648a1 100644 --- a/test/functional/page_objects/tag_cloud_page.ts +++ b/test/functional/page_objects/tag_cloud_page.ts @@ -34,7 +34,7 @@ export function TagCloudPageProvider({ getService, getPageObjects }: FtrProvider public async getTextTag() { await visChart.waitForVisualization(); const elements = await find.allByCssSelector('text'); - return await Promise.all(elements.map(async element => await element.getVisibleText())); + return await Promise.all(elements.map(async (element) => await element.getVisibleText())); } public async getTextSizes() { diff --git a/test/functional/page_objects/tile_map_page.ts b/test/functional/page_objects/tile_map_page.ts index beb2f029c3e1c..609e6ebddd50a 100644 --- a/test/functional/page_objects/tile_map_page.ts +++ b/test/functional/page_objects/tile_map_page.ts @@ -70,7 +70,7 @@ export function TileMapPageProvider({ getService, getPageObjects }: FtrProviderC public async getMapZoomEnabled(zoomSelector: string): Promise { const zooms = await this.getZoomSelectors(zoomSelector); const classAttributes = await Promise.all( - zooms.map(async zoom => await zoom.getAttribute('class')) + zooms.map(async (zoom) => await zoom.getAttribute('class')) ); return !classAttributes.join('').includes('leaflet-disabled'); } diff --git a/test/functional/page_objects/time_picker.ts b/test/functional/page_objects/time_picker.ts index 4606d93ac27f5..c755a6655e71f 100644 --- a/test/functional/page_objects/time_picker.ts +++ b/test/functional/page_objects/time_picker.ts @@ -179,7 +179,7 @@ export function TimePickerProvider({ getService, getPageObjects }: FtrProviderCo const select = await testSubjects.find('superDatePickerRefreshIntervalUnitsSelect'); const options = await find.allDescendantDisplayedByCssSelector('option', select); await Promise.all( - options.map(async optionElement => { + options.map(async (optionElement) => { const isSelected = await optionElement.isSelected(); if (isSelected) { selectedUnit = await optionElement.getVisibleText(); diff --git a/test/functional/page_objects/timelion_page.ts b/test/functional/page_objects/timelion_page.ts index 1075c19a105c0..f025fc946bef1 100644 --- a/test/functional/page_objects/timelion_page.ts +++ b/test/functional/page_objects/timelion_page.ts @@ -57,7 +57,7 @@ export function TimelionPageProvider({ getService, getPageObjects }: FtrProvider public async getSuggestionItemsText() { const elements = await testSubjects.findAll('timelionSuggestionListItem'); - return await Promise.all(elements.map(async element => await element.getVisibleText())); + return await Promise.all(elements.map(async (element) => await element.getVisibleText())); } public async clickSuggestion(suggestionIndex = 0, waitTime = 500) { diff --git a/test/functional/page_objects/vega_chart_page.ts b/test/functional/page_objects/vega_chart_page.ts index 9931ebebef6ef..488f4cfd0d0ce 100644 --- a/test/functional/page_objects/vega_chart_page.ts +++ b/test/functional/page_objects/vega_chart_page.ts @@ -38,7 +38,7 @@ export function VegaChartPageProvider({ const editor = await testSubjects.find('vega-editor'); const lines = await editor.findAllByClassName('ace_line_group'); const linesText = await Promise.all( - lines.map(async line => { + lines.map(async (line) => { return await line.getVisibleText(); }) ); diff --git a/test/functional/page_objects/visual_builder_page.ts b/test/functional/page_objects/visual_builder_page.ts index f3af08b2a15fa..6649231887a4d 100644 --- a/test/functional/page_objects/visual_builder_page.ts +++ b/test/functional/page_objects/visual_builder_page.ts @@ -165,7 +165,7 @@ export function VisualBuilderPageProvider({ getService, getPageObjects }: FtrPro const variables = await testTableVariables.findAllByCssSelector(variablesSelector); const variablesKeyValueSelectorMap = await Promise.all( - variables.map(async variable => { + variables.map(async (variable) => { const subVars = await variable.findAllByCssSelector('td'); const selector = await subVars[0].findByTagName('a'); const key = await selector.getVisibleText(); diff --git a/test/functional/page_objects/visualize_chart_page.ts b/test/functional/page_objects/visualize_chart_page.ts index 31e18adad7589..673fba0c346b8 100644 --- a/test/functional/page_objects/visualize_chart_page.ts +++ b/test/functional/page_objects/visualize_chart_page.ts @@ -40,11 +40,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr const $ = await xAxis.parseDomContent(); return $('.x > g > text') .toArray() - .map(tick => - $(tick) - .text() - .trim() - ); + .map((tick) => $(tick).text().trim()); } public async getYAxisLabels() { @@ -52,11 +48,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr const $ = await yAxis.parseDomContent(); return $('.y > g > text') .toArray() - .map(tick => - $(tick) - .text() - .trim() - ); + .map((tick) => $(tick).text().trim()); } /** @@ -137,7 +129,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr ); // 4). for each chart element, find the green circle, then the cy position const chartData = await Promise.all( - chartTypes.map(async chart => { + chartTypes.map(async (chart) => { const cy = Number(await chart.getAttribute('cy')); // the point_series_options test has data in the billions range and // getting 11 digits of precision with these calculations is very hard @@ -159,7 +151,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr const $ = await svg.parseDomContent(); const chartData = $(`g > g.series > rect[data-label="${dataLabel}"]`) .toArray() - .map(chart => { + .map((chart) => { const barHeight = Number($(chart).attr('height')); return Math.round(barHeight * yAxisRatio); }); @@ -268,7 +260,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr defaultFindTimeout * 2 ); return await Promise.all( - legendEntries.map(async chart => await chart.getAttribute('data-label')) + legendEntries.map(async (chart) => await chart.getAttribute('data-label')) ); } @@ -333,10 +325,12 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr } const allData = await Promise.all( - allTables.map(async t => { + allTables.map(async (t) => { let data = await table.getDataFromElement(t); if (stripEmptyRows) { - data = data.filter(row => row.length > 0 && row.some(cell => cell.trim().length > 0)); + data = data.filter( + (row) => row.length > 0 && row.some((cell) => cell.trim().length > 0) + ); } return data; }) @@ -358,13 +352,13 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr '[data-test-subj="visualizationLoader"] .mtrVis__container' ); const values = await Promise.all( - elements.map(async element => { + elements.map(async (element) => { const text = await element.getVisibleText(); return text; }) ); return values - .filter(item => item.length > 0) + .filter((item) => item.length > 0) .reduce((arr: string[], item) => arr.concat(item.split('\n')), []); } @@ -373,12 +367,12 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr '[data-test-subj="visualizationLoader"] .chart svg text' ); const values = await Promise.all( - elements.map(async element => { + elements.map(async (element) => { const text = await element.getVisibleText(); return text; }) ); - return values.filter(item => item.length > 0); + return values.filter((item) => item.length > 0); } public async getRightValueAxes() { @@ -396,12 +390,9 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr const $ = await grid.parseDomContent(); return $('path') .toArray() - .map(line => { + .map((line) => { const dAttribute = $(line).attr('d'); - const firstPoint = dAttribute - .split('L')[0] - .replace('M', '') - .split(','); + const firstPoint = dAttribute.split('L')[0].replace('M', '').split(','); return { x: parseFloat(firstPoint[0]), y: parseFloat(firstPoint[1]), @@ -412,7 +403,7 @@ export function VisualizeChartPageProvider({ getService, getPageObjects }: FtrPr public async getChartValues() { const elements = await find.allByCssSelector('.series.histogram text'); const values = await Promise.all( - elements.map(async element => { + elements.map(async (element) => { const text = await element.getVisibleText(); return text; }) diff --git a/test/functional/page_objects/visualize_editor_page.ts b/test/functional/page_objects/visualize_editor_page.ts index 43323d37ffb6a..c4c7c2aaffabd 100644 --- a/test/functional/page_objects/visualize_editor_page.ts +++ b/test/functional/page_objects/visualize_editor_page.ts @@ -475,7 +475,7 @@ export function VisualizeEditorPageProvider({ getService, getPageObjects }: FtrP const $ = await selectField.parseDomContent(); const optionsText = $('option') .toArray() - .map(option => $(option).text()); + .map((option) => $(option).text()); const optionIndex = optionsText.indexOf(optionText); if (optionIndex === -1) { diff --git a/test/functional/page_objects/visualize_page.ts b/test/functional/page_objects/visualize_page.ts index eebbfc7105862..22142d1975000 100644 --- a/test/functional/page_objects/visualize_page.ts +++ b/test/functional/page_objects/visualize_page.ts @@ -56,12 +56,7 @@ export function VisualizePageProvider({ getService, getPageObjects }: FtrProvide const $ = await chartTypeField.parseDomContent(); return $('button') .toArray() - .map(chart => - $(chart) - .findTestSubject('visTypeTitle') - .text() - .trim() - ); + .map((chart) => $(chart).findTestSubject('visTypeTitle').text().trim()); } public async waitForVisualizationSelectPage() { diff --git a/test/functional/services/apps_menu.ts b/test/functional/services/apps_menu.ts index 0f27de67fd535..969bddbd30f9a 100644 --- a/test/functional/services/apps_menu.ts +++ b/test/functional/services/apps_menu.ts @@ -79,7 +79,7 @@ export function AppsMenuProvider({ getService, getPageObjects }: FtrProviderCont const $ = await appMenu.parseDomContent(); const links = $.findTestSubjects('collapsibleNavAppLink') .toArray() - .map(link => { + .map((link) => { return { text: $(link).text(), href: $(link).attr('href'), @@ -97,7 +97,7 @@ export function AppsMenuProvider({ getService, getPageObjects }: FtrProviderCont * @param name */ public async getLink(name: string) { - return (await this.readLinks()).find(nl => nl.text === name); + return (await this.readLinks()).find((nl) => nl.text === name); } /** @@ -105,7 +105,7 @@ export function AppsMenuProvider({ getService, getPageObjects }: FtrProviderCont * @param name */ public async linkExists(name: string) { - return (await this.readLinks()).some(nl => nl.text === name); + return (await this.readLinks()).some((nl) => nl.text === name); } /** diff --git a/test/functional/services/combo_box.ts b/test/functional/services/combo_box.ts index 2c12490ccd436..60fea7ea86cf9 100644 --- a/test/functional/services/combo_box.ts +++ b/test/functional/services/combo_box.ts @@ -200,7 +200,7 @@ export function ComboBoxProvider({ getService, getPageObjects }: FtrProviderCont const $ = await comboBox.parseDomContent(); return $('.euiComboBoxPill') .toArray() - .map(option => $(option).text()); + .map((option) => $(option).text()); } /** @@ -283,7 +283,7 @@ export function ComboBoxProvider({ getService, getPageObjects }: FtrProviderCont const $ = await comboBoxElement.parseDomContent(); const selectedOptions = $('.euiComboBoxPill') .toArray() - .map(option => $(option).text()); + .map((option) => $(option).text()); return selectedOptions.length === 1 && selectedOptions[0] === value; } diff --git a/test/functional/services/common/browser.ts b/test/functional/services/common/browser.ts index 4b5a3c101b51c..46d57f030937b 100644 --- a/test/functional/services/common/browser.ts +++ b/test/functional/services/common/browser.ts @@ -87,10 +87,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { * @return {Promise<{height: number, width: number, x: number, y: number}>} */ public async getWindowSize(): Promise<{ height: number; width: number; x: number; y: number }> { - return await driver - .manage() - .window() - .getRect(); + return await driver.manage().window().getRect(); } /** @@ -102,10 +99,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { * @return {Promise} */ public async setWindowSize(width: number, height: number) { - await driver - .manage() - .window() - .setRect({ width, height }); + await driver.manage().window().setRect({ width, height }); } /** @@ -176,7 +170,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { } else { current = await driver.getCurrentUrl(); } - const currentWithoutTime = modifyUrl(current, parsed => { + const currentWithoutTime = modifyUrl(current, (parsed) => { delete (parsed.query as any)._t; return void 0; }); @@ -193,7 +187,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { */ public async get(url: string, insertTimestamp: boolean = true) { if (insertTimestamp) { - const urlWithTime = modifyUrl(url, parsed => { + const urlWithTime = modifyUrl(url, (parsed) => { (parsed.query as any)._t = Date.now(); return void 0; }); @@ -221,12 +215,8 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { */ public async moveMouseTo(point: { x: number; y: number }): Promise { if (this.isW3CEnabled) { - await this.getActions() - .move({ x: 0, y: 0 }) - .perform(); - await this.getActions() - .move({ x: point.x, y: point.y, origin: Origin.POINTER }) - .perform(); + await this.getActions().move({ x: 0, y: 0 }).perform(); + await this.getActions().move({ x: point.x, y: point.y, origin: Origin.POINTER }).perform(); } else { await this.getActions() .pause(this.getActions().mouse) @@ -260,15 +250,8 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { const startPoint = getW3CPoint(from); const endPoint = getW3CPoint(to); - await this.getActions() - .move({ x: 0, y: 0 }) - .perform(); - return await this.getActions() - .move(startPoint) - .press() - .move(endPoint) - .release() - .perform(); + await this.getActions().move({ x: 0, y: 0 }).perform(); + return await this.getActions().move(startPoint).press().move(endPoint).release().perform(); } else { // The offset should be specified in pixels relative to the top-left corner of the element's bounding box const getOffset: any = (offset: { x: number; y: number }) => @@ -345,9 +328,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { public async pressKeys(...args: string[]): Promise; public async pressKeys(...args: string[]): Promise { const chord = this.keys.chord(...args); - await this.getActions() - .sendKeys(chord) - .perform(); + await this.getActions().sendKeys(chord).perform(); } /** @@ -361,9 +342,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { */ public async clickMouseButton(point: { x: number; y: number }) { if (this.isW3CEnabled) { - await this.getActions() - .move({ x: 0, y: 0 }) - .perform(); + await this.getActions().move({ x: 0, y: 0 }).perform(); await this.getActions() .move({ x: point.x, y: point.y, origin: Origin.POINTER }) .click() @@ -405,9 +384,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { * @return {Promise} */ public async doubleClick() { - await this.getActions() - .doubleClick() - .perform(); + await this.getActions().doubleClick().perform(); } /** @@ -480,7 +457,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { ): Promise { return await driver.executeScript( fn, - ...cloneDeep(args, arg => { + ...cloneDeep(args, (arg) => { if (arg instanceof WebElementWrapper) { return arg._webElement; } @@ -494,7 +471,7 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { ): Promise { return await driver.executeAsyncScript( fn, - ...cloneDeep(args, arg => { + ...cloneDeep(args, (arg) => { if (arg instanceof WebElementWrapper) { return arg._webElement; } diff --git a/test/functional/services/common/find.ts b/test/functional/services/common/find.ts index 727d81377b141..876fb7369feac 100644 --- a/test/functional/services/common/find.ts +++ b/test/functional/services/common/find.ts @@ -44,7 +44,7 @@ export async function FindProvider({ getService }: FtrProviderContext) { ); const wrapAll = (webElements: Array) => - webElements.map(e => wrap(e)); + webElements.map((e) => wrap(e)); const findAndWrap = async (locator: By, timeout: number): Promise => { const webElement = await driver.wait(until.elementLocated(locator), timeout); @@ -145,7 +145,7 @@ export async function FindProvider({ getService }: FtrProviderContext) { elements = []; } // Force isStale checks for all the retrieved elements. - await Promise.all(elements.map(async element => await element.isEnabled())); + await Promise.all(elements.map(async (element) => await element.isEnabled())); await this._withTimeout(defaultFindTimeout); return elements; }); @@ -289,7 +289,7 @@ export async function FindProvider({ getService }: FtrProviderContext) { ): Promise { log.debug(`Find.existsByLinkText('${linkText}') with timeout=${timeout}`); return await this.exists( - async drive => wrapAll(await drive.findElements(By.linkText(linkText))), + async (drive) => wrapAll(await drive.findElements(By.linkText(linkText))), timeout ); } @@ -322,7 +322,7 @@ export async function FindProvider({ getService }: FtrProviderContext) { timeout: number = WAIT_FOR_EXISTS_TIME ): Promise { log.debug(`Find.existsByCssSelector('${selector}') with timeout=${timeout}`); - return await this.exists(async drive => { + return await this.exists(async (drive) => { return wrapAll(await drive.findElements(By.css(selector))); }, timeout); } @@ -377,11 +377,11 @@ export async function FindProvider({ getService }: FtrProviderContext) { const _element = element instanceof WebElementWrapper ? element._webElement : element; const allButtons = wrapAll(await _element.findElements(By.tagName('button'))); const buttonTexts = await Promise.all( - allButtons.map(async el => { + allButtons.map(async (el) => { return el.getVisibleText(); }) ); - const index = buttonTexts.findIndex(text => text.trim() === buttonText.trim()); + const index = buttonTexts.findIndex((text) => text.trim() === buttonText.trim()); if (index === -1) { throw new Error('Button not found'); } diff --git a/test/functional/services/common/test_subjects.ts b/test/functional/services/common/test_subjects.ts index c71154ba2ec6a..204edcb215107 100644 --- a/test/functional/services/common/test_subjects.ts +++ b/test/functional/services/common/test_subjects.ts @@ -80,7 +80,7 @@ export function TestSubjectsProvider({ getService }: FtrProviderContext) { const responseCodeBlock = await this.find(codeBlockSelector); const spans = await find.allDescendantDisplayedByTagName('span', responseCodeBlock); const foundInSpans = await Promise.all( - spans.map(async span => { + spans.map(async (span) => { const text = await span.getVisibleText(); if (text === stringToFind) { log.debug(`"${text}" matched "${stringToFind}"!`); @@ -90,7 +90,7 @@ export function TestSubjectsProvider({ getService }: FtrProviderContext) { } }) ); - if (!foundInSpans.find(foundInSpan => foundInSpan)) { + if (!foundInSpans.find((foundInSpan) => foundInSpan)) { throw new Error(`"${stringToFind}" was not found. Trying again...`); } }); diff --git a/test/functional/services/dashboard/expectations.js b/test/functional/services/dashboard/expectations.js index be538d896cc52..66073e1043b0d 100644 --- a/test/functional/services/dashboard/expectations.js +++ b/test/functional/services/dashboard/expectations.js @@ -41,7 +41,7 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { log.debug('Checking all visualisations are present on dashsboard'); let notLoaded = await PageObjects.dashboard.getNotLoadedVisualizations(vizList); // TODO: Determine issue occasionally preventing 'geo map' from loading - notLoaded = notLoaded.filter(x => x !== 'Rendering Test: geo map'); + notLoaded = notLoaded.filter((x) => x !== 'Rendering Test: geo map'); expect(notLoaded).to.be.empty(); } @@ -67,7 +67,7 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { async fieldSuggestions(expectedFields) { log.debug(`DashboardExpect.fieldSuggestions(${expectedFields})`); const fields = await filterBar.getFilterEditorFields(); - expectedFields.forEach(expectedField => { + expectedFields.forEach((expectedField) => { expect(fields).to.contain(expectedField); }); } @@ -75,7 +75,7 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { async legendValuesToExist(legendValues) { log.debug(`DashboardExpect.legendValuesToExist(${legendValues})`); await Promise.all( - legendValues.map(async legend => { + legendValues.map(async (legend) => { await retry.try(async () => { const legendValueExists = await testSubjects.exists(`legend-${legend}`); expect(legendValueExists).to.be(true); @@ -90,12 +90,12 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { const elements = await getElementsFn(); const elementTexts = []; await Promise.all( - elements.map(async element => { + elements.map(async (element) => { elementTexts.push(await element.getVisibleText()); }) ); log.debug(`Found ${elements.length} elements with values: ${JSON.stringify(elementTexts)}`); - texts.forEach(value => { + texts.forEach((value) => { const indexOfValue = elementTexts.indexOf(value); expect(indexOfValue).to.be.greaterThan(-1); elementTexts.splice(indexOfValue, 1); @@ -121,12 +121,12 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { const elements = await getElementsFn(); const elementTexts = []; await Promise.all( - elements.map(async element => { + elements.map(async (element) => { elementTexts.push(await element.getVisibleText()); }) ); log.debug(`Found ${elements.length} elements with values: ${JSON.stringify(elementTexts)}`); - texts.forEach(value => { + texts.forEach((value) => { const indexOfValue = elementTexts.indexOf(value); expect(indexOfValue).to.be(-1); }); @@ -153,7 +153,7 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { log.debug(`DashboardExpect.emptyTagCloudFound()`); const tagCloudVisualizations = await testSubjects.findAll('tagCloudVisualization'); const tagCloudsHaveContent = await Promise.all( - tagCloudVisualizations.map(async tagCloud => { + tagCloudVisualizations.map(async (tagCloud) => { return await find.descendantExistsByCssSelector('text', tagCloud); }) ); @@ -164,7 +164,7 @@ export function DashboardExpectProvider({ getService, getPageObjects }) { log.debug(`DashboardExpect.tagCloudWithValuesFound(${values})`); const tagCloudVisualizations = await testSubjects.findAll('tagCloudVisualization'); const matches = await Promise.all( - tagCloudVisualizations.map(async tagCloud => { + tagCloudVisualizations.map(async (tagCloud) => { for (let i = 0; i < values.length; i++) { const valueExists = await testSubjects.descendantExists(values[i], tagCloud); if (!valueExists) { diff --git a/test/functional/services/doc_table.ts b/test/functional/services/doc_table.ts index 69650f123d99d..52593de68705b 100644 --- a/test/functional/services/doc_table.ts +++ b/test/functional/services/doc_table.ts @@ -39,11 +39,7 @@ export function DocTableProvider({ getService, getPageObjects }: FtrProviderCont const $ = await table.parseDomContent(); return $.findTestSubjects('~docTableRow') .toArray() - .map((row: any) => - $(row) - .text() - .trim() - ); + .map((row: any) => $(row).text().trim()); } public async getBodyRows(): Promise { @@ -111,11 +107,7 @@ export function DocTableProvider({ getService, getPageObjects }: FtrProviderCont const $ = await table.parseDomContent(); return $.findTestSubjects('~docTableHeaderField') .toArray() - .map((field: any) => - $(field) - .text() - .trim() - ); + .map((field: any) => $(field).text().trim()); } public async getTableDocViewRow( diff --git a/test/functional/services/filter_bar.ts b/test/functional/services/filter_bar.ts index a463a593e9e04..f6531f8d872c2 100644 --- a/test/functional/services/filter_bar.ts +++ b/test/functional/services/filter_bar.ts @@ -187,10 +187,7 @@ export function FilterBarProvider({ getService, getPageObjects }: FtrProviderCon await testSubjects.click('addFilter'); const indexPatterns = await comboBox.getOptionsList('filterIndexPatternsSelect'); await this.ensureFieldEditorModalIsClosed(); - return indexPatterns - .trim() - .split('\n') - .join(','); + return indexPatterns.trim().split('\n').join(','); } /** diff --git a/test/functional/services/inspector.ts b/test/functional/services/inspector.ts index ce61530246eea..d8ac224ddd9bc 100644 --- a/test/functional/services/inspector.ts +++ b/test/functional/services/inspector.ts @@ -119,24 +119,19 @@ export function InspectorProvider({ getService }: FtrProviderContext) { const $ = await tableBody.parseDomContent(); return $('tr') .toArray() - .map(tr => { + .map((tr) => { return $(tr) .find('td') .toArray() - .map(cell => { + .map((cell) => { // if this is an EUI table, filter down to the specific cell content // otherwise this will include mobile-specific header information const euiTableCellContent = $(cell).find('.euiTableCellContent'); if (euiTableCellContent.length > 0) { - return $(cell) - .find('.euiTableCellContent') - .text() - .trim(); + return $(cell).find('.euiTableCellContent').text().trim(); } else { - return $(cell) - .text() - .trim(); + return $(cell).text().trim(); } }); }); @@ -155,11 +150,7 @@ export function InspectorProvider({ getService }: FtrProviderContext) { const $ = await dataTableHeader.parseDomContent(); return $('th span.euiTableCellContent__text') .toArray() - .map(cell => - $(cell) - .text() - .trim() - ); + .map((cell) => $(cell).text().trim()); } /** @@ -236,10 +227,7 @@ export function InspectorProvider({ getService }: FtrProviderContext) { await testSubjects.click('inspectorRequestChooser'); const menu = await testSubjects.find('inspectorRequestChooserMenuPanel'); const requestNames = await menu.getVisibleText(); - return requestNames - .trim() - .split('\n') - .join(','); + return requestNames.trim().split('\n').join(','); } const singleRequest = await testSubjects.find('inspectorRequestName'); diff --git a/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts b/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts index 615dc783601bc..281a412653bd0 100644 --- a/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts +++ b/test/functional/services/lib/web_element_wrapper/web_element_wrapper.ts @@ -111,7 +111,7 @@ export class WebElementWrapper { } private _wrapAll(otherWebElements: Array) { - return otherWebElements.map(e => this._wrap(e)); + return otherWebElements.map((e) => this._wrap(e)); } private async retryCall( @@ -430,10 +430,7 @@ export class WebElementWrapper { await this.retryCall(async function moveMouseTo(wrapper) { await wrapper.scrollIntoViewIfNecessary(); if (wrapper.isW3CEnabled) { - await wrapper - .getActions() - .move({ x: 0, y: 0 }) - .perform(); + await wrapper.getActions().move({ x: 0, y: 0 }).perform(); await wrapper .getActions() .move({ x: options.xOffset, y: options.yOffset, origin: wrapper._webElement }) @@ -460,10 +457,7 @@ export class WebElementWrapper { await this.retryCall(async function clickMouseButton(wrapper) { await wrapper.scrollIntoViewIfNecessary(); if (wrapper.isW3CEnabled) { - await wrapper - .getActions() - .move({ x: 0, y: 0 }) - .perform(); + await wrapper.getActions().move({ x: 0, y: 0 }).perform(); await wrapper .getActions() .move({ x: options.xOffset, y: options.yOffset, origin: wrapper._webElement }) @@ -489,10 +483,7 @@ export class WebElementWrapper { public async doubleClick() { await this.retryCall(async function clickMouseButton(wrapper) { await wrapper.scrollIntoViewIfNecessary(); - await wrapper - .getActions() - .doubleClick(wrapper._webElement) - .perform(); + await wrapper.getActions().doubleClick(wrapper._webElement).perform(); }); } diff --git a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/config.js b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/config.js index 6ac839946d75e..ae5c939d4aa07 100644 --- a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/config.js +++ b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/config.js @@ -19,7 +19,7 @@ import { RemoteProvider } from '../../../remote'; -export default function() { +export default function () { return { testFiles: [require.resolve('./test')], services: { diff --git a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test.js b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test.js index 788b16e74c31e..7f4b15df4b436 100644 --- a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test.js +++ b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const remote = getService('remote'); describe('suite1', () => { diff --git a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test2.js b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test2.js index c486e4ecad5f1..fa648fd661981 100644 --- a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test2.js +++ b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test2.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const remote = getService('remote'); describe('suite2', () => { diff --git a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.1.js b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.1.js index 8115611bb4445..78a30b7e6065d 100644 --- a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.1.js +++ b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.1.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const remote = getService('remote'); describe('suite3.1', () => { diff --git a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.js b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.js index 6f66420612413..b29cb4a91ca38 100644 --- a/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.js +++ b/test/functional/services/remote/__tests__/fixtures/several_nested_window_size_changes/test3.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const remote = getService('remote'); describe('suite3', () => { diff --git a/test/functional/services/remote/__tests__/remote_default_window_size.js b/test/functional/services/remote/__tests__/remote_default_window_size.js index 9bead6e262b8b..8c8415fa15319 100644 --- a/test/functional/services/remote/__tests__/remote_default_window_size.js +++ b/test/functional/services/remote/__tests__/remote_default_window_size.js @@ -31,7 +31,7 @@ const SUITE2_SIZE = { width: 900, height: 900 }; const SUITE3_SIZE = { width: 800, height: 800 }; const SUITE31_SIZE = { width: 700, height: 700 }; -describe('remote default window size', function() { +describe('remote default window size', function () { // give the tests some time to initialize the FTR and Chrome this.timeout(30 * SECOND); @@ -41,7 +41,7 @@ describe('remote default window size', function() { }); const messages = []; - proc.on('message', msg => { + proc.on('message', (msg) => { messages.push(msg); }); diff --git a/test/functional/services/remote/create_stdout_stream.ts b/test/functional/services/remote/create_stdout_stream.ts index 877be1f829daf..9af5cba63f9ea 100644 --- a/test/functional/services/remote/create_stdout_stream.ts +++ b/test/functional/services/remote/create_stdout_stream.ts @@ -27,7 +27,7 @@ export async function createStdoutSocket() { const cleanup$ = new Rx.ReplaySubject(1); const server = Net.createServer(); - server.on('connection', socket => { + server.on('connection', (socket) => { const data$ = Rx.fromEvent(socket, 'data'); const end$ = Rx.fromEvent(socket, 'end'); const error$ = Rx.fromEvent(socket, 'error'); @@ -58,7 +58,7 @@ export async function createStdoutSocket() { const readyPromise = Rx.race( Rx.fromEvent(server, 'listening').pipe(take(1)), Rx.fromEvent(server, 'error').pipe( - map(error => { + map((error) => { throw error; }) ) @@ -77,9 +77,7 @@ export async function createStdoutSocket() { } const input = Net.createConnection(addressInfo.port, addressInfo.address); - await Rx.fromEvent(input, 'connect') - .pipe(take(1)) - .toPromise(); + await Rx.fromEvent(input, 'connect').pipe(take(1)).toPromise(); return { input, diff --git a/test/functional/services/remote/poll_for_log_entry.ts b/test/functional/services/remote/poll_for_log_entry.ts index 0bd5d94f892b0..35a8b9a705533 100644 --- a/test/functional/services/remote/poll_for_log_entry.ts +++ b/test/functional/services/remote/poll_for_log_entry.ts @@ -36,7 +36,7 @@ export function pollForLogEntry$( const FINAL_MSG = '@@final@@'; - return new Rx.Observable(subscriber => { + return new Rx.Observable((subscriber) => { subscriber.add( stop$.pipe(first()).subscribe(() => { driver @@ -49,7 +49,7 @@ export function pollForLogEntry$( console.log(${JSON.stringify(FINAL_MSG)}) ` ) - .catch(error => subscriber.error(error)); + .catch((error) => subscriber.error(error)); }) ); @@ -61,8 +61,8 @@ export function pollForLogEntry$( mergeMap(async () => await logCtrl.get(type)), // filter and flatten list of entries - mergeMap(entries => { - const filtered = entries.filter(entry => { + mergeMap((entries) => { + const filtered = entries.filter((entry) => { if (entry.message.includes(FINAL_MSG)) { poll$.complete(); return false; diff --git a/test/functional/services/remote/prevent_parallel_calls.test.js b/test/functional/services/remote/prevent_parallel_calls.test.js index 03cf4c671be53..18e719375ed88 100644 --- a/test/functional/services/remote/prevent_parallel_calls.test.js +++ b/test/functional/services/remote/prevent_parallel_calls.test.js @@ -24,11 +24,11 @@ it('only calls fn when previous call is complete, ignores when filter returns tr async function foo(arg) { orderOfEvents.push(`called with ${arg}`); - await new Promise(resolve => setTimeout(resolve, arg)); + await new Promise((resolve) => setTimeout(resolve, arg)); orderOfEvents.push(`resolved with ${arg}`); } - const serialized = preventParallelCalls(foo, arg => arg === 0); + const serialized = preventParallelCalls(foo, (arg) => arg === 0); await Promise.all([ serialized(100), diff --git a/test/functional/services/remote/prevent_parallel_calls.ts b/test/functional/services/remote/prevent_parallel_calls.ts index b2cedcbd5da98..a19fca2902280 100644 --- a/test/functional/services/remote/prevent_parallel_calls.ts +++ b/test/functional/services/remote/prevent_parallel_calls.ts @@ -49,7 +49,7 @@ export function preventParallelCalls( } } - return async function(this: C, arg: A) { + return async function (this: C, arg: A) { if (filter(arg)) { return await fn.call(this, arg); } diff --git a/test/functional/services/remote/remote.ts b/test/functional/services/remote/remote.ts index 770e82ad461d2..5a3a775cae0c5 100644 --- a/test/functional/services/remote/remote.ts +++ b/test/functional/services/remote/remote.ts @@ -83,7 +83,7 @@ export async function RemoteProvider({ getService }: FtrProviderContext) { consoleLog$ .pipe( - mergeMap(logEntry => { + mergeMap((logEntry) => { if (collectCoverage && logEntry.message.includes(coveragePrefix)) { const [, coverageJsonBase64] = logEntry.message.split(coveragePrefix); const coverageJson = Buffer.from(coverageJsonBase64, 'base64').toString('utf8'); @@ -108,20 +108,12 @@ export async function RemoteProvider({ getService }: FtrProviderContext) { lifecycle.beforeTests.add(async () => { // hard coded default, can be overridden per suite using `browser.setWindowSize()` // and will be automatically reverted after each suite - await driver - .manage() - .window() - .setRect({ width: 1600, height: 1000 }); + await driver.manage().window().setRect({ width: 1600, height: 1000 }); }); const windowSizeStack: Array<{ width: number; height: number }> = []; lifecycle.beforeTestSuite.add(async () => { - windowSizeStack.unshift( - await driver - .manage() - .window() - .getRect() - ); + windowSizeStack.unshift(await driver.manage().window().getRect()); }); lifecycle.beforeEachTest.add(async () => { @@ -130,10 +122,7 @@ export async function RemoteProvider({ getService }: FtrProviderContext) { lifecycle.afterTestSuite.add(async () => { const { width, height } = windowSizeStack.shift()!; - await driver - .manage() - .window() - .setRect({ width, height }); + await driver.manage().window().setRect({ width, height }); await clearBrowserStorage('sessionStorage'); await clearBrowserStorage('localStorage'); }); @@ -144,7 +133,7 @@ export async function RemoteProvider({ getService }: FtrProviderContext) { const coverageJson = await driver .executeScript('return window.__coverage__') .catch(() => undefined) - .then(coverage => coverage && JSON.stringify(coverage)); + .then((coverage) => coverage && JSON.stringify(coverage)); if (coverageJson) { writeCoverage(coverageJson); } diff --git a/test/functional/services/remote/webdriver.ts b/test/functional/services/remote/webdriver.ts index 27d17bf754659..9fbbf28bbf42c 100644 --- a/test/functional/services/remote/webdriver.ts +++ b/test/functional/services/remote/webdriver.ts @@ -241,8 +241,8 @@ async function attemptToCreateCommand( return { session, consoleLog$: chunk$.pipe( - map(chunk => chunk.toString('utf8')), - mergeMap(msg => { + map((chunk) => chunk.toString('utf8')), + mergeMap((msg) => { const match = msg.match(CONSOLE_LINE_RE); if (!match) { log.debug('Firefox stdout: ' + msg); diff --git a/test/functional/services/table.ts b/test/functional/services/table.ts index fc3bbbf8fba6f..8dbed2e5d250b 100644 --- a/test/functional/services/table.ts +++ b/test/functional/services/table.ts @@ -44,11 +44,11 @@ export function TableProvider({ getService }: FtrProviderContext) { const $ = await element.parseDomContent(); return $('tr') .toArray() - .map(row => + .map((row) => $(row) .find('td') .toArray() - .map(cell => + .map((cell) => $(cell) .text() .replace(/ /g, '') diff --git a/test/functional/services/visualizations/pie_chart.js b/test/functional/services/visualizations/pie_chart.js index 0ce44b5ec0117..edabc7ce989c0 100644 --- a/test/functional/services/visualizations/pie_chart.js +++ b/test/functional/services/visualizations/pie_chart.js @@ -67,14 +67,14 @@ export function PieChartProvider({ getService }) { log.debug(`VisualizePage.getAllPieSliceStyles(${name})`); const pieSlices = await this.getAllPieSlices(name); return await Promise.all( - pieSlices.map(async pieSlice => await pieSlice.getAttribute('style')) + pieSlices.map(async (pieSlice) => await pieSlice.getAttribute('style')) ); } async getPieChartData() { const chartTypes = await find.allByCssSelector('path.slice', defaultFindTimeout * 2); - const getChartTypesPromises = chartTypes.map(async chart => await chart.getAttribute('d')); + const getChartTypesPromises = chartTypes.map(async (chart) => await chart.getAttribute('d')); return await Promise.all(getChartTypesPromises); } @@ -88,7 +88,7 @@ export function PieChartProvider({ getService }) { const chartTypes = await find.allByCssSelector('path.slice', defaultFindTimeout * 2); const getChartTypesPromises = chartTypes.map( - async chart => await chart.getAttribute('data-label') + async (chart) => await chart.getAttribute('data-label') ); return await Promise.all(getChartTypesPromises); } diff --git a/test/harden/child_process.js b/test/harden/child_process.js index 11e2eeb07e0b6..df3e87746585f 100644 --- a/test/harden/child_process.js +++ b/test/harden/child_process.js @@ -31,7 +31,7 @@ test.onFinish(() => { delete Object.prototype.POLLUTED; }); -test('test setup ok', t => { +test('test setup ok', (t) => { t.equal({}.POLLUTED, 'polluted!'); t.end(); }); @@ -41,7 +41,7 @@ test('test setup ok', t => { // newer versions. See https://github.com/elastic/kibana/issues/59628 const functions = ['exec', 'execFile', 'spawn', 'execFileSync', 'execSync', 'spawnSync']; for (const name of functions) { - test(`${name}()`, t => { + test(`${name}()`, (t) => { t.throws(() => cp[name](), /argument must be of type string/); t.end(); }); @@ -50,11 +50,11 @@ for (const name of functions) { { const command = 'echo $POLLUTED$custom'; - test('exec(command)', t => { + test('exec(command)', (t) => { assertProcess(t, cp.exec(command)); }); - test('exec(command, callback)', t => { + test('exec(command, callback)', (t) => { cp.exec(command, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -63,15 +63,15 @@ for (const name of functions) { }); }); - test('exec(command, options)', t => { + test('exec(command, options)', (t) => { assertProcess(t, cp.exec(command, {})); }); - test('exec(command, options) - with custom env', t => { + test('exec(command, options) - with custom env', (t) => { assertProcess(t, cp.exec(command, { env: { custom: 'custom' } }), { stdout: 'custom' }); }); - test('exec(command, options, callback)', t => { + test('exec(command, options, callback)', (t) => { cp.exec(command, {}, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -80,7 +80,7 @@ for (const name of functions) { }); }); - test('exec(command, options, callback) - with custom env', t => { + test('exec(command, options, callback) - with custom env', (t) => { cp.exec(command, { env: { custom: 'custom' } }, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), 'custom'); @@ -90,11 +90,11 @@ for (const name of functions) { }); for (const unset of notSet) { - test(`exec(command, ${unset})`, t => { + test(`exec(command, ${unset})`, (t) => { assertProcess(t, cp.exec(command, unset)); }); - test(`exec(command, ${unset}, callback)`, t => { + test(`exec(command, ${unset}, callback)`, (t) => { cp.exec(command, unset, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -108,15 +108,15 @@ for (const name of functions) { { const file = path.join('test', 'harden', '_echo.sh'); - test('execFile(file)', t => { + test('execFile(file)', (t) => { assertProcess(t, cp.execFile(file)); }); - test('execFile(file, args)', t => { + test('execFile(file, args)', (t) => { assertProcess(t, cp.execFile(file, [])); }); - test('execFile(file, callback)', t => { + test('execFile(file, callback)', (t) => { cp.execFile(file, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -125,15 +125,15 @@ for (const name of functions) { }); }); - test('execFile(file, options)', t => { + test('execFile(file, options)', (t) => { assertProcess(t, cp.execFile(file, {})); }); - test('execFile(file, options) - with custom env', t => { + test('execFile(file, options) - with custom env', (t) => { assertProcess(t, cp.execFile(file, { env: { custom: 'custom' } }), { stdout: 'custom' }); }); - test('execFile(file, options, callback)', t => { + test('execFile(file, options, callback)', (t) => { cp.execFile(file, {}, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -142,7 +142,7 @@ for (const name of functions) { }); }); - test('execFile(file, options, callback) - with custom env', t => { + test('execFile(file, options, callback) - with custom env', (t) => { cp.execFile(file, { env: { custom: 'custom' } }, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), 'custom'); @@ -151,7 +151,7 @@ for (const name of functions) { }); }); - test('execFile(file, args, callback)', t => { + test('execFile(file, args, callback)', (t) => { cp.execFile(file, [], (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -160,15 +160,15 @@ for (const name of functions) { }); }); - test('execFile(file, args, options)', t => { + test('execFile(file, args, options)', (t) => { assertProcess(t, cp.execFile(file, [], {})); }); - test('execFile(file, args, options) - with custom env', t => { + test('execFile(file, args, options) - with custom env', (t) => { assertProcess(t, cp.execFile(file, [], { env: { custom: 'custom' } }), { stdout: 'custom' }); }); - test('execFile(file, args, options, callback)', t => { + test('execFile(file, args, options, callback)', (t) => { cp.execFile(file, [], {}, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -177,7 +177,7 @@ for (const name of functions) { }); }); - test('execFile(file, args, options, callback) - with custom env', t => { + test('execFile(file, args, options, callback) - with custom env', (t) => { cp.execFile(file, [], { env: { custom: 'custom' } }, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), 'custom'); @@ -187,15 +187,15 @@ for (const name of functions) { }); for (const unset of notSet) { - test(`execFile(file, ${unset})`, t => { + test(`execFile(file, ${unset})`, (t) => { assertProcess(t, cp.execFile(file, unset)); }); - test(`execFile(file, ${unset}, ${unset})`, t => { + test(`execFile(file, ${unset}, ${unset})`, (t) => { assertProcess(t, cp.execFile(file, unset, unset)); }); - test(`execFile(file, ${unset}, callback)`, t => { + test(`execFile(file, ${unset}, callback)`, (t) => { cp.execFile(file, unset, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -204,7 +204,7 @@ for (const name of functions) { }); }); - test(`execFile(file, ${unset}, ${unset}, callback)`, t => { + test(`execFile(file, ${unset}, ${unset}, callback)`, (t) => { cp.execFile(file, unset, unset, (err, stdout, stderr) => { t.error(err); t.equal(stdout.trim(), ''); @@ -213,7 +213,7 @@ for (const name of functions) { }); }); - test(`execFile(file, ${unset}, options)`, t => { + test(`execFile(file, ${unset}, options)`, (t) => { assertProcess(t, cp.execFile(file, unset, {})); }); } @@ -223,16 +223,16 @@ for (const name of functions) { const modulePath = path.join('test', 'harden', '_fork.js'); // NOTE: Forked processes don't have any stdout we can monitor without providing options - test.skip('fork(modulePath)', t => { + test.skip('fork(modulePath)', (t) => { assertProcess(t, cp.fork(modulePath)); }); // NOTE: Forked processes don't have any stdout we can monitor without providing options - test.skip('execFile(file, args)', t => { + test.skip('execFile(file, args)', (t) => { assertProcess(t, cp.fork(modulePath, [])); }); - test('fork(modulePath, options)', t => { + test('fork(modulePath, options)', (t) => { assertProcess( t, cp.fork(modulePath, { @@ -241,7 +241,7 @@ for (const name of functions) { ); }); - test('fork(modulePath, options) - with custom env', t => { + test('fork(modulePath, options) - with custom env', (t) => { assertProcess( t, cp.fork(modulePath, { @@ -252,7 +252,7 @@ for (const name of functions) { ); }); - test('fork(modulePath, args, options)', t => { + test('fork(modulePath, args, options)', (t) => { assertProcess( t, cp.fork(modulePath, [], { @@ -261,7 +261,7 @@ for (const name of functions) { ); }); - test('fork(modulePath, args, options) - with custom env', t => { + test('fork(modulePath, args, options) - with custom env', (t) => { assertProcess( t, cp.fork(modulePath, [], { @@ -274,16 +274,16 @@ for (const name of functions) { for (const unset of notSet) { // NOTE: Forked processes don't have any stdout we can monitor without providing options - test.skip(`fork(modulePath, ${unset})`, t => { + test.skip(`fork(modulePath, ${unset})`, (t) => { assertProcess(t, cp.fork(modulePath, unset)); }); // NOTE: Forked processes don't have any stdout we can monitor without providing options - test.skip(`fork(modulePath, ${unset}, ${unset})`, t => { + test.skip(`fork(modulePath, ${unset}, ${unset})`, (t) => { assertProcess(t, cp.fork(modulePath, unset, unset)); }); - test(`fork(modulePath, ${unset}, options)`, t => { + test(`fork(modulePath, ${unset}, options)`, (t) => { assertProcess( t, cp.fork(modulePath, unset, { @@ -297,40 +297,40 @@ for (const name of functions) { { const command = path.join('test', 'harden', '_echo.sh'); - test('spawn(command)', t => { + test('spawn(command)', (t) => { assertProcess(t, cp.spawn(command)); }); - test('spawn(command, args)', t => { + test('spawn(command, args)', (t) => { assertProcess(t, cp.spawn(command, [])); }); - test('spawn(command, options)', t => { + test('spawn(command, options)', (t) => { assertProcess(t, cp.spawn(command, {})); }); - test('spawn(command, options) - with custom env', t => { + test('spawn(command, options) - with custom env', (t) => { assertProcess(t, cp.spawn(command, { env: { custom: 'custom' } }), { stdout: 'custom' }); }); - test('spawn(command, args, options)', t => { + test('spawn(command, args, options)', (t) => { assertProcess(t, cp.spawn(command, [], {})); }); - test('spawn(command, args, options) - with custom env', t => { + test('spawn(command, args, options) - with custom env', (t) => { assertProcess(t, cp.spawn(command, [], { env: { custom: 'custom' } }), { stdout: 'custom' }); }); for (const unset of notSet) { - test(`spawn(command, ${unset})`, t => { + test(`spawn(command, ${unset})`, (t) => { assertProcess(t, cp.spawn(command, unset)); }); - test(`spawn(command, ${unset}, ${unset})`, t => { + test(`spawn(command, ${unset}, ${unset})`, (t) => { assertProcess(t, cp.spawn(command, unset, unset)); }); - test(`spawn(command, ${unset}, options)`, t => { + test(`spawn(command, ${unset}, options)`, (t) => { assertProcess(t, cp.spawn(command, unset, {})); }); } @@ -339,40 +339,22 @@ for (const name of functions) { { const file = path.join('test', 'harden', '_echo.sh'); - test('execFileSync(file)', t => { - t.equal( - cp - .execFileSync(file) - .toString() - .trim(), - '' - ); + test('execFileSync(file)', (t) => { + t.equal(cp.execFileSync(file).toString().trim(), ''); t.end(); }); - test('execFileSync(file, args)', t => { - t.equal( - cp - .execFileSync(file, []) - .toString() - .trim(), - '' - ); + test('execFileSync(file, args)', (t) => { + t.equal(cp.execFileSync(file, []).toString().trim(), ''); t.end(); }); - test('execFileSync(file, options)', t => { - t.equal( - cp - .execFileSync(file, {}) - .toString() - .trim(), - '' - ); + test('execFileSync(file, options)', (t) => { + t.equal(cp.execFileSync(file, {}).toString().trim(), ''); t.end(); }); - test('execFileSync(file, options) - with custom env', t => { + test('execFileSync(file, options) - with custom env', (t) => { t.equal( cp .execFileSync(file, { env: { custom: 'custom' } }) @@ -383,18 +365,12 @@ for (const name of functions) { t.end(); }); - test('execFileSync(file, args, options)', t => { - t.equal( - cp - .execFileSync(file, [], {}) - .toString() - .trim(), - '' - ); + test('execFileSync(file, args, options)', (t) => { + t.equal(cp.execFileSync(file, [], {}).toString().trim(), ''); t.end(); }); - test('execFileSync(file, args, options) - with custom env', t => { + test('execFileSync(file, args, options) - with custom env', (t) => { t.equal( cp .execFileSync(file, [], { env: { custom: 'custom' } }) @@ -406,36 +382,18 @@ for (const name of functions) { }); for (const unset of notSet) { - test(`execFileSync(file, ${unset})`, t => { - t.equal( - cp - .execFileSync(file, unset) - .toString() - .trim(), - '' - ); + test(`execFileSync(file, ${unset})`, (t) => { + t.equal(cp.execFileSync(file, unset).toString().trim(), ''); t.end(); }); - test(`execFileSync(file, ${unset}, ${unset})`, t => { - t.equal( - cp - .execFileSync(file, unset, unset) - .toString() - .trim(), - '' - ); + test(`execFileSync(file, ${unset}, ${unset})`, (t) => { + t.equal(cp.execFileSync(file, unset, unset).toString().trim(), ''); t.end(); }); - test(`execFileSync(file, ${unset}, options)`, t => { - t.equal( - cp - .execFileSync(file, unset, {}) - .toString() - .trim(), - '' - ); + test(`execFileSync(file, ${unset}, options)`, (t) => { + t.equal(cp.execFileSync(file, unset, {}).toString().trim(), ''); t.end(); }); } @@ -444,29 +402,17 @@ for (const name of functions) { { const command = 'echo $POLLUTED$custom'; - test('execSync(command)', t => { - t.equal( - cp - .execSync(command) - .toString() - .trim(), - '' - ); + test('execSync(command)', (t) => { + t.equal(cp.execSync(command).toString().trim(), ''); t.end(); }); - test('execSync(command, options)', t => { - t.equal( - cp - .execSync(command, {}) - .toString() - .trim(), - '' - ); + test('execSync(command, options)', (t) => { + t.equal(cp.execSync(command, {}).toString().trim(), ''); t.end(); }); - test('execSync(command, options) - with custom env', t => { + test('execSync(command, options) - with custom env', (t) => { t.equal( cp .execSync(command, { env: { custom: 'custom' } }) @@ -478,14 +424,8 @@ for (const name of functions) { }); for (const unset of notSet) { - test(`execSync(command, ${unset})`, t => { - t.equal( - cp - .execSync(command, unset) - .toString() - .trim(), - '' - ); + test(`execSync(command, ${unset})`, (t) => { + t.equal(cp.execSync(command, unset).toString().trim(), ''); t.end(); }); } @@ -494,7 +434,7 @@ for (const name of functions) { { const command = path.join('test', 'harden', '_echo.sh'); - test('spawnSync(command)', t => { + test('spawnSync(command)', (t) => { const result = cp.spawnSync(command); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -502,7 +442,7 @@ for (const name of functions) { t.end(); }); - test('spawnSync(command, args)', t => { + test('spawnSync(command, args)', (t) => { const result = cp.spawnSync(command, []); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -510,7 +450,7 @@ for (const name of functions) { t.end(); }); - test('spawnSync(command, options)', t => { + test('spawnSync(command, options)', (t) => { const result = cp.spawnSync(command, {}); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -518,7 +458,7 @@ for (const name of functions) { t.end(); }); - test('spawnSync(command, options) - with custom env', t => { + test('spawnSync(command, options) - with custom env', (t) => { const result = cp.spawnSync(command, { env: { custom: 'custom' } }); t.error(result.error); t.equal(result.stdout.toString().trim(), 'custom'); @@ -526,7 +466,7 @@ for (const name of functions) { t.end(); }); - test('spawnSync(command, args, options)', t => { + test('spawnSync(command, args, options)', (t) => { const result = cp.spawnSync(command, [], {}); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -534,7 +474,7 @@ for (const name of functions) { t.end(); }); - test('spawnSync(command, args, options) - with custom env', t => { + test('spawnSync(command, args, options) - with custom env', (t) => { const result = cp.spawnSync(command, [], { env: { custom: 'custom' } }); t.error(result.error); t.equal(result.stdout.toString().trim(), 'custom'); @@ -543,7 +483,7 @@ for (const name of functions) { }); for (const unset of notSet) { - test(`spawnSync(command, ${unset})`, t => { + test(`spawnSync(command, ${unset})`, (t) => { const result = cp.spawnSync(command, unset); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -551,7 +491,7 @@ for (const name of functions) { t.end(); }); - test(`spawnSync(command, ${unset}, ${unset})`, t => { + test(`spawnSync(command, ${unset}, ${unset})`, (t) => { const result = cp.spawnSync(command, unset, unset); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -559,7 +499,7 @@ for (const name of functions) { t.end(); }); - test(`spawnSync(command, ${unset}, options)`, t => { + test(`spawnSync(command, ${unset}, options)`, (t) => { const result = cp.spawnSync(command, unset, {}); t.error(result.error); t.equal(result.stdout.toString().trim(), ''); @@ -572,15 +512,15 @@ for (const name of functions) { function assertProcess(t, cmd, { stdout = '' } = {}) { t.plan(2); - cmd.stdout.on('data', data => { + cmd.stdout.on('data', (data) => { t.equal(data.toString().trim(), stdout); }); - cmd.stderr.on('data', data => { + cmd.stderr.on('data', (data) => { t.fail(`Unexpected data on STDERR: "${data}"`); }); - cmd.on('close', code => { + cmd.on('close', (code) => { t.equal(code, 0); t.end(); }); diff --git a/test/interpreter_functional/config.ts b/test/interpreter_functional/config.ts index d3cfcea9823e9..753fb03b52022 100644 --- a/test/interpreter_functional/config.ts +++ b/test/interpreter_functional/config.ts @@ -21,12 +21,12 @@ import path from 'path'; import fs from 'fs'; import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; -export default async function({ readConfigFile }: FtrConfigProviderContext) { +export default async function ({ readConfigFile }: FtrConfigProviderContext) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); // Find all folders in ./plugins since we treat all them as plugin folder const allFiles = fs.readdirSync(path.resolve(__dirname, 'plugins')); - const plugins = allFiles.filter(file => + const plugins = allFiles.filter((file) => fs.statSync(path.resolve(__dirname, 'plugins', file)).isDirectory() ); @@ -54,7 +54,7 @@ export default async function({ readConfigFile }: FtrConfigProviderContext) { // Required to load new platform plugins via `--plugin-path` flag. '--env.name=development', ...plugins.map( - pluginDir => `--plugin-path=${path.resolve(__dirname, 'plugins', pluginDir)}` + (pluginDir) => `--plugin-path=${path.resolve(__dirname, 'plugins', pluginDir)}` ), ], }, diff --git a/test/interpreter_functional/test_suites/run_pipeline/basic.ts b/test/interpreter_functional/test_suites/run_pipeline/basic.ts index a2172dd2da1ba..fa83174fe308a 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/basic.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/basic.ts @@ -23,7 +23,7 @@ import { FtrProviderContext } from '../../../functional/ftr_provider_context'; // this file showcases how to use testing utilities defined in helpers.ts together with the kbn_tp_run_pipeline // test plugin to write automated tests for interpreter -export default function({ +export default function ({ getService, updateBaselines, }: FtrProviderContext & { updateBaselines: boolean }) { diff --git a/test/interpreter_functional/test_suites/run_pipeline/esaggs.ts b/test/interpreter_functional/test_suites/run_pipeline/esaggs.ts index 5ea151dffdc8e..96140b003af18 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/esaggs.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/esaggs.ts @@ -29,7 +29,7 @@ function getCell(esaggsResult: any, column: number, row: number): unknown | unde return esaggsResult?.rows[row]?.[columnId]; } -export default function({ +export default function ({ getService, updateBaselines, }: FtrProviderContext & { updateBaselines: boolean }) { diff --git a/test/interpreter_functional/test_suites/run_pipeline/index.ts b/test/interpreter_functional/test_suites/run_pipeline/index.ts index 9590f9f8c1794..9675047c24054 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/index.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/index.ts @@ -19,7 +19,7 @@ import { FtrProviderContext } from '../../../functional/ftr_provider_context'; -export default function({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { +export default function ({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); @@ -27,7 +27,7 @@ export default function({ getService, getPageObjects, loadTestFile }: FtrProvide const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common', 'header']); - describe('runPipeline', function() { + describe('runPipeline', function () { this.tags(['skipFirefox']); before(async () => { diff --git a/test/interpreter_functional/test_suites/run_pipeline/metric.ts b/test/interpreter_functional/test_suites/run_pipeline/metric.ts index 5f685037d4fad..a816cdeb4c6e5 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/metric.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/metric.ts @@ -20,7 +20,7 @@ import { ExpectExpression, expectExpressionProvider, ExpressionResult } from './helpers'; import { FtrProviderContext } from '../../../functional/ftr_provider_context'; -export default function({ +export default function ({ getService, updateBaselines, }: FtrProviderContext & { updateBaselines: boolean }) { diff --git a/test/interpreter_functional/test_suites/run_pipeline/tag_cloud.ts b/test/interpreter_functional/test_suites/run_pipeline/tag_cloud.ts index 2451df4db6310..b8da8f2f0c146 100644 --- a/test/interpreter_functional/test_suites/run_pipeline/tag_cloud.ts +++ b/test/interpreter_functional/test_suites/run_pipeline/tag_cloud.ts @@ -20,7 +20,7 @@ import { ExpectExpression, expectExpressionProvider, ExpressionResult } from './helpers'; import { FtrProviderContext } from '../../../functional/ftr_provider_context'; -export default function({ +export default function ({ getService, updateBaselines, }: FtrProviderContext & { updateBaselines: boolean }) { diff --git a/test/plugin_functional/config.js b/test/plugin_functional/config.js index c7fa0f40e1d0c..9039f7e734a6e 100644 --- a/test/plugin_functional/config.js +++ b/test/plugin_functional/config.js @@ -21,12 +21,12 @@ import path from 'path'; import fs from 'fs'; import { services } from './services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); // Find all folders in ./plugins since we treat all them as plugin folder const allFiles = fs.readdirSync(path.resolve(__dirname, 'plugins')); - const plugins = allFiles.filter(file => + const plugins = allFiles.filter((file) => fs.statSync(path.resolve(__dirname, 'plugins', file)).isDirectory() ); @@ -63,7 +63,7 @@ export default async function({ readConfigFile }) { // Required to load new platform plugins via `--plugin-path` flag. '--env.name=development', ...plugins.map( - pluginDir => `--plugin-path=${path.resolve(__dirname, 'plugins', pluginDir)}` + (pluginDir) => `--plugin-path=${path.resolve(__dirname, 'plugins', pluginDir)}` ), ], }, diff --git a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts index 6535a54f6b744..1b9496be36526 100644 --- a/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts +++ b/test/plugin_functional/plugins/core_plugin_a/server/plugin.ts @@ -31,7 +31,7 @@ declare module 'kibana/server' { export class CorePluginAPlugin implements Plugin { public setup(core: CoreSetup, deps: {}) { - core.http.registerRouteHandlerContext('pluginA', context => { + core.http.registerRouteHandlerContext('pluginA', (context) => { return { ping: () => context.core.elasticsearch.adminClient.callAsInternalUser('ping') as Promise, diff --git a/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx index 336bb9d787895..9e54165e72713 100644 --- a/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_appleave/public/plugin.tsx @@ -27,7 +27,7 @@ export class CoreAppLeavePlugin title: 'AppLeave 1', async mount(context, params) { const { renderApp } = await import('./application'); - params.onAppLeave(actions => actions.confirm('confirm-message', 'confirm-title')); + params.onAppLeave((actions) => actions.confirm('confirm-message', 'confirm-title')); return renderApp('AppLeave 1', params); }, }); @@ -36,7 +36,7 @@ export class CoreAppLeavePlugin title: 'AppLeave 2', async mount(context, params) { const { renderApp } = await import('./application'); - params.onAppLeave(actions => actions.default()); + params.onAppLeave((actions) => actions.default()); return renderApp('AppLeave 2', params); }, }); diff --git a/test/plugin_functional/plugins/core_plugin_legacy/index.ts b/test/plugin_functional/plugins/core_plugin_legacy/index.ts index d91f3293e28d7..fde67a2f9243f 100644 --- a/test/plugin_functional/plugins/core_plugin_legacy/index.ts +++ b/test/plugin_functional/plugins/core_plugin_legacy/index.ts @@ -20,7 +20,7 @@ import KbnServer from 'src/legacy/server/kbn_server'; // eslint-disable-next-line import/no-default-export -export default function(kibana: any) { +export default function (kibana: any) { return new kibana.Plugin({ id: 'core_plugin_legacy', require: ['kibana'], diff --git a/test/plugin_functional/plugins/core_provider_plugin/public/index.ts b/test/plugin_functional/plugins/core_provider_plugin/public/index.ts index 2f271fe5ef65b..ac2d63bb9fd75 100644 --- a/test/plugin_functional/plugins/core_provider_plugin/public/index.ts +++ b/test/plugin_functional/plugins/core_provider_plugin/public/index.ts @@ -38,7 +38,7 @@ class CoreProviderPlugin implements Plugin { plugins, }, testUtils: { - delay: (ms: number) => new Promise(res => setTimeout(res, ms)), + delay: (ms: number) => new Promise((res) => setTimeout(res, ms)), }, }; } diff --git a/test/plugin_functional/plugins/doc_views_plugin/public/plugin.tsx b/test/plugin_functional/plugins/doc_views_plugin/public/plugin.tsx index 4b9823fda3673..742f2ab11f968 100644 --- a/test/plugin_functional/plugins/doc_views_plugin/public/plugin.tsx +++ b/test/plugin_functional/plugins/doc_views_plugin/public/plugin.tsx @@ -48,7 +48,7 @@ export class DocViewsPlugin implements Plugin { }); discover.docViews.addDocView({ - component: props => { + component: (props) => { return ; }, order: 2, diff --git a/test/plugin_functional/plugins/legacy_plugin/index.ts b/test/plugin_functional/plugins/legacy_plugin/index.ts index a7578f4f82dcd..fe171cb24e7b7 100644 --- a/test/plugin_functional/plugins/legacy_plugin/index.ts +++ b/test/plugin_functional/plugins/legacy_plugin/index.ts @@ -18,7 +18,7 @@ */ // eslint-disable-next-line import/no-default-export -export default function(kibana: any) { +export default function (kibana: any) { return new kibana.Plugin({ id: 'legacy_plugin', require: ['kibana'], diff --git a/test/plugin_functional/test_suites/bfetch_explorer/batched_function.ts b/test/plugin_functional/test_suites/bfetch_explorer/batched_function.ts index cb2a0b41694c2..25c5ba4a7ca3e 100644 --- a/test/plugin_functional/test_suites/bfetch_explorer/batched_function.ts +++ b/test/plugin_functional/test_suites/bfetch_explorer/batched_function.ts @@ -20,7 +20,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../../functional/ftr_provider_context'; -export default function({ getService }: FtrProviderContext) { +export default function ({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); const appsMenu = getService('appsMenu'); @@ -35,7 +35,7 @@ export default function({ getService }: FtrProviderContext) { const form = await testSubjects.find('DoubleIntegers'); const btn = await form.findByCssSelector('button'); await btn.click(); - await new Promise(r => setTimeout(r, 4000)); + await new Promise((r) => setTimeout(r, 4000)); const pre = await form.findByCssSelector('pre'); const text = await pre.getVisibleText(); const json = JSON.parse(text); @@ -73,7 +73,7 @@ export default function({ getService }: FtrProviderContext) { const btn = await form.findByCssSelector('button'); await btn.click(); - await new Promise(r => setTimeout(r, 500)); + await new Promise((r) => setTimeout(r, 500)); const pre = await form.findByCssSelector('pre'); const text1 = await pre.getVisibleText(); @@ -82,7 +82,7 @@ export default function({ getService }: FtrProviderContext) { expect(json1.length > 0).to.be(true); expect(json1.length < 4).to.be(true); - await new Promise(r => setTimeout(r, 3500)); + await new Promise((r) => setTimeout(r, 3500)); const text2 = await pre.getVisibleText(); const json2 = JSON.parse(text2); diff --git a/test/plugin_functional/test_suites/bfetch_explorer/index.ts b/test/plugin_functional/test_suites/bfetch_explorer/index.ts index 54f127d6de89a..a68a5090b9bed 100644 --- a/test/plugin_functional/test_suites/bfetch_explorer/index.ts +++ b/test/plugin_functional/test_suites/bfetch_explorer/index.ts @@ -19,12 +19,12 @@ import { FtrProviderContext } from '../../../functional/ftr_provider_context'; -export default function({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { +export default function ({ getService, getPageObjects, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); const appsMenu = getService('appsMenu'); const PageObjects = getPageObjects(['common', 'header']); - describe('bfetch explorer', function() { + describe('bfetch explorer', function () { before(async () => { await browser.setWindowSize(1300, 900); await PageObjects.common.navigateToApp('settings'); diff --git a/test/plugin_functional/test_suites/core_plugins/application_leave_confirm.ts b/test/plugin_functional/test_suites/core_plugins/application_leave_confirm.ts index 7f5580dc6fa54..d2e23f7d9572e 100644 --- a/test/plugin_functional/test_suites/core_plugins/application_leave_confirm.ts +++ b/test/plugin_functional/test_suites/core_plugins/application_leave_confirm.ts @@ -30,7 +30,7 @@ const getKibanaUrl = (pathname?: string, search?: string) => }); // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); const appsMenu = getService('appsMenu'); diff --git a/test/plugin_functional/test_suites/core_plugins/application_status.ts b/test/plugin_functional/test_suites/core_plugins/application_status.ts index b2c0413c5024b..96bcda39f3981 100644 --- a/test/plugin_functional/test_suites/core_plugins/application_status.ts +++ b/test/plugin_functional/test_suites/core_plugins/application_status.ts @@ -37,7 +37,7 @@ const getKibanaUrl = (pathname?: string, search?: string) => }); // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); const appsMenu = getService('appsMenu'); diff --git a/test/plugin_functional/test_suites/core_plugins/applications.ts b/test/plugin_functional/test_suites/core_plugins/applications.ts index 7cf78f280a4a4..64d27103e59e2 100644 --- a/test/plugin_functional/test_suites/core_plugins/applications.ts +++ b/test/plugin_functional/test_suites/core_plugins/applications.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from '../../services'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); diff --git a/test/plugin_functional/test_suites/core_plugins/index.ts b/test/plugin_functional/test_suites/core_plugins/index.ts index d57ad11ea004e..8f54ec6c0f4cd 100644 --- a/test/plugin_functional/test_suites/core_plugins/index.ts +++ b/test/plugin_functional/test_suites/core_plugins/index.ts @@ -19,7 +19,7 @@ import { PluginFunctionalProviderContext } from '../../services'; // eslint-disable-next-line import/no-default-export -export default function({ loadTestFile }: PluginFunctionalProviderContext) { +export default function ({ loadTestFile }: PluginFunctionalProviderContext) { describe('core plugins', () => { loadTestFile(require.resolve('./applications')); loadTestFile(require.resolve('./legacy_plugins')); diff --git a/test/plugin_functional/test_suites/core_plugins/legacy_plugins.ts b/test/plugin_functional/test_suites/core_plugins/legacy_plugins.ts index 948679c64e88b..cb3a24375607e 100644 --- a/test/plugin_functional/test_suites/core_plugins/legacy_plugins.ts +++ b/test/plugin_functional/test_suites/core_plugins/legacy_plugins.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from '../../services'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const testSubjects = getService('testSubjects'); const supertest = getService('supertest'); diff --git a/test/plugin_functional/test_suites/core_plugins/rendering.ts b/test/plugin_functional/test_suites/core_plugins/rendering.ts index b8e26b8e6ffcb..7ae6865d45a97 100644 --- a/test/plugin_functional/test_suites/core_plugins/rendering.ts +++ b/test/plugin_functional/test_suites/core_plugins/rendering.ts @@ -33,7 +33,7 @@ declare global { } // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const appsMenu = getService('appsMenu'); const browser = getService('browser'); diff --git a/test/plugin_functional/test_suites/core_plugins/server_plugins.ts b/test/plugin_functional/test_suites/core_plugins/server_plugins.ts index f5b45d36944e1..00f242ccc62f6 100644 --- a/test/plugin_functional/test_suites/core_plugins/server_plugins.ts +++ b/test/plugin_functional/test_suites/core_plugins/server_plugins.ts @@ -20,15 +20,12 @@ import { PluginFunctionalProviderContext } from '../../services'; // eslint-disable-next-line import/no-default-export -export default function({ getService }: PluginFunctionalProviderContext) { +export default function ({ getService }: PluginFunctionalProviderContext) { const supertest = getService('supertest'); describe('server plugins', function describeIndexTests() { it('extend request handler context', async () => { - await supertest - .get('/core_plugin_b') - .expect(200) - .expect('Pong via plugin A: true'); + await supertest.get('/core_plugin_b').expect(200).expect('Pong via plugin A: true'); }); it('extend request handler context with validation', async () => { diff --git a/test/plugin_functional/test_suites/core_plugins/top_nav.js b/test/plugin_functional/test_suites/core_plugins/top_nav.js index 0a7288276652f..5c46e3d7f76db 100644 --- a/test/plugin_functional/test_suites/core_plugins/top_nav.js +++ b/test/plugin_functional/test_suites/core_plugins/top_nav.js @@ -18,7 +18,7 @@ */ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); diff --git a/test/plugin_functional/test_suites/core_plugins/ui_plugins.ts b/test/plugin_functional/test_suites/core_plugins/ui_plugins.ts index b2393443989f9..929d5b68be93d 100644 --- a/test/plugin_functional/test_suites/core_plugins/ui_plugins.ts +++ b/test/plugin_functional/test_suites/core_plugins/ui_plugins.ts @@ -22,12 +22,12 @@ import { PluginFunctionalProviderContext } from '../../services'; import '../../../../test/plugin_functional/plugins/core_provider_plugin/types'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); const supertest = getService('supertest'); - describe('ui plugins', function() { + describe('ui plugins', function () { describe('loading', function describeIndexTests() { before(async () => { await PageObjects.common.navigateToApp('settings'); @@ -49,7 +49,7 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider it('to start services via coreSetup.getStartServices', async () => { expect( - await browser.executeAsync(async cb => { + await browser.executeAsync(async (cb) => { const [coreStart] = await window.__coreProvider.setup.core.getStartServices(); cb(Boolean(coreStart.overlays)); }) @@ -76,7 +76,7 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider it('should send kbn-system-request header when asSystemRequest: true', async () => { expect( - await browser.executeAsync(async cb => { + await browser.executeAsync(async (cb) => { window.__coreProvider.start.plugins.core_plugin_b.sendSystemRequest(true).then(cb); }) ).to.be('/core_plugin_b/system_request says: "System request? true"'); @@ -84,27 +84,27 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider it('should not send kbn-system-request header when asSystemRequest: false', async () => { expect( - await browser.executeAsync(async cb => { + await browser.executeAsync(async (cb) => { window.__coreProvider.start.plugins.core_plugin_b.sendSystemRequest(false).then(cb); }) ).to.be('/core_plugin_b/system_request says: "System request? false"'); }); }); - describe('Plugin static assets', function() { + describe('Plugin static assets', function () { it('exposes static assets from "public/assets" folder', async () => { await supertest.get('/plugins/corePluginStaticAssets/assets/chart.svg').expect(200); }); - it('returns 404 if not found', async function() { + it('returns 404 if not found', async function () { await supertest.get('/plugins/corePluginStaticAssets/assets/not-a-chart.svg').expect(404); }); - it('does not expose folder content', async function() { + it('does not expose folder content', async function () { await supertest.get('/plugins/corePluginStaticAssets/assets/').expect(403); }); - it('does not allow file tree traversing', async function() { + it('does not allow file tree traversing', async function () { await supertest.get('/plugins/corePluginStaticAssets/assets/../../kibana.json').expect(404); }); diff --git a/test/plugin_functional/test_suites/core_plugins/ui_settings.ts b/test/plugin_functional/test_suites/core_plugins/ui_settings.ts index dec79fd15f4dd..6a0a5fed48e6d 100644 --- a/test/plugin_functional/test_suites/core_plugins/ui_settings.ts +++ b/test/plugin_functional/test_suites/core_plugins/ui_settings.ts @@ -21,12 +21,12 @@ import { PluginFunctionalProviderContext } from '../../services'; import '../../plugins/core_provider_plugin/types'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); const browser = getService('browser'); const supertest = getService('supertest'); - describe('ui settings', function() { + describe('ui settings', function () { before(async () => { await PageObjects.common.navigateToApp('settings'); }); @@ -52,17 +52,14 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider const settingsValueViaObservables = await browser.executeAsync(async (callback: Function) => { window.__coreProvider.setup.core.uiSettings .get$('ui_settings_plugin') - .subscribe(v => callback(v)); + .subscribe((v) => callback(v)); }); expect(settingsValueViaObservables).to.be('2'); }); it('server plugins have access to registered settings', async () => { - await supertest - .get('/api/ui-settings-plugin') - .expect(200) - .expect({ uiSettingsValue: 2 }); + await supertest.get('/api/ui-settings-plugin').expect(200).expect({ uiSettingsValue: 2 }); }); }); } diff --git a/test/plugin_functional/test_suites/custom_visualizations/index.js b/test/plugin_functional/test_suites/custom_visualizations/index.js index 1b2388495ad8d..a38318127f1bb 100644 --- a/test/plugin_functional/test_suites/custom_visualizations/index.js +++ b/test/plugin_functional/test_suites/custom_visualizations/index.js @@ -17,12 +17,12 @@ * under the License. */ -export default function({ getService, loadTestFile }) { +export default function ({ getService, loadTestFile }) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); - describe('custom visualizations', function() { + describe('custom visualizations', function () { before(async () => { await esArchiver.loadIfNeeded('../functional/fixtures/es_archiver/logstash_functional'); await esArchiver.loadIfNeeded('../functional/fixtures/es_archiver/visualize'); diff --git a/test/plugin_functional/test_suites/custom_visualizations/self_changing_vis.js b/test/plugin_functional/test_suites/custom_visualizations/self_changing_vis.js index 83258a1ca3bdc..0846780f75ff6 100644 --- a/test/plugin_functional/test_suites/custom_visualizations/self_changing_vis.js +++ b/test/plugin_functional/test_suites/custom_visualizations/self_changing_vis.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); const renderable = getService('renderable'); const PageObjects = getPageObjects(['common', 'visualize', 'visEditor']); diff --git a/test/plugin_functional/test_suites/doc_views/doc_views.ts b/test/plugin_functional/test_suites/doc_views/doc_views.ts index 8764f45c2c076..87b4dc2a63d5a 100644 --- a/test/plugin_functional/test_suites/doc_views/doc_views.ts +++ b/test/plugin_functional/test_suites/doc_views/doc_views.ts @@ -21,12 +21,12 @@ import expect from '@kbn/expect'; import { PluginFunctionalProviderContext } from '../../services'; // eslint-disable-next-line import/no-default-export -export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { +export default function ({ getService, getPageObjects }: PluginFunctionalProviderContext) { const testSubjects = getService('testSubjects'); const find = getService('find'); const PageObjects = getPageObjects(['common', 'discover', 'timePicker']); - describe('custom doc views', function() { + describe('custom doc views', function () { before(async () => { await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setDefaultAbsoluteRange(); diff --git a/test/plugin_functional/test_suites/doc_views/index.ts b/test/plugin_functional/test_suites/doc_views/index.ts index dee3a72e3f2c6..328d651f73752 100644 --- a/test/plugin_functional/test_suites/doc_views/index.ts +++ b/test/plugin_functional/test_suites/doc_views/index.ts @@ -18,10 +18,10 @@ */ import { PluginFunctionalProviderContext } from '../../services'; -export default function({ getService, loadTestFile }: PluginFunctionalProviderContext) { +export default function ({ getService, loadTestFile }: PluginFunctionalProviderContext) { const esArchiver = getService('esArchiver'); - describe('doc views', function() { + describe('doc views', function () { before(async () => { await esArchiver.loadIfNeeded('../functional/fixtures/es_archiver/discover'); }); diff --git a/test/plugin_functional/test_suites/embeddable_explorer/dashboard_container.js b/test/plugin_functional/test_suites/embeddable_explorer/dashboard_container.js index 4a1bcecc0d5a1..9a1d6c1e38fc0 100644 --- a/test/plugin_functional/test_suites/embeddable_explorer/dashboard_container.js +++ b/test/plugin_functional/test_suites/embeddable_explorer/dashboard_container.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const testSubjects = getService('testSubjects'); const pieChart = getService('pieChart'); const dashboardExpect = getService('dashboardExpect'); diff --git a/test/plugin_functional/test_suites/embeddable_explorer/index.js b/test/plugin_functional/test_suites/embeddable_explorer/index.js index e1eb4cf1185e6..b122d9740dc96 100644 --- a/test/plugin_functional/test_suites/embeddable_explorer/index.js +++ b/test/plugin_functional/test_suites/embeddable_explorer/index.js @@ -17,14 +17,14 @@ * under the License. */ -export default function({ getService, getPageObjects, loadTestFile }) { +export default function ({ getService, getPageObjects, loadTestFile }) { const browser = getService('browser'); const appsMenu = getService('appsMenu'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'header']); - describe('embeddable explorer', function() { + describe('embeddable explorer', function () { before(async () => { await esArchiver.loadIfNeeded('../functional/fixtures/es_archiver/dashboard/current/data'); await esArchiver.load('../functional/fixtures/es_archiver/dashboard/current/kibana'); diff --git a/test/plugin_functional/test_suites/management/index.js b/test/plugin_functional/test_suites/management/index.js index 2bfc05547b292..319f78dab2df9 100644 --- a/test/plugin_functional/test_suites/management/index.js +++ b/test/plugin_functional/test_suites/management/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ loadTestFile }) { +export default function ({ loadTestFile }) { describe('management plugin', () => { loadTestFile(require.resolve('./management_plugin')); }); diff --git a/test/plugin_functional/test_suites/management/management_plugin.js b/test/plugin_functional/test_suites/management/management_plugin.js index 6ad2bb56391dd..87542c97a3f5d 100644 --- a/test/plugin_functional/test_suites/management/management_plugin.js +++ b/test/plugin_functional/test_suites/management/management_plugin.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['common']); diff --git a/test/plugin_functional/test_suites/panel_actions/index.js b/test/plugin_functional/test_suites/panel_actions/index.js index bacd930c76e56..40c063d1afc5e 100644 --- a/test/plugin_functional/test_suites/panel_actions/index.js +++ b/test/plugin_functional/test_suites/panel_actions/index.js @@ -28,13 +28,13 @@ export const DATA_ARCHIVE_PATH = path.resolve( '../../../functional/fixtures/es_archiver/dashboard/current/data' ); -export default function({ getService, getPageObjects, loadTestFile }) { +export default function ({ getService, getPageObjects, loadTestFile }) { const browser = getService('browser'); const esArchiver = getService('esArchiver'); const kibanaServer = getService('kibanaServer'); const PageObjects = getPageObjects(['common', 'dashboard']); - describe('pluggable panel actions', function() { + describe('pluggable panel actions', function () { before(async () => { await browser.setWindowSize(1300, 900); await esArchiver.load(KIBANA_ARCHIVE_PATH); @@ -46,7 +46,7 @@ export default function({ getService, getPageObjects, loadTestFile }) { await PageObjects.dashboard.preserveCrossAppState(); }); - after(async function() { + after(async function () { await PageObjects.dashboard.clearSavedObjectsFromAppLinks(); await esArchiver.unload(KIBANA_ARCHIVE_PATH); await esArchiver.unload(DATA_ARCHIVE_PATH); diff --git a/test/plugin_functional/test_suites/panel_actions/panel_actions.js b/test/plugin_functional/test_suites/panel_actions/panel_actions.js index 26c8322b0b053..b06b4e55f31c0 100644 --- a/test/plugin_functional/test_suites/panel_actions/panel_actions.js +++ b/test/plugin_functional/test_suites/panel_actions/panel_actions.js @@ -19,7 +19,7 @@ import expect from '@kbn/expect'; -export default function({ getService, getPageObjects }) { +export default function ({ getService, getPageObjects }) { const dashboardPanelActions = getService('dashboardPanelActions'); const testSubjects = getService('testSubjects'); const PageObjects = getPageObjects(['dashboard']); diff --git a/test/server_integration/config.js b/test/server_integration/config.js index 26e00e5fce294..aa9266321664c 100644 --- a/test/server_integration/config.js +++ b/test/server_integration/config.js @@ -23,7 +23,7 @@ import { ElasticsearchSupertestProvider, } from './services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const commonConfig = await readConfigFile(require.resolve('../common/config')); const functionalConfig = await readConfigFile(require.resolve('../functional/config')); diff --git a/test/server_integration/http/cache/config.js b/test/server_integration/http/cache/config.js index 10acf94f0a3cf..de20bc6fc1f14 100644 --- a/test/server_integration/http/cache/config.js +++ b/test/server_integration/http/cache/config.js @@ -17,7 +17,7 @@ * under the License. */ -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const httpConfig = await readConfigFile(require.resolve('../../config')); return { diff --git a/test/server_integration/http/cache/index.js b/test/server_integration/http/cache/index.js index 3aff35ca12928..8cca8cf7bd99d 100644 --- a/test/server_integration/http/cache/index.js +++ b/test/server_integration/http/cache/index.js @@ -18,7 +18,7 @@ */ // eslint-disable-next-line import/no-default-export -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana server cache-control', () => { diff --git a/test/server_integration/http/ssl/config.js b/test/server_integration/http/ssl/config.js index 2f2e7b778d361..a7cbd0cce2570 100644 --- a/test/server_integration/http/ssl/config.js +++ b/test/server_integration/http/ssl/config.js @@ -21,7 +21,7 @@ import { readFileSync } from 'fs'; import { CA_CERT_PATH, KBN_CERT_PATH, KBN_KEY_PATH } from '@kbn/dev-utils'; import { createKibanaSupertestProvider } from '../../services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const httpConfig = await readConfigFile(require.resolve('../../config')); return { diff --git a/test/server_integration/http/ssl/index.js b/test/server_integration/http/ssl/index.js index 25e28f12ceaaa..66333f0aeeeb6 100644 --- a/test/server_integration/http/ssl/index.js +++ b/test/server_integration/http/ssl/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana server with ssl', () => { diff --git a/test/server_integration/http/ssl_redirect/config.js b/test/server_integration/http/ssl_redirect/config.js index 20ab4a210cc7b..ab3bd2a19c005 100644 --- a/test/server_integration/http/ssl_redirect/config.js +++ b/test/server_integration/http/ssl_redirect/config.js @@ -22,7 +22,7 @@ import { CA_CERT_PATH, KBN_CERT_PATH, KBN_KEY_PATH } from '@kbn/dev-utils'; import { createKibanaSupertestProvider } from '../../services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const httpConfig = await readConfigFile(require.resolve('../../config')); const redirectPort = httpConfig.get('servers.kibana.port') + 1; diff --git a/test/server_integration/http/ssl_redirect/index.js b/test/server_integration/http/ssl_redirect/index.js index 8e6c801133171..3a7b0e310fb23 100644 --- a/test/server_integration/http/ssl_redirect/index.js +++ b/test/server_integration/http/ssl_redirect/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana server with ssl', () => { @@ -26,16 +26,9 @@ export default function({ getService }) { const port = process.env.TEST_KIBANA_PORT || '5620'; const url = `https://${host}:${port}/`; - await supertest - .get('/') - .expect('location', url) - .expect(302); + await supertest.get('/').expect('location', url).expect(302); - await supertest - .get('/') - .redirects(1) - .expect('location', '/app/kibana') - .expect(302); + await supertest.get('/').redirects(1).expect('location', '/app/kibana').expect(302); }); }); } diff --git a/test/server_integration/http/ssl_with_p12/config.js b/test/server_integration/http/ssl_with_p12/config.js index e220914af54f4..88c03302fb754 100644 --- a/test/server_integration/http/ssl_with_p12/config.js +++ b/test/server_integration/http/ssl_with_p12/config.js @@ -21,7 +21,7 @@ import { readFileSync } from 'fs'; import { CA_CERT_PATH, KBN_P12_PATH, KBN_P12_PASSWORD } from '@kbn/dev-utils'; import { createKibanaSupertestProvider } from '../../services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const httpConfig = await readConfigFile(require.resolve('../../config')); return { diff --git a/test/server_integration/http/ssl_with_p12/index.js b/test/server_integration/http/ssl_with_p12/index.js index 700f30ddc21a9..fea57b85124e2 100644 --- a/test/server_integration/http/ssl_with_p12/index.js +++ b/test/server_integration/http/ssl_with_p12/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana server with ssl', () => { diff --git a/test/server_integration/http/ssl_with_p12_intermediate/config.js b/test/server_integration/http/ssl_with_p12_intermediate/config.js index 73a77425ec774..24f8eefd1077e 100644 --- a/test/server_integration/http/ssl_with_p12_intermediate/config.js +++ b/test/server_integration/http/ssl_with_p12_intermediate/config.js @@ -21,7 +21,7 @@ import { readFileSync } from 'fs'; import { CA1_CERT_PATH, CA2_CERT_PATH, EE_P12_PATH, EE_P12_PASSWORD } from '../../__fixtures__'; import { createKibanaSupertestProvider } from '../../services'; -export default async function({ readConfigFile }) { +export default async function ({ readConfigFile }) { const httpConfig = await readConfigFile(require.resolve('../../config')); return { diff --git a/test/server_integration/http/ssl_with_p12_intermediate/index.js b/test/server_integration/http/ssl_with_p12_intermediate/index.js index fb079a4e091c3..1ba4bd3f56c5e 100644 --- a/test/server_integration/http/ssl_with_p12_intermediate/index.js +++ b/test/server_integration/http/ssl_with_p12_intermediate/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function({ getService }) { +export default function ({ getService }) { const supertest = getService('supertest'); describe('kibana server with ssl', () => { diff --git a/test/server_integration/services/supertest.js b/test/server_integration/services/supertest.js index 74bb5400bc299..9d38b83d4bcd1 100644 --- a/test/server_integration/services/supertest.js +++ b/test/server_integration/services/supertest.js @@ -22,7 +22,7 @@ import { format as formatUrl } from 'url'; import supertestAsPromised from 'supertest-as-promised'; export function createKibanaSupertestProvider({ certificateAuthorities, options } = {}) { - return function({ getService }) { + return function ({ getService }) { const config = getService('config'); const kibanaServerUrl = options ? formatUrl(options) : formatUrl(config.get('servers.kibana')); diff --git a/test/ui_capabilities/newsfeed_err/test.ts b/test/ui_capabilities/newsfeed_err/test.ts index 2aa81f34028a0..04d7284e4b347 100644 --- a/test/ui_capabilities/newsfeed_err/test.ts +++ b/test/ui_capabilities/newsfeed_err/test.ts @@ -25,7 +25,7 @@ export default function uiCapabilitiesTests({ getService, getPageObjects }: FtrP const globalNav = getService('globalNav'); const PageObjects = getPageObjects(['common', 'newsfeed']); - describe('Newsfeed icon button handle errors', function() { + describe('Newsfeed icon button handle errors', function () { this.tags('ciGroup6'); before(async () => { diff --git a/test/visual_regression/config.ts b/test/visual_regression/config.ts index 77450b517dcc6..cc230c6b4cff9 100644 --- a/test/visual_regression/config.ts +++ b/test/visual_regression/config.ts @@ -20,7 +20,7 @@ import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; import { services } from './services'; -export default async function({ readConfigFile }: FtrConfigProviderContext) { +export default async function ({ readConfigFile }: FtrConfigProviderContext) { const functionalConfig = await readConfigFile(require.resolve('../functional/config')); return { diff --git a/test/visual_regression/services/visual_testing/visual_testing.ts b/test/visual_regression/services/visual_testing/visual_testing.ts index 0882beecf7f5c..3a71c3aa9d3d6 100644 --- a/test/visual_regression/services/visual_testing/visual_testing.ts +++ b/test/visual_regression/services/visual_testing/visual_testing.ts @@ -54,7 +54,7 @@ export async function VisualTestingProvider({ getService }: FtrProviderContext) const lifecycle = getService('lifecycle'); let currentTest: Test | undefined; - lifecycle.beforeEachTest.add(test => { + lifecycle.beforeEachTest.add((test) => { currentTest = test; }); diff --git a/test/visual_regression/tests/console_app.ts b/test/visual_regression/tests/console_app.ts index 555664f31e826..a7392cc8b90dd 100644 --- a/test/visual_regression/tests/console_app.ts +++ b/test/visual_regression/tests/console_app.ts @@ -31,7 +31,7 @@ GET _search `.trim(); -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const retry = getService('retry'); const log = getService('log'); const visualTesting = getService('visualTesting'); diff --git a/test/visual_regression/tests/discover/chart_visualization.ts b/test/visual_regression/tests/discover/chart_visualization.ts index 5d37471dd8f30..1564e43b112ee 100644 --- a/test/visual_regression/tests/discover/chart_visualization.ts +++ b/test/visual_regression/tests/discover/chart_visualization.ts @@ -21,7 +21,7 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; -export default function({ getService, getPageObjects }: FtrProviderContext) { +export default function ({ getService, getPageObjects }: FtrProviderContext) { const retry = getService('retry'); const esArchiver = getService('esArchiver'); const browser = getService('browser'); @@ -34,7 +34,7 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { }; describe('discover', function describeIndexTests() { - before(async function() { + before(async function () { await esArchiver.load('discover'); // and load a set of makelogs data @@ -63,31 +63,31 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { }); } - describe('query', function() { + describe('query', function () { this.tags(['skipFirefox']); - it('should show bars in the correct time zone', async function() { + it('should show bars in the correct time zone', async function () { await PageObjects.header.awaitGlobalLoadingIndicatorHidden(); await PageObjects.discover.waitUntilSearchingHasFinished(); await takeSnapshot(); }); - it('should show correct data for chart interval Hour', async function() { + it('should show correct data for chart interval Hour', async function () { await PageObjects.discover.setChartInterval('Hour'); await takeSnapshot(); }); - it('should show correct data for chart interval Day', async function() { + it('should show correct data for chart interval Day', async function () { await PageObjects.discover.setChartInterval('Day'); await takeSnapshot(); }); - it('should show correct data for chart interval Week', async function() { + it('should show correct data for chart interval Week', async function () { await PageObjects.discover.setChartInterval('Week'); await takeSnapshot(); }); - it('browser back button should show previous interval Day', async function() { + it('browser back button should show previous interval Day', async function () { await browser.goBack(); await retry.try(async function tryingForTime() { const actualInterval = await PageObjects.discover.getChartInterval(); @@ -96,24 +96,24 @@ export default function({ getService, getPageObjects }: FtrProviderContext) { await takeSnapshot(); }); - it('should show correct data for chart interval Month', async function() { + it('should show correct data for chart interval Month', async function () { await PageObjects.discover.setChartInterval('Month'); await takeSnapshot(); }); - it('should show correct data for chart interval Year', async function() { + it('should show correct data for chart interval Year', async function () { await PageObjects.discover.setChartInterval('Year'); await takeSnapshot(); }); - it('should show correct data for chart interval Auto', async function() { + it('should show correct data for chart interval Auto', async function () { await PageObjects.discover.setChartInterval('Auto'); await takeSnapshot(); }); }); describe('time zone switch', () => { - it('should show bars in the correct time zone after switching', async function() { + it('should show bars in the correct time zone after switching', async function () { await kibanaServer.uiSettings.replace({ 'dateFormat:tz': 'America/Phoenix' }); await refreshDiscover(); await PageObjects.timePicker.setDefaultAbsoluteRange(); diff --git a/test/visual_regression/tests/discover/index.ts b/test/visual_regression/tests/discover/index.ts index d036327ae7475..d33b69aa7f4cf 100644 --- a/test/visual_regression/tests/discover/index.ts +++ b/test/visual_regression/tests/discover/index.ts @@ -23,13 +23,13 @@ import { FtrProviderContext } from '../../ftr_provider_context'; // Width must be the same as visual_testing or canvas image widths will get skewed const [SCREEN_WIDTH] = DEFAULT_OPTIONS.widths || []; -export default function({ getService, loadTestFile }: FtrProviderContext) { +export default function ({ getService, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); - describe('discover app', function() { + describe('discover app', function () { this.tags('ciGroup6'); - before(function() { + before(function () { return browser.setWindowSize(SCREEN_WIDTH, 1000); }); diff --git a/utilities/visual_regression.js b/utilities/visual_regression.js index d95b3018bea96..0121bbb2363cc 100644 --- a/utilities/visual_regression.js +++ b/utilities/visual_regression.js @@ -81,10 +81,10 @@ async function compareScreenshots() { fs.mkdirSync(DIFF_SCREENSHOTS_DIR, { recursive: true }); fs.mkdirSync(SESSION_SCREENSHOTS_DIR, { recursive: true }); const files = await readDirAsync(SESSION_SCREENSHOTS_DIR); - const screenshots = files.filter(file => file.indexOf('.png') !== -1); + const screenshots = files.filter((file) => file.indexOf('.png') !== -1); // We'll use this data to build a screenshot gallery in HTML. - return await bluebird.map(screenshots, async screenshot => { + return await bluebird.map(screenshots, async (screenshot) => { // We're going to load image data and cache it in this object. const comparison = { name: screenshot, @@ -138,13 +138,13 @@ async function compareScreenshots() { export function run(done) { compareScreenshots().then( - screenshotComparisons => { + (screenshotComparisons) => { // Once all of the data has been loaded, we can build the gallery. buildGallery(screenshotComparisons).then(() => { done(); }); }, - error => { + (error) => { console.error(error); done(false); } diff --git a/x-pack/dev-tools/api_debug/index.js b/x-pack/dev-tools/api_debug/index.js index 28a855536038a..a5364dde1b7f1 100644 --- a/x-pack/dev-tools/api_debug/index.js +++ b/x-pack/dev-tools/api_debug/index.js @@ -11,7 +11,7 @@ import { argv } from 'yargs'; import { requestFromApi } from './request_from_api'; async function listFiles() { - const scan = pattern => { + const scan = (pattern) => { return new Promise((resolve, reject) => { glob(pattern, {}, (err, files) => (err ? reject(err) : resolve(files))); }); @@ -19,7 +19,7 @@ async function listFiles() { const pattern = resolve(__dirname, './apis/*/index.js'); const files = await scan(pattern); - files.forEach(file => { + files.forEach((file) => { const { name, description } = require(file); // eslint-disable-line import/no-dynamic-require console.log(' ' + bold(`node ${argv.$0} ${name}`)); console.log(` ${description}`); diff --git a/x-pack/dev-tools/jest/setup/polyfills.js b/x-pack/dev-tools/jest/setup/polyfills.js index 13e43b5671478..5ecee2e3ad0d3 100644 --- a/x-pack/dev-tools/jest/setup/polyfills.js +++ b/x-pack/dev-tools/jest/setup/polyfills.js @@ -9,7 +9,7 @@ // x-pack has a different version of bluebird so it needs its own polyfills.js to ensure // the scheduler is set on the right bluebird instance const bluebird = require('bluebird'); -bluebird.Promise.setScheduler(function(fn) { +bluebird.Promise.setScheduler(function (fn) { global.setImmediate.call(global, fn); }); diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_hello_world_drilldown/index.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_hello_world_drilldown/index.tsx index b1e1040daee6e..847035403da02 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_hello_world_drilldown/index.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_hello_world_drilldown/index.tsx @@ -39,7 +39,7 @@ export class DashboardHelloWorldDrilldown implements Drilldown onConfig({ ...config, name: event.target.value })} + onChange={(event) => onConfig({ ...config, name: event.target.value })} /> ); diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/collect_config_container.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/collect_config_container.tsx index 69cf260a20a81..dd5d13a4da351 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/collect_config_container.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/collect_config_container.tsx @@ -28,7 +28,7 @@ export const CollectConfigContainer: React.FC = ({ if (!isMounted()) return; setIndexPatterns( indexPatternSavedObjects - ? indexPatternSavedObjects.map(indexPattern => ({ + ? indexPatternSavedObjects.map((indexPattern) => ({ id: indexPattern.id, title: indexPattern.attributes.title, })) @@ -41,7 +41,7 @@ export const CollectConfigContainer: React.FC = ({ { + onIndexPatternSelect={(indexPatternId) => { onConfig({ ...config, indexPatternId }); }} customIndexPattern={config.customIndexPattern} diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/components/discover_drilldown_config/discover_drilldown_config.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/components/discover_drilldown_config/discover_drilldown_config.tsx index cf379b29a0039..0237e128c5a2f 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/components/discover_drilldown_config/discover_drilldown_config.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/components/discover_drilldown_config/discover_drilldown_config.tsx @@ -71,7 +71,7 @@ export const DiscoverDrilldownConfig: React.FC = ( ...indexPatterns.map(({ id, title }) => ({ value: id, text: title })), ]} value={activeIndexPatternId || ''} - onChange={e => onIndexPatternSelect(e.target.value)} + onChange={(e) => onIndexPatternSelect(e.target.value)} /> )} diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/drilldown.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/drilldown.tsx index be2b6ef7a241c..fef01c9640f0d 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/drilldown.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_discover_drilldown/drilldown.tsx @@ -36,7 +36,7 @@ export class DashboardToDiscoverDrilldown implements Drilldown = props => ( + private readonly ReactCollectConfig: React.FC = (props) => ( ); diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_url_drilldown/index.tsx b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_url_drilldown/index.tsx index cc38386b26385..20267a8b7292b 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_url_drilldown/index.tsx +++ b/x-pack/examples/ui_actions_enhanced_examples/public/dashboard_to_url_drilldown/index.tsx @@ -63,7 +63,7 @@ export class DashboardToUrlDrilldown implements Drilldown name="url" placeholder="Enter URL" value={config.url} - onChange={event => onConfig({ ...config, url: event.target.value })} + onChange={(event) => onConfig({ ...config, url: event.target.value })} onBlur={() => { if (!config.url) return; if (/https?:\/\//.test(config.url)) return; diff --git a/x-pack/index.js b/x-pack/index.js index bac871fcb5414..0975a82f16f6d 100644 --- a/x-pack/index.js +++ b/x-pack/index.js @@ -15,7 +15,7 @@ import { spaces } from './legacy/plugins/spaces'; import { encryptedSavedObjects } from './legacy/plugins/encrypted_saved_objects'; import { ingestManager } from './legacy/plugins/ingest_manager'; -module.exports = function(kibana) { +module.exports = function (kibana) { return [ xpackMain(kibana), monitoring(kibana), diff --git a/x-pack/legacy/common/__tests__/poller.js b/x-pack/legacy/common/__tests__/poller.js index 12e8c5faa26db..24558502a8d02 100644 --- a/x-pack/legacy/common/__tests__/poller.js +++ b/x-pack/legacy/common/__tests__/poller.js @@ -36,12 +36,12 @@ describe('Poller', () => { await Promise.resolve(); }; - const allowPoll = async interval => { + const allowPoll = async (interval) => { await queueNextPoll(); clock.tick(interval); }; - const allowDelayPoll = async interval => { + const allowDelayPoll = async (interval) => { clock.tick(interval); await queueNextPoll(); }; diff --git a/x-pack/legacy/common/poller.js b/x-pack/legacy/common/poller.js index d5761beac6c33..09824ce9d6d23 100644 --- a/x-pack/legacy/common/poller.js +++ b/x-pack/legacy/common/poller.js @@ -33,7 +33,7 @@ export class Poller { this._timeoutId = setTimeout(this._poll.bind(this), this.pollFrequencyInMillis); }) - .catch(e => { + .catch((e) => { this.errorFunction(e); if (!this._isRunning) { return; diff --git a/x-pack/legacy/plugins/beats_management/common/config_block_validation.ts b/x-pack/legacy/plugins/beats_management/common/config_block_validation.ts index 8972084018d98..f3d1b9164e976 100644 --- a/x-pack/legacy/plugins/beats_management/common/config_block_validation.ts +++ b/x-pack/legacy/plugins/beats_management/common/config_block_validation.ts @@ -20,7 +20,7 @@ export const validateConfigurationBlocks = (configurationBlocks: ConfigurationBl }; for (const [index, block] of configurationBlocks.entries()) { - const blockSchema = configBlockSchemas.find(s => s.id === block.type); + const blockSchema = configBlockSchemas.find((s) => s.id === block.type); if (!blockSchema) { throw new Error( `Invalid config type of ${block.type} used in 'configuration_blocks' at index ${index}` @@ -30,7 +30,7 @@ export const validateConfigurationBlocks = (configurationBlocks: ConfigurationBl const interfaceConfig = blockSchema.configs.reduce((props, config) => { if (config.options) { props[config.id] = t.keyof( - Object.fromEntries(config.options.map(opt => [opt.value, null])) as Record + Object.fromEntries(config.options.map((opt) => [opt.value, null])) as Record ); } else if (config.validation) { props[config.id] = validationMap[config.validation]; diff --git a/x-pack/legacy/plugins/beats_management/common/config_schemas.ts b/x-pack/legacy/plugins/beats_management/common/config_schemas.ts index 499a9479d4e8d..1bb196be56ee8 100644 --- a/x-pack/legacy/plugins/beats_management/common/config_schemas.ts +++ b/x-pack/legacy/plugins/beats_management/common/config_schemas.ts @@ -353,7 +353,7 @@ export const configBlockSchemas: ConfigBlockSchema[] = [ validation: 'isHosts', error: 'outputConfig.hosts.error', errorId: 'outputConfig.hosts.error', - parseValidResult: v => v.split('\n'), + parseValidResult: (v) => v.split('\n'), }, { id: 'username', diff --git a/x-pack/legacy/plugins/beats_management/common/config_schemas_translations_map.ts b/x-pack/legacy/plugins/beats_management/common/config_schemas_translations_map.ts index 6e08e32ded166..1aec3e8081708 100644 --- a/x-pack/legacy/plugins/beats_management/common/config_schemas_translations_map.ts +++ b/x-pack/legacy/plugins/beats_management/common/config_schemas_translations_map.ts @@ -217,10 +217,10 @@ export const translateConfigSchema = (schemas: ConfigBlockSchema[]) => { return translatedConfigs; } - translatedConfigs = schemas.map(schema => { + translatedConfigs = schemas.map((schema) => { schema.name = supportedConfigLabelsMap.get(`supportedConfigs.${schema.id}.text`) || schema.name; - schema.configs = schema.configs.map(configBlock => { + schema.configs = schema.configs.map((configBlock) => { if (configBlock.ui.label) { configBlock.ui.label = supportedConfigLabelsMap.get(configBlock.ui.labelId || '') || configBlock.ui.label; diff --git a/x-pack/legacy/plugins/beats_management/common/domain_types.ts b/x-pack/legacy/plugins/beats_management/common/domain_types.ts index bc77abc9815be..b4a9ac8a07479 100644 --- a/x-pack/legacy/plugins/beats_management/common/domain_types.ts +++ b/x-pack/legacy/plugins/beats_management/common/domain_types.ts @@ -14,7 +14,7 @@ export const OutputTypesArray = ['elasticsearch', 'logstash', 'kafka', 'redis']; // can be used to validate blocs on the API and UI export const createConfigurationBlockInterface = ( configType: t.LiteralType | t.KeyofC> = t.keyof( - Object.fromEntries(configBlockSchemas.map(s => [s.id, null])) as Record + Object.fromEntries(configBlockSchemas.map((s) => [s.id, null])) as Record ), beatConfigInterface: t.Mixed = t.Dictionary ) => diff --git a/x-pack/legacy/plugins/beats_management/common/io_ts_types.ts b/x-pack/legacy/plugins/beats_management/common/io_ts_types.ts index b8e5d80911920..d77ad92298699 100644 --- a/x-pack/legacy/plugins/beats_management/common/io_ts_types.ts +++ b/x-pack/legacy/plugins/beats_management/common/io_ts_types.ts @@ -24,7 +24,7 @@ export class DateFromStringType extends t.Type { return isNaN(d.getTime()) ? t.failure(s, c) : t.success(d); } }, - a => a.toISOString() + (a) => a.toISOString() ); } } diff --git a/x-pack/legacy/plugins/beats_management/index.ts b/x-pack/legacy/plugins/beats_management/index.ts index b5399595fb782..1f04f342f9ca0 100644 --- a/x-pack/legacy/plugins/beats_management/index.ts +++ b/x-pack/legacy/plugins/beats_management/index.ts @@ -13,9 +13,7 @@ const DEFAULT_ENROLLMENT_TOKENS_TTL_S = 10 * 60; // 10 minutes export const config = Joi.object({ enabled: Joi.boolean().default(true), - defaultUserRoles: Joi.array() - .items(Joi.string()) - .default(['superuser']), + defaultUserRoles: Joi.array().items(Joi.string()).default(['superuser']), encryptionKey: Joi.string().default('xpack_beats_default_encryptionKey'), enrollmentTokensTtlInSeconds: Joi.number() .integer() diff --git a/x-pack/legacy/plugins/beats_management/scripts/fake_env.ts b/x-pack/legacy/plugins/beats_management/scripts/fake_env.ts index fe8919f48ac10..246f86c957174 100644 --- a/x-pack/legacy/plugins/beats_management/scripts/fake_env.ts +++ b/x-pack/legacy/plugins/beats_management/scripts/fake_env.ts @@ -15,7 +15,7 @@ const args = process.argv.slice(2); const chance = new Chance(); function sleep(ms: number) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } function getRandomColor() { const letters = '0123456789ABCDEF'; diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts index 1ab7418c15614..f76cd46a60440 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts @@ -64,7 +64,7 @@ export class ElasticsearchBeatsAdapter implements CMBeatsAdapter { } public async getWithIds(user: FrameworkUser, beatIds: string[]) { - const ids = beatIds.map(beatId => `beat:${beatId}`); + const ids = beatIds.map((beatId) => `beat:${beatId}`); const params = { body: { diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/memory_beats_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/memory_beats_adapter.ts index 15cb9458ae365..afae87c490158 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/memory_beats_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/beats/memory_beats_adapter.ts @@ -18,7 +18,7 @@ export class MemoryBeatsAdapter implements CMBeatsAdapter { } public async get(user: FrameworkUser, id: string) { - return this.beatsDB.find(beat => beat.id === id) || null; + return this.beatsDB.find((beat) => beat.id === id) || null; } public async insert(user: FrameworkUser, beat: CMBeat) { @@ -26,7 +26,7 @@ export class MemoryBeatsAdapter implements CMBeatsAdapter { } public async update(user: FrameworkUser, beat: CMBeat) { - const beatIndex = this.beatsDB.findIndex(b => b.id === beat.id); + const beatIndex = this.beatsDB.findIndex((b) => b.id === beat.id); this.beatsDB[beatIndex] = { ...this.beatsDB[beatIndex], @@ -35,18 +35,18 @@ export class MemoryBeatsAdapter implements CMBeatsAdapter { } public async getWithIds(user: FrameworkUser, beatIds: string[]) { - return this.beatsDB.filter(beat => beatIds.includes(beat.id)); + return this.beatsDB.filter((beat) => beatIds.includes(beat.id)); } public async getAllWithTags(user: FrameworkUser, tagIds: string[]): Promise { - return this.beatsDB.filter(beat => intersection(tagIds, beat.tags || []).length !== 0); + return this.beatsDB.filter((beat) => intersection(tagIds, beat.tags || []).length !== 0); } public async getBeatWithToken( user: FrameworkUser, enrollmentToken: string ): Promise { - return this.beatsDB.find(beat => enrollmentToken === beat.enrollment_token) || null; + return this.beatsDB.find((beat) => enrollmentToken === beat.enrollment_token) || null; } public async getAll(user: FrameworkUser) { @@ -57,15 +57,15 @@ export class MemoryBeatsAdapter implements CMBeatsAdapter { user: FrameworkUser, removals: BeatsTagAssignment[] ): Promise { - const beatIds = removals.map(r => r.beatId); + const beatIds = removals.map((r) => r.beatId); const response = this.beatsDB - .filter(beat => beatIds.includes(beat.id)) - .map(beat => { - const tagData = removals.find(r => r.beatId === beat.id); + .filter((beat) => beatIds.includes(beat.id)) + .map((beat) => { + const tagData = removals.find((r) => r.beatId === beat.id); if (tagData) { if (beat.tags) { - beat.tags = beat.tags.filter(tag => tag !== tagData.tag); + beat.tags = beat.tags.filter((tag) => tag !== tagData.tag); } } return beat; @@ -82,14 +82,14 @@ export class MemoryBeatsAdapter implements CMBeatsAdapter { user: FrameworkUser, assignments: BeatsTagAssignment[] ): Promise { - const beatIds = assignments.map(r => r.beatId); + const beatIds = assignments.map((r) => r.beatId); this.beatsDB - .filter(beat => beatIds.includes(beat.id)) - .map(beat => { + .filter((beat) => beatIds.includes(beat.id)) + .map((beat) => { // get tags that need to be assigned to this beat const tags = assignments - .filter(a => a.beatId === beat.id) + .filter((a) => a.beatId === beat.id) .map((t: BeatsTagAssignment) => t.tag); if (tags.length > 0) { diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/elasticsearch_configuration_block_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/elasticsearch_configuration_block_adapter.ts index f48b1807d7777..f60b5c8b4d0f6 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/elasticsearch_configuration_block_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/elasticsearch_configuration_block_adapter.ts @@ -30,7 +30,7 @@ export class ElasticsearchConfigurationBlockAdapter implements ConfigurationBloc size: 10000, index: INDEX_NAMES.BEATS, body: { - ids: ids.map(id => `configuration_block:${id}`), + ids: ids.map((id) => `configuration_block:${id}`), }, }; @@ -88,7 +88,7 @@ export class ElasticsearchConfigurationBlockAdapter implements ConfigurationBloc ids: string[] ): Promise> { const result = await this.database.bulk(user, { - body: ids.map(id => ({ delete: { _id: `configuration_block:${id}` } })), + body: ids.map((id) => ({ delete: { _id: `configuration_block:${id}` } })), index: INDEX_NAMES.BEATS, refresh: 'wait_for', }); @@ -136,7 +136,7 @@ export class ElasticsearchConfigurationBlockAdapter implements ConfigurationBloc public async create(user: FrameworkUser, configs: ConfigurationBlock[]): Promise { const body = flatten( - configs.map(config => { + configs.map((config) => { const id = config.id || uuidv4(); return [ { index: { _id: `configuration_block:${id}` } }, diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/memory_tags_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/memory_tags_adapter.ts index 4f8bb88b360fb..ea8a75c92fad2 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/memory_tags_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/configuration_blocks/memory_tags_adapter.ts @@ -15,7 +15,7 @@ export class MemoryConfigurationBlockAdapter implements ConfigurationBlockAdapte private db: ConfigurationBlock[] = []; constructor(db: ConfigurationBlock[]) { - this.db = db.map(config => { + this.db = db.map((config) => { if (config.id === undefined) { config.id = chance.word(); } @@ -24,11 +24,11 @@ export class MemoryConfigurationBlockAdapter implements ConfigurationBlockAdapte } public async getByIds(user: FrameworkUser, ids: string[]) { - return this.db.filter(block => ids.includes(block.id)); + return this.db.filter((block) => ids.includes(block.id)); } public async delete(user: FrameworkUser, blockIds: string[]) { - this.db = this.db.filter(block => !blockIds.includes(block.id)); - return blockIds.map(id => ({ + this.db = this.db.filter((block) => !blockIds.includes(block.id)); + return blockIds.map((id) => ({ id, success: true, })); @@ -37,14 +37,14 @@ export class MemoryConfigurationBlockAdapter implements ConfigurationBlockAdapte user: FrameworkUser, tagIds: string[] ): Promise<{ success: boolean; reason?: string }> { - this.db = this.db.filter(block => !tagIds.includes(block.tag)); + this.db = this.db.filter((block) => !tagIds.includes(block.tag)); return { success: true, }; } public async getForTags(user: FrameworkUser, tagIds: string[], page?: number, size?: number) { - const results = this.db.filter(block => tagIds.includes(block.id)); + const results = this.db.filter((block) => tagIds.includes(block.id)); return { page: 0, total: results.length, @@ -53,8 +53,8 @@ export class MemoryConfigurationBlockAdapter implements ConfigurationBlockAdapte } public async create(user: FrameworkUser, blocks: ConfigurationBlock[]) { - return blocks.map(block => { - const existingIndex = this.db.findIndex(t => t.id === block.id); + return blocks.map((block) => { + const existingIndex = this.db.findIndex((t) => t.id === block.id); if (existingIndex !== -1) { this.db[existingIndex] = block; } else { @@ -65,7 +65,7 @@ export class MemoryConfigurationBlockAdapter implements ConfigurationBlockAdapte } public setDB(db: ConfigurationBlock[]) { - this.db = db.map(block => { + this.db = db.map((block) => { if (block.id === undefined) { block.id = chance.word(); } diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts index 6e4613e3f2fd5..4e032001809f2 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts @@ -49,7 +49,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { } public async delete(user: FrameworkUser, tagIds: string[]): Promise { - const ids = tagIds.map(tag => tag); + const ids = tagIds.map((tag) => tag); const params = { ignore: [404], @@ -67,8 +67,8 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { (beat: any) => beat._source.beat ); - const inactiveBeats = beats.filter(beat => beat.active === false); - const activeBeats = beats.filter(beat => beat.active === true); + const inactiveBeats = beats.filter((beat) => beat.active === false); + const activeBeats = beats.filter((beat) => beat.active === true); if (activeBeats.length !== 0) { return false; } @@ -76,7 +76,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { // While we block tag deletion when on an active beat, we should remove from inactive const bulkInactiveBeatsUpdates = flatten( - beatIds.map(beatId => { + beatIds.map((beatId) => { const script = ` def beat = ctx._source.beat; if (beat.tags != null) { @@ -84,7 +84,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { }`; return flatten( - ids.map(tagId => [ + ids.map((tagId) => [ { update: { _id: `beat:${beatId}` } }, { script: { source: script.replace(' ', ''), params: { tagId } } }, ]) @@ -92,7 +92,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { }) ); - const bulkTagsDelete = ids.map(tagId => ({ delete: { _id: `tag:${tagId}` } })); + const bulkTagsDelete = ids.map((tagId) => ({ delete: { _id: `tag:${tagId}` } })); await this.database.bulk(user, { body: flatten([...bulkInactiveBeatsUpdates, ...bulkTagsDelete]), @@ -107,7 +107,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { if (tagIds.length === 0) { return []; } - const ids = tagIds.map(tag => `tag:${tag}`); + const ids = tagIds.map((tag) => `tag:${tag}`); const params = { ignore: [404], diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/memory_tags_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/memory_tags_adapter.ts index 278f47c1fca75..66a6c7ebebc2c 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/memory_tags_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tags/memory_tags_adapter.ts @@ -19,16 +19,16 @@ export class MemoryTagsAdapter implements CMTagsAdapter { return this.tagsDB; } public async delete(user: FrameworkUser, tagIds: string[]) { - this.tagsDB = this.tagsDB.filter(tag => !tagIds.includes(tag.id)); + this.tagsDB = this.tagsDB.filter((tag) => !tagIds.includes(tag.id)); return true; } public async getTagsWithIds(user: FrameworkUser, tagIds: string[]) { - return this.tagsDB.filter(tag => tagIds.includes(tag.id)); + return this.tagsDB.filter((tag) => tagIds.includes(tag.id)); } public async upsertTag(user: FrameworkUser, tag: BeatTag) { - const existingTagIndex = this.tagsDB.findIndex(t => t.id === tag.id); + const existingTagIndex = this.tagsDB.findIndex((t) => t.id === tag.id); if (existingTagIndex !== -1) { this.tagsDB[existingTagIndex] = tag; } else { @@ -41,7 +41,7 @@ export class MemoryTagsAdapter implements CMTagsAdapter { user: FrameworkUser, blockTypes: string[] ): Promise { - return this.tagsDB.filter(tag => tag.hasConfigurationBlocksTypes.includes(blockTypes[0])); + return this.tagsDB.filter((tag) => tag.hasConfigurationBlocksTypes.includes(blockTypes[0])); } public setDB(tagsDB: BeatTag[]) { diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts index 533ded1a7b531..4987e4dbd4e0a 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts @@ -44,14 +44,14 @@ export class ElasticsearchTokensAdapter implements CMTokensAdapter { // out whether a token is valid or not. So we introduce a random delay in returning from // this function to obscure the actual time it took for Elasticsearch to find the token. const randomDelayInMs = 25 + Math.round(Math.random() * 200); // between 25 and 225 ms - return new Promise(resolve => + return new Promise((resolve) => setTimeout(() => resolve(tokenDetails), randomDelayInMs) ); } public async insertTokens(user: FrameworkUser, tokens: TokenEnrollmentData[]) { const body = flatten( - tokens.map(token => [ + tokens.map((token) => [ { index: { _id: `enrollment_token:${token.token}` } }, { enrollment_token: token, diff --git a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts index 536b825c949e9..431263c808b45 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts @@ -15,7 +15,7 @@ export class MemoryTokensAdapter implements CMTokensAdapter { } public async deleteEnrollmentToken(user: FrameworkUser, enrollmentToken: string) { - const index = this.tokenDB.findIndex(token => token.token === enrollmentToken); + const index = this.tokenDB.findIndex((token) => token.token === enrollmentToken); if (index > -1) { this.tokenDB.splice(index, 1); @@ -26,14 +26,14 @@ export class MemoryTokensAdapter implements CMTokensAdapter { user: FrameworkUser, tokenString: string ): Promise { - return new Promise(resolve => { - return resolve(this.tokenDB.find(token => token.token === tokenString)); + return new Promise((resolve) => { + return resolve(this.tokenDB.find((token) => token.token === tokenString)); }); } public async insertTokens(user: FrameworkAuthenticatedUser, tokens: TokenEnrollmentData[]) { - tokens.forEach(token => { - const existingIndex = this.tokenDB.findIndex(t => t.token === token.token); + tokens.forEach((token) => { + const existingIndex = this.tokenDB.findIndex((t) => t.token === token.token); if (existingIndex !== -1) { this.tokenDB[existingIndex] = token; } else { diff --git a/x-pack/legacy/plugins/beats_management/server/lib/beat_events.ts b/x-pack/legacy/plugins/beats_management/server/lib/beat_events.ts index f0a394b58c801..f4cb3cb424f6f 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/beat_events.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/beat_events.ts @@ -30,7 +30,7 @@ export class BeatEventsLib { timestamp: new Date(events[events.length - 2].timestamp), }, }) - .catch(e => { + .catch((e) => { // eslint-disable-next-line console.error('Error inserting event into beats log.', e); }); @@ -48,7 +48,7 @@ export class BeatEventsLib { timestamp: new Date(events[events.length - 1].timestamp), }, }) - .catch(e => { + .catch((e) => { // eslint-disable-next-line console.error('Error inserting event into beats log.', e); }); diff --git a/x-pack/legacy/plugins/beats_management/server/lib/beats.ts b/x-pack/legacy/plugins/beats_management/server/lib/beats.ts index ca1e07bfab573..3b9c4d35d8331 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/beats.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/beats.ts @@ -43,7 +43,7 @@ export class CMBeatsDomain { public async getByIds(user: FrameworkUser, beatIds: string[]): Promise { const beats = await this.adapter.getWithIds(user, beatIds); - return beats.filter(beat => beat.active); + return beats.filter((beat) => beat.active); } public async getAll(user: FrameworkUser, ESQuery?: any) { @@ -131,8 +131,8 @@ export class CMBeatsDomain { user: FrameworkUser, removals: BeatsTagAssignment[] ): Promise { - const beatIds = uniq(removals.map(removal => removal.beatId)); - const tagIds = uniq(removals.map(removal => removal.tag)); + const beatIds = uniq(removals.map((removal) => removal.beatId)); + const tagIds = uniq(removals.map((removal) => removal.tag)); const response = { removals: removals.map(() => ({ status: null })), @@ -173,8 +173,8 @@ export class CMBeatsDomain { user: FrameworkUser, assignments: BeatsTagAssignment[] ): Promise { - const beatIds = uniq(assignments.map(assignment => assignment.beatId)); - const tagIds = uniq(assignments.map(assignment => assignment.tag)); + const beatIds = uniq(assignments.map((assignment) => assignment.beatId)); + const tagIds = uniq(assignments.map((assignment) => assignment.tag)); const response = { assignments: assignments.map(() => ({ status: null })), diff --git a/x-pack/legacy/plugins/beats_management/server/lib/tags.ts b/x-pack/legacy/plugins/beats_management/server/lib/tags.ts index df9c65034115b..947e177100f7b 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/tags.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/tags.ts @@ -30,7 +30,7 @@ export class CMTagsDomain { public async delete(user: FrameworkUser, tagIds: string[]) { const beats = await this.beatsAdabter.getAllWithTags(user, tagIds); - if (beats.filter(b => b.active).length > 0) { + if (beats.filter((b) => b.active).length > 0) { return false; } await this.configurationBlocksAdapter.deleteForTags(user, tagIds); @@ -46,7 +46,7 @@ export class CMTagsDomain { } return existingUniqueTypes; }, [] as string[]) - ).filter(type => UNIQUENESS_ENFORCING_TYPES.includes(type)); + ).filter((type) => UNIQUENESS_ENFORCING_TYPES.includes(type)); const safeTags = await this.adapter.getWithoutConfigTypes(user, existingUniqueBlockTypes); return safeTags; diff --git a/x-pack/legacy/plugins/beats_management/server/lib/tokens.ts b/x-pack/legacy/plugins/beats_management/server/lib/tokens.ts index 7846bb5a8451e..759868810c0ce 100644 --- a/x-pack/legacy/plugins/beats_management/server/lib/tokens.ts +++ b/x-pack/legacy/plugins/beats_management/server/lib/tokens.ts @@ -134,9 +134,9 @@ export class CMTokensDomain { } await Promise.all( - chunk(tokens, 100).map(tokenChunk => this.adapter.insertTokens(user, tokenChunk)) + chunk(tokens, 100).map((tokenChunk) => this.adapter.insertTokens(user, tokenChunk)) ); - return tokens.map(token => token.token); + return tokens.map((token) => token.token); } } diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_assignment.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_assignment.ts index db19e5b6a7627..974b2822fbd92 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_assignment.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_assignment.ts @@ -37,7 +37,7 @@ export const createTagAssignmentsRoute = (libs: CMServerLibs) => ({ return { success: true, - results: response.assignments.map(assignment => ({ + results: response.assignments.map((assignment) => ({ success: assignment.status && assignment.status >= 200 && assignment.status < 300, error: !assignment.status || assignment.status >= 300 diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_removal.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_removal.ts index 90c8a78552df7..3bbc32dc5748b 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_removal.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/beats/tag_removal.ts @@ -35,7 +35,7 @@ export const createTagRemovalsRoute = (libs: CMServerLibs) => ({ return { success: true, - results: response.removals.map(removal => ({ + results: response.removals.map((removal) => ({ success: removal.status && removal.status >= 200 && removal.status < 300, error: !removal.status || removal.status >= 300 diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/delete.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/delete.ts index 5cd9897be91d0..b7d430fb18c01 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/delete.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/delete.ts @@ -22,7 +22,7 @@ export const createDeleteConfidurationsRoute = (libs: CMServerLibs) => ({ return { success: true, - results: results.map(result => ({ + results: results.map((result) => ({ success: result.success, action: 'deleted', error: result.success ? undefined : { message: result.reason }, diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/upsert.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/upsert.ts index 78fc9e962c9ec..fb62800594d0a 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/upsert.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/configurations/upsert.ts @@ -55,7 +55,7 @@ export const upsertConfigurationRoute = (libs: CMServerLibs) => ({ ); return { - results: result.map(r => ({ + results: result.map((r) => ({ success: r.success as boolean, // TODO: we need to surface this data, not hard coded action: 'created' as 'created' | 'updated', diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/tags/assignable.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/tags/assignable.ts index 8495d648b85d0..88a322c03790f 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/tags/assignable.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/tags/assignable.ts @@ -23,7 +23,7 @@ export const createAssignableTagsRoute = (libs: CMServerLibs) => ({ const beats = await libs.beats.getByIds(request.user, beatIds); const tags = await libs.tags.getNonConflictingTags( request.user, - flatten(beats.map(beat => beat.tags)) + flatten(beats.map((beat) => beat.tags)) ); return { diff --git a/x-pack/legacy/plugins/beats_management/server/rest_api/tokens/create.ts b/x-pack/legacy/plugins/beats_management/server/rest_api/tokens/create.ts index 9de44447a0a01..571d2b4a4947c 100644 --- a/x-pack/legacy/plugins/beats_management/server/rest_api/tokens/create.ts +++ b/x-pack/legacy/plugins/beats_management/server/rest_api/tokens/create.ts @@ -21,10 +21,7 @@ export const createTokensRoute = (libs: CMServerLibs) => ({ config: { validate: { payload: Joi.object({ - num_tokens: Joi.number() - .optional() - .default(DEFAULT_NUM_TOKENS) - .min(1), + num_tokens: Joi.number().optional().default(DEFAULT_NUM_TOKENS).min(1), }).allow(null), }, }, @@ -36,7 +33,7 @@ export const createTokensRoute = (libs: CMServerLibs) => ({ try { const tokens = await libs.tokens.createEnrollmentTokens(request.user, numTokens); return { - results: tokens.map(token => ({ + results: tokens.map((token) => ({ item: token, success: true, action: 'created', diff --git a/x-pack/legacy/plugins/beats_management/server/utils/helper_types.ts b/x-pack/legacy/plugins/beats_management/server/utils/helper_types.ts index f3231b6ec771b..96f7b7bc79b62 100644 --- a/x-pack/legacy/plugins/beats_management/server/utils/helper_types.ts +++ b/x-pack/legacy/plugins/beats_management/server/utils/helper_types.ts @@ -8,6 +8,6 @@ export type InterfaceExcept = Pick> export function arrayFromEnum(e: any): T[] { return Object.keys(e) - .filter(key => isNaN(+key)) - .map(name => e[name]) as T[]; + .filter((key) => isNaN(+key)) + .map((name) => e[name]) as T[]; } diff --git a/x-pack/legacy/plugins/beats_management/wallaby.js b/x-pack/legacy/plugins/beats_management/wallaby.js index d07e0e56e6b77..823f63b15bcb3 100644 --- a/x-pack/legacy/plugins/beats_management/wallaby.js +++ b/x-pack/legacy/plugins/beats_management/wallaby.js @@ -6,7 +6,7 @@ const path = require('path'); process.env.NODE_PATH = path.resolve(__dirname, '..', '..', '..', 'node_modules'); -module.exports = function(wallaby) { +module.exports = function (wallaby) { return { debug: true, files: [ @@ -37,7 +37,7 @@ module.exports = function(wallaby) { }), }, - setup: wallaby => { + setup: (wallaby) => { const path = require('path'); const kibanaDirectory = path.resolve(wallaby.localProjectDir, '..', '..', '..'); diff --git a/x-pack/legacy/plugins/dashboard_mode/server/__tests__/dashboard_mode_request_interceptor.js b/x-pack/legacy/plugins/dashboard_mode/server/__tests__/dashboard_mode_request_interceptor.js index 6735adbf65fed..3fd9bf5f59d52 100644 --- a/x-pack/legacy/plugins/dashboard_mode/server/__tests__/dashboard_mode_request_interceptor.js +++ b/x-pack/legacy/plugins/dashboard_mode/server/__tests__/dashboard_mode_request_interceptor.js @@ -24,7 +24,7 @@ function setup() { server.ext(createDashboardModeRequestInterceptor()); // allow the extension to fake "render an app" - server.decorate('toolkit', 'renderApp', function(app) { + server.decorate('toolkit', 'renderApp', function (app) { // `this` is the `h` response toolkit return this.response({ renderApp: true, app }); }); @@ -93,13 +93,10 @@ describe('DashboardOnlyModeRequestInterceptor', () => { }, }); - expect(response) - .to.have.property('statusCode', 200) - .and.have.property('result') - .eql({ - catchAll: true, - path: '/foo/bar', - }); + expect(response).to.have.property('statusCode', 200).and.have.property('result').eql({ + catchAll: true, + path: '/foo/bar', + }); }); }); }); diff --git a/x-pack/legacy/plugins/dashboard_mode/server/dashboard_mode_request_interceptor.js b/x-pack/legacy/plugins/dashboard_mode/server/dashboard_mode_request_interceptor.js index 4e42e3c69d314..76a582d6cf239 100644 --- a/x-pack/legacy/plugins/dashboard_mode/server/dashboard_mode_request_interceptor.js +++ b/x-pack/legacy/plugins/dashboard_mode/server/dashboard_mode_request_interceptor.js @@ -40,10 +40,10 @@ export function createDashboardModeRequestInterceptor() { return h.continue; } - const isDashboardOnlyModeUser = user.roles.find(role => + const isDashboardOnlyModeUser = user.roles.find((role) => dashboardOnlyModeRoles.includes(role) ); - const isSuperUser = user.roles.find(role => role === superuserRole); + const isSuperUser = user.roles.find((role) => role === superuserRole); const enforceDashboardOnlyMode = isDashboardOnlyModeUser && !isSuperUser; if (enforceDashboardOnlyMode) { @@ -57,10 +57,7 @@ export function createDashboardModeRequestInterceptor() { // If the user is in "Dashboard only mode" they should only be allowed to see // the dashboard app and none others. If the kibana app is requested, this might be a old // url we will migrate on the fly. - return h - .redirect(url) - .permanent() - .takeover(); + return h.redirect(url).permanent().takeover(); } if (url.path.startsWith('/app/dashboard_mode')) { // let through requests to the dashboard_mode app diff --git a/x-pack/legacy/plugins/maps/public/angular/map_controller.js b/x-pack/legacy/plugins/maps/public/angular/map_controller.js index 02de4f1947228..91b54d2698c1d 100644 --- a/x-pack/legacy/plugins/maps/public/angular/map_controller.js +++ b/x-pack/legacy/plugins/maps/public/angular/map_controller.js @@ -145,13 +145,13 @@ app.controller( const visibleSubscription = getCoreChrome() .getIsVisible$() - .subscribe(isVisible => { + .subscribe((isVisible) => { $scope.$evalAsync(() => { $scope.isVisible = isVisible; }); }); - $scope.$listen(globalState, 'fetch_with_changes', diff => { + $scope.$listen(globalState, 'fetch_with_changes', (diff) => { if (diff.includes('time') || diff.includes('filters')) { onQueryChange({ filters: [...globalState.filters, ...getAppStateFilters()], @@ -163,7 +163,7 @@ app.controller( } }); - $scope.$listen($state, 'fetch_with_changes', function(diff) { + $scope.$listen($state, 'fetch_with_changes', function (diff) { if ((diff.includes('query') || diff.includes('filters')) && $state.query) { onQueryChange({ filters: [...globalState.filters, ...getAppStateFilters()], @@ -209,16 +209,16 @@ app.controller( $scope.$watch( () => getMapsCapabilities().saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability; } ); - $scope.onQuerySaved = savedQuery => { + $scope.onQuerySaved = (savedQuery) => { $scope.savedQuery = savedQuery; }; - $scope.onSavedQueryUpdated = savedQuery => { + $scope.onSavedQueryUpdated = (savedQuery) => { $scope.savedQuery = { ...savedQuery }; }; @@ -259,7 +259,7 @@ app.controller( } } - $scope.$watch('savedQuery', newSavedQuery => { + $scope.$watch('savedQuery', (newSavedQuery) => { if (!newSavedQuery) return; $state.savedQuery = newSavedQuery.id; @@ -268,13 +268,13 @@ app.controller( $scope.$watch( () => $state.savedQuery, - newSavedQueryId => { + (newSavedQueryId) => { if (!newSavedQueryId) { $scope.savedQuery = undefined; return; } if ($scope.savedQuery && newSavedQueryId !== $scope.savedQuery.id) { - savedQueryService.getSavedQuery(newSavedQueryId).then(savedQuery => { + savedQueryService.getSavedQuery(newSavedQueryId).then((savedQuery) => { $scope.$evalAsync(() => { $scope.savedQuery = savedQuery; updateStateFromSavedQuery(savedQuery); @@ -311,19 +311,19 @@ app.controller( } $scope.indexPatterns = []; - $scope.onQuerySubmit = function({ dateRange, query }) { + $scope.onQuerySubmit = function ({ dateRange, query }) { onQueryChange({ query, time: dateRange, refresh: true, }); }; - $scope.updateFiltersAndDispatch = function(filters) { + $scope.updateFiltersAndDispatch = function (filters) { onQueryChange({ filters, }); }; - $scope.onRefreshChange = function({ isPaused, refreshInterval }) { + $scope.onRefreshChange = function ({ isPaused, refreshInterval }) { $scope.refreshConfig = { isPaused, interval: refreshInterval ? refreshInterval : $scope.refreshConfig.interval, @@ -334,7 +334,7 @@ app.controller( }; function addFilters(newFilters) { - newFilters.forEach(filter => { + newFilters.forEach((filter) => { filter.$state = { store: esFilters.FilterStateStore.APP_STATE }; }); $scope.updateFiltersAndDispatch([...$scope.filters, ...newFilters]); @@ -439,7 +439,7 @@ app.controller( let prevIndexPatternIds; async function updateIndexPatterns(nextIndexPatternIds) { const indexPatterns = []; - const getIndexPatternPromises = nextIndexPatternIds.map(async indexPatternId => { + const getIndexPatternPromises = nextIndexPatternIds.map(async (indexPatternId) => { try { const indexPattern = await getIndexPatternService().get(indexPatternId); indexPatterns.push(indexPattern); @@ -659,7 +659,7 @@ app.controller( isTitleDuplicateConfirmed, onTitleDuplicate, }; - return doSave(saveOptions).then(response => { + return doSave(saveOptions).then((response) => { // If the save wasn't successful, put the original values back. if (!response.id || response.error) { savedMap.title = currentTitle; diff --git a/x-pack/legacy/plugins/maps/public/plugin.ts b/x-pack/legacy/plugins/maps/public/plugin.ts index 08bc184ef549d..9605c0d3e5fd8 100644 --- a/x-pack/legacy/plugins/maps/public/plugin.ts +++ b/x-pack/legacy/plugins/maps/public/plugin.ts @@ -52,7 +52,7 @@ export class MapsPlugin implements Plugin { public setup(core: CoreSetup, { __LEGACY: { uiModules }, np }: MapsPluginSetupDependencies) { uiModules .get('app/maps', ['ngRoute', 'react']) - .directive('mapListing', function(reactDirective: any) { + .directive('mapListing', function (reactDirective: any) { return reactDirective(wrapInI18nContext(MapListing)); }); diff --git a/x-pack/legacy/plugins/maps/public/routes.js b/x-pack/legacy/plugins/maps/public/routes.js index 721b30a208ebc..20664b1b35a26 100644 --- a/x-pack/legacy/plugins/maps/public/routes.js +++ b/x-pack/legacy/plugins/maps/public/routes.js @@ -45,19 +45,19 @@ routes controller($scope, config) { const gisMapSavedObjectLoader = getMapsSavedObjectLoader(); $scope.listingLimit = config.get(LISTING_LIMIT_SETTING); - $scope.find = search => { + $scope.find = (search) => { return gisMapSavedObjectLoader.find(search, $scope.listingLimit); }; - $scope.delete = ids => { + $scope.delete = (ids) => { return gisMapSavedObjectLoader.delete(ids); }; $scope.readOnly = !getMapsCapabilities().save; }, resolve: { - hasMaps: function(kbnUrl) { + hasMaps: function (kbnUrl) { getSavedObjectsClient() .find({ type: 'map', perPage: 1 }) - .then(resp => { + .then((resp) => { // Do not show empty listing page, just redirect to a new map if (resp.savedObjects.length === 0) { kbnUrl.redirect('/map'); @@ -71,7 +71,7 @@ routes template: mapTemplate, controller: 'GisMapController', resolve: { - map: function(redirectWhenMissing) { + map: function (redirectWhenMissing) { const gisMapSavedObjectLoader = getMapsSavedObjectLoader(); return gisMapSavedObjectLoader.get().catch( redirectWhenMissing({ @@ -85,12 +85,12 @@ routes template: mapTemplate, controller: 'GisMapController', resolve: { - map: function(redirectWhenMissing, $route) { + map: function (redirectWhenMissing, $route) { const gisMapSavedObjectLoader = getMapsSavedObjectLoader(); const id = $route.current.params.id; return gisMapSavedObjectLoader .get(id) - .then(savedMap => { + .then((savedMap) => { getCoreChrome().recentlyAccessed.add(savedMap.getFullPath(), savedMap.title, id); getCoreChrome().docTitle.change(savedMap.title); return savedMap; diff --git a/x-pack/legacy/plugins/monitoring/config.ts b/x-pack/legacy/plugins/monitoring/config.ts index 0c664fbe1c00c..52f4b866dd7b2 100644 --- a/x-pack/legacy/plugins/monitoring/config.ts +++ b/x-pack/legacy/plugins/monitoring/config.ts @@ -36,14 +36,9 @@ export const config = (Joi: any) => { elasticsearch: Joi.object({ customHeaders: Joi.object().default({}), logQueries: Joi.boolean().default(false), - requestHeadersWhitelist: Joi.array() - .items() - .single() - .default(DEFAULT_REQUEST_HEADERS), + requestHeadersWhitelist: Joi.array().items().single().default(DEFAULT_REQUEST_HEADERS), sniffOnStart: Joi.boolean().default(false), - sniffInterval: Joi.number() - .allow(false) - .default(false), + sniffInterval: Joi.number().allow(false).default(false), sniffOnConnectionFault: Joi.boolean().default(false), hosts: Joi.array() .items(Joi.string().uri({ scheme: ['http', 'https'] })) @@ -53,12 +48,8 @@ export const config = (Joi: any) => { requestTimeout: Joi.number().default(30000), pingTimeout: Joi.number().default(30000), ssl: Joi.object({ - verificationMode: Joi.string() - .valid('none', 'certificate', 'full') - .default('full'), - certificateAuthorities: Joi.array() - .single() - .items(Joi.string()), + verificationMode: Joi.string().valid('none', 'certificate', 'full').default('full'), + certificateAuthorities: Joi.array().single().items(Joi.string()), certificate: Joi.string(), key: Joi.string(), keyPassphrase: Joi.string(), @@ -85,14 +76,9 @@ export const config = (Joi: any) => { elasticsearch: Joi.object({ customHeaders: Joi.object().default({}), logQueries: Joi.boolean().default(false), - requestHeadersWhitelist: Joi.array() - .items() - .single() - .default(DEFAULT_REQUEST_HEADERS), + requestHeadersWhitelist: Joi.array().items().single().default(DEFAULT_REQUEST_HEADERS), sniffOnStart: Joi.boolean().default(false), - sniffInterval: Joi.number() - .allow(false) - .default(false), + sniffInterval: Joi.number().allow(false).default(false), sniffOnConnectionFault: Joi.boolean().default(false), hosts: Joi.array() .items(Joi.string().uri({ scheme: ['http', 'https'] })) @@ -102,12 +88,8 @@ export const config = (Joi: any) => { requestTimeout: Joi.number().default(30000), pingTimeout: Joi.number().default(30000), ssl: Joi.object({ - verificationMode: Joi.string() - .valid('none', 'certificate', 'full') - .default('full'), - certificateAuthorities: Joi.array() - .single() - .items(Joi.string()), + verificationMode: Joi.string().valid('none', 'certificate', 'full').default('full'), + certificateAuthorities: Joi.array().single().items(Joi.string()), certificate: Joi.string(), key: Joi.string(), keyPassphrase: Joi.string(), diff --git a/x-pack/legacy/plugins/reporting/common/validate_urls.ts b/x-pack/legacy/plugins/reporting/common/validate_urls.ts index b4ed2b19289a8..58e63a522e609 100644 --- a/x-pack/legacy/plugins/reporting/common/validate_urls.ts +++ b/x-pack/legacy/plugins/reporting/common/validate_urls.ts @@ -21,7 +21,7 @@ const isBogusUrl = (url: string) => { }; export const validateUrls = (urls: string[]): void => { - const badUrls = _.filter(urls, url => isBogusUrl(url)); + const badUrls = _.filter(urls, (url) => isBogusUrl(url)); if (badUrls.length) { throw new Error(`Found invalid URL(s), all URLs must be relative: ${badUrls.join(' ')}`); diff --git a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_conditional_headers.test.ts b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_conditional_headers.test.ts index c09cc8314374e..5067d5f5e5dd8 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_conditional_headers.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_conditional_headers.test.ts @@ -134,10 +134,7 @@ test(`uses basePath from server if job doesn't have a basePath when creating sav describe('config formatting', () => { test(`lowercases server.host`, async () => { - const mockConfigGet = sinon - .stub() - .withArgs('server', 'host') - .returns('COOL-HOSTNAME'); + const mockConfigGet = sinon.stub().withArgs('server', 'host').returns('COOL-HOSTNAME'); mockConfig = getMockConfig(mockConfigGet); const conditionalHeaders = await getConditionalHeaders({ diff --git a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_full_urls.ts b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_full_urls.ts index 59cb7ce14ca2d..90f3a3b2c9c24 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_full_urls.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/get_full_urls.ts @@ -58,7 +58,7 @@ export function getFullUrls({ validateUrls(relativeUrls); - const urls = relativeUrls.map(relativeUrl => { + const urls = relativeUrls.map((relativeUrl) => { const parsedRelative: UrlWithStringQuery = urlParse(relativeUrl); const jobUrl = getAbsoluteUrl({ basePath: job.basePath, diff --git a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/omit_blacklisted_headers.ts b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/omit_blacklisted_headers.ts index 2fbfd868674f6..0e5974225b932 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/execute_job/omit_blacklisted_headers.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/execute_job/omit_blacklisted_headers.ts @@ -21,7 +21,7 @@ export const omitBlacklistedHeaders = ({ (_value, header: string) => header && (KBN_SCREENSHOT_HEADER_BLACKLIST.includes(header) || - KBN_SCREENSHOT_HEADER_BLACKLIST_STARTS_WITH_PATTERN.some(pattern => + KBN_SCREENSHOT_HEADER_BLACKLIST_STARTS_WITH_PATTERN.some((pattern) => header?.startsWith(pattern) )) ); diff --git a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/get_time_range.ts b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/get_time_range.ts index 7bdb38298c383..74926918584fe 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/get_time_range.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/get_time_range.ts @@ -19,7 +19,7 @@ export const getTimeRange = async ( const timeRange = await browser.evaluate( { - fn: durationAttribute => { + fn: (durationAttribute) => { const durationElement = document.querySelector(`[${durationAttribute}]`); if (!durationElement) { diff --git a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/inject_css.ts b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/inject_css.ts index dae6f3cc6350f..8a198880a7768 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/inject_css.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/inject_css.ts @@ -31,7 +31,7 @@ export const injectCustomCss = async ( try { await browser.evaluate( { - fn: css => { + fn: (css) => { const node = document.createElement('style'); node.type = 'text/css'; node.innerHTML = css; // eslint-disable-line no-unsanitized/property diff --git a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/observable.ts b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/observable.ts index de27d5ad30014..bb11d1d3b7b63 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/observable.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/observable.ts @@ -86,7 +86,7 @@ export function screenshotsObservableFactory( ); }), mergeMap(() => getNumberOfItems(captureConfig, driver, layout, logger)), - mergeMap(async itemsCount => { + mergeMap(async (itemsCount) => { const viewport = layout.getViewport(itemsCount) || getDefaultViewPort(); await Promise.all([ driver.setViewport(viewport, logger), @@ -116,7 +116,7 @@ export function screenshotsObservableFactory( timeRange, })); }), - catchError(err => { + catchError((err) => { logger.error(err); return Rx.of({ elementsPositionAndAttributes: null, timeRange: null, error: err }); }) diff --git a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/wait_for_render.ts b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/wait_for_render.ts index 0e02fa2dacfad..c31c55ea8dec6 100644 --- a/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/wait_for_render.ts +++ b/x-pack/legacy/plugins/reporting/export_types/common/lib/screenshots/wait_for_render.ts @@ -35,13 +35,13 @@ export const waitForRenderComplete = async ( const renderedTasks = []; function waitForRender(visualization: Element) { - return new Promise(resolve => { + return new Promise((resolve) => { visualization.addEventListener('renderComplete', () => resolve()); }); } function waitForRenderDelay() { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(resolve, visLoadDelay); }); } @@ -63,7 +63,7 @@ export const waitForRenderComplete = async ( // capture the first visualization before it was actually in the DOM. // Note: 100 proved too short, see https://github.com/elastic/kibana/issues/22581, // bumping to 250. - const hackyWaitForVisualizations = () => new Promise(r => setTimeout(r, 250)); + const hackyWaitForVisualizations = () => new Promise((r) => setTimeout(r, 250)); return Promise.all(renderedTasks).then(hackyWaitForVisualizations); }, diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.ts index d427600817d69..f6ae8edb9d5cb 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.test.ts @@ -17,7 +17,7 @@ import { createMockReportingCore } from '../../../test_helpers'; import { JobDocPayloadDiscoverCsv } from '../types'; import { executeJobFactory } from './execute_job'; -const delay = (ms: number) => new Promise(resolve => setTimeout(() => resolve(), ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(() => resolve(), ms)); const puid = new Puid(); const getRandomScrollId = () => { @@ -26,7 +26,7 @@ const getRandomScrollId = () => { const getJobDocPayload = (baseObj: any) => baseObj as JobDocPayloadDiscoverCsv; -describe('CSV Execute Job', function() { +describe('CSV Execute Job', function () { const encryptionKey = 'testEncryptionKey'; const headers = { sid: 'test', @@ -58,12 +58,12 @@ describe('CSV Execute Job', function() { get: sinon.stub(), }; - beforeAll(async function() { + beforeAll(async function () { const crypto = nodeCrypto({ encryptionKey }); encryptedHeaders = await crypto.encrypt(headers); }); - beforeEach(async function() { + beforeEach(async function () { configGetStub = sinon.stub(); configGetStub.withArgs('index').returns('.reporting-foo-test'); configGetStub.withArgs('encryptionKey').returns(encryptionKey); @@ -103,7 +103,7 @@ describe('CSV Execute Job', function() { const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); - fieldFormatsRegistry.init(key => (uiConfigMock as any)[key], {}, [ + fieldFormatsRegistry.init((key) => (uiConfigMock as any)[key], {}, [ fieldFormats.StringFormat, ]); @@ -112,8 +112,8 @@ describe('CSV Execute Job', function() { }); }); - describe('basic Elasticsearch call behavior', function() { - it('should decrypt encrypted headers and pass to callAsCurrentUser', async function() { + describe('basic Elasticsearch call behavior', function () { + it('should decrypt encrypted headers and pass to callAsCurrentUser', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); await executeJob( 'job456', @@ -128,7 +128,7 @@ describe('CSV Execute Job', function() { expect(callAsCurrentUserStub.firstCall.args[0]).toEqual('search'); }); - it('should pass the index and body to execute the initial search', async function() { + it('should pass the index and body to execute the initial search', async function () { const index = 'index'; const body = { testBody: true, @@ -152,7 +152,7 @@ describe('CSV Execute Job', function() { expect(searchCall.args[1].body).toBe(body); }); - it('should pass the scrollId from the initial search to the subsequent scroll', async function() { + it('should pass the scrollId from the initial search to the subsequent scroll', async function () { const scrollId = getRandomScrollId(); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -178,7 +178,7 @@ describe('CSV Execute Job', function() { expect(scrollCall.args[1].scrollId).toBe(scrollId); }); - it('should not execute scroll if there are no hits from the search', async function() { + it('should not execute scroll if there are no hits from the search', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); await executeJob( 'job456', @@ -199,7 +199,7 @@ describe('CSV Execute Job', function() { expect(clearScrollCall.args[0]).toBe('clearScroll'); }); - it('should stop executing scroll if there are no hits', async function() { + it('should stop executing scroll if there are no hits', async function () { callAsCurrentUserStub.onFirstCall().resolves({ hits: { hits: [{}], @@ -236,7 +236,7 @@ describe('CSV Execute Job', function() { expect(clearScroll.args[0]).toBe('clearScroll'); }); - it('should call clearScroll with scrollId when there are no more hits', async function() { + it('should call clearScroll with scrollId when there are no more hits', async function () { const lastScrollId = getRandomScrollId(); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -268,7 +268,7 @@ describe('CSV Execute Job', function() { expect(lastCall.args[1].scrollId).toEqual([lastScrollId]); }); - it('calls clearScroll when there is an error iterating the hits', async function() { + it('calls clearScroll when there is an error iterating the hits', async function () { const lastScrollId = getRandomScrollId(); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -302,7 +302,7 @@ describe('CSV Execute Job', function() { }); describe('Warning when cells have formulas', () => { - it('returns `csv_contains_formulas` when cells contain formulas', async function() { + it('returns `csv_contains_formulas` when cells contain formulas', async function () { configGetStub.withArgs('csv', 'checkForFormulas').returns(true); callAsCurrentUserStub.onFirstCall().returns({ hits: { @@ -327,7 +327,7 @@ describe('CSV Execute Job', function() { expect(csvContainsFormulas).toEqual(true); }); - it('returns warnings when headings contain formulas', async function() { + it('returns warnings when headings contain formulas', async function () { configGetStub.withArgs('csv', 'checkForFormulas').returns(true); callAsCurrentUserStub.onFirstCall().returns({ hits: { @@ -352,7 +352,7 @@ describe('CSV Execute Job', function() { expect(csvContainsFormulas).toEqual(true); }); - it('returns no warnings when cells have no formulas', async function() { + it('returns no warnings when cells have no formulas', async function () { configGetStub.withArgs('csv', 'checkForFormulas').returns(true); configGetStub.withArgs('csv', 'escapeFormulaValues').returns(false); callAsCurrentUserStub.onFirstCall().returns({ @@ -378,7 +378,7 @@ describe('CSV Execute Job', function() { expect(csvContainsFormulas).toEqual(false); }); - it('returns no warnings when cells have formulas but are escaped', async function() { + it('returns no warnings when cells have formulas but are escaped', async function () { configGetStub.withArgs('csv', 'checkForFormulas').returns(true); configGetStub.withArgs('csv', 'escapeFormulaValues').returns(true); callAsCurrentUserStub.onFirstCall().returns({ @@ -519,8 +519,8 @@ describe('CSV Execute Job', function() { }); }); - describe('Elasticsearch call errors', function() { - it('should reject Promise if search call errors out', async function() { + describe('Elasticsearch call errors', function () { + it('should reject Promise if search call errors out', async function () { callAsCurrentUserStub.rejects(new Error()); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); const jobParams = getJobDocPayload({ @@ -533,7 +533,7 @@ describe('CSV Execute Job', function() { ).rejects.toMatchInlineSnapshot(`[Error]`); }); - it('should reject Promise if scroll call errors out', async function() { + it('should reject Promise if scroll call errors out', async function () { callAsCurrentUserStub.onFirstCall().resolves({ hits: { hits: [{}], @@ -553,8 +553,8 @@ describe('CSV Execute Job', function() { }); }); - describe('invalid responses', function() { - it('should reject Promise if search returns hits but no _scroll_id', async function() { + describe('invalid responses', function () { + it('should reject Promise if search returns hits but no _scroll_id', async function () { callAsCurrentUserStub.resolves({ hits: { hits: [{}], @@ -575,7 +575,7 @@ describe('CSV Execute Job', function() { ); }); - it('should reject Promise if search returns no hits and no _scroll_id', async function() { + it('should reject Promise if search returns no hits and no _scroll_id', async function () { callAsCurrentUserStub.resolves({ hits: { hits: [], @@ -596,7 +596,7 @@ describe('CSV Execute Job', function() { ); }); - it('should reject Promise if scroll returns hits but no _scroll_id', async function() { + it('should reject Promise if scroll returns hits but no _scroll_id', async function () { callAsCurrentUserStub.onFirstCall().resolves({ hits: { hits: [{}], @@ -624,7 +624,7 @@ describe('CSV Execute Job', function() { ); }); - it('should reject Promise if scroll returns no hits and no _scroll_id', async function() { + it('should reject Promise if scroll returns no hits and no _scroll_id', async function () { callAsCurrentUserStub.onFirstCall().resolves({ hits: { hits: [{}], @@ -653,17 +653,17 @@ describe('CSV Execute Job', function() { }); }); - describe('cancellation', function() { + describe('cancellation', function () { const scrollId = getRandomScrollId(); - beforeEach(function() { + beforeEach(function () { // We have to "re-stub" the callAsCurrentUser stub here so that we can use the fakeFunction // that delays the Promise resolution so we have a chance to call cancellationToken.cancel(). // Otherwise, we get into an endless loop, and don't have a chance to call cancel callAsCurrentUserStub.restore(); callAsCurrentUserStub = sinon .stub(clusterStub, 'callAsCurrentUser') - .callsFake(async function() { + .callsFake(async function () { await delay(1); return { hits: { @@ -674,7 +674,7 @@ describe('CSV Execute Job', function() { }); }); - it('should stop calling Elasticsearch when cancellationToken.cancel is called', async function() { + it('should stop calling Elasticsearch when cancellationToken.cancel is called', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); executeJob( 'job345', @@ -693,7 +693,7 @@ describe('CSV Execute Job', function() { expect(callAsCurrentUserStub.callCount).toBe(callCount + 1); // last call is to clear the scroll }); - it(`shouldn't call clearScroll if it never got a scrollId`, async function() { + it(`shouldn't call clearScroll if it never got a scrollId`, async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); executeJob( 'job345', @@ -711,7 +711,7 @@ describe('CSV Execute Job', function() { } }); - it('should call clearScroll if it got a scrollId', async function() { + it('should call clearScroll if it got a scrollId', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); executeJob( 'job345', @@ -732,8 +732,8 @@ describe('CSV Execute Job', function() { }); }); - describe('csv content', function() { - it('should write column headers to output, even if there are no results', async function() { + describe('csv content', function () { + it('should write column headers to output, even if there are no results', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); const jobParams = getJobDocPayload({ headers: encryptedHeaders, @@ -744,7 +744,7 @@ describe('CSV Execute Job', function() { expect(content).toBe(`one,two\n`); }); - it('should use custom uiSettings csv:separator for header', async function() { + it('should use custom uiSettings csv:separator for header', async function () { mockUiSettingsClient.get.withArgs('csv:separator').returns(';'); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); const jobParams = getJobDocPayload({ @@ -756,7 +756,7 @@ describe('CSV Execute Job', function() { expect(content).toBe(`one;two\n`); }); - it('should escape column headers if uiSettings csv:quoteValues is true', async function() { + it('should escape column headers if uiSettings csv:quoteValues is true', async function () { mockUiSettingsClient.get.withArgs('csv:quoteValues').returns(true); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); const jobParams = getJobDocPayload({ @@ -768,7 +768,7 @@ describe('CSV Execute Job', function() { expect(content).toBe(`"one and a half",two,"three-and-four","five & six"\n`); }); - it(`shouldn't escape column headers if uiSettings csv:quoteValues is false`, async function() { + it(`shouldn't escape column headers if uiSettings csv:quoteValues is false`, async function () { mockUiSettingsClient.get.withArgs('csv:quoteValues').returns(false); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); const jobParams = getJobDocPayload({ @@ -780,7 +780,7 @@ describe('CSV Execute Job', function() { expect(content).toBe(`one and a half,two,three-and-four,five & six\n`); }); - it('should write column headers to output, when there are results', async function() { + it('should write column headers to output, when there are results', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -800,7 +800,7 @@ describe('CSV Execute Job', function() { expect(headerLine).toBe('one,two'); }); - it('should use comma separated values of non-nested fields from _source', async function() { + it('should use comma separated values of non-nested fields from _source', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -821,7 +821,7 @@ describe('CSV Execute Job', function() { expect(valuesLine).toBe('foo,bar'); }); - it('should concatenate the hits from multiple responses', async function() { + it('should concatenate the hits from multiple responses', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -849,7 +849,7 @@ describe('CSV Execute Job', function() { expect(lines[2]).toBe('baz,qux'); }); - it('should use field formatters to format fields', async function() { + it('should use field formatters to format fields', async function () { const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); callAsCurrentUserStub.onFirstCall().resolves({ hits: { @@ -880,16 +880,16 @@ describe('CSV Execute Job', function() { }); }); - describe('maxSizeBytes', function() { + describe('maxSizeBytes', function () { // The following tests use explicitly specified lengths. UTF-8 uses between one and four 8-bit bytes for each // code-point. However, any character that can be represented by ASCII requires one-byte, so a majority of the // tests use these 'simple' characters to make the math easier - describe('when only the headers exceed the maxSizeBytes', function() { + describe('when only the headers exceed the maxSizeBytes', function () { let content: string; let maxSizeReached: boolean; - beforeEach(async function() { + beforeEach(async function () { configGetStub.withArgs('csv', 'maxSizeBytes').returns(1); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); @@ -906,20 +906,20 @@ describe('CSV Execute Job', function() { )); }); - it('should return max_size_reached', function() { + it('should return max_size_reached', function () { expect(maxSizeReached).toBe(true); }); - it('should return empty content', function() { + it('should return empty content', function () { expect(content).toBe(''); }); }); - describe('when headers are equal to maxSizeBytes', function() { + describe('when headers are equal to maxSizeBytes', function () { let content: string; let maxSizeReached: boolean; - beforeEach(async function() { + beforeEach(async function () { configGetStub.withArgs('csv', 'maxSizeBytes').returns(9); const executeJob = await executeJobFactory(mockReportingPlugin, mockLogger); @@ -936,20 +936,20 @@ describe('CSV Execute Job', function() { )); }); - it(`shouldn't return max_size_reached`, function() { + it(`shouldn't return max_size_reached`, function () { expect(maxSizeReached).toBe(false); }); - it(`should return content`, function() { + it(`should return content`, function () { expect(content).toBe('one,two\n'); }); }); - describe('when the data exceeds the maxSizeBytes', function() { + describe('when the data exceeds the maxSizeBytes', function () { let content: string; let maxSizeReached: boolean; - beforeEach(async function() { + beforeEach(async function () { configGetStub.withArgs('csv', 'maxSizeBytes').returns(9); callAsCurrentUserStub.onFirstCall().returns({ @@ -974,20 +974,20 @@ describe('CSV Execute Job', function() { )); }); - it(`should return max_size_reached`, function() { + it(`should return max_size_reached`, function () { expect(maxSizeReached).toBe(true); }); - it(`should return the headers in the content`, function() { + it(`should return the headers in the content`, function () { expect(content).toBe('one,two\n'); }); }); - describe('when headers and data equal the maxSizeBytes', function() { + describe('when headers and data equal the maxSizeBytes', function () { let content: string; let maxSizeReached: boolean; - beforeEach(async function() { + beforeEach(async function () { mockReportingPlugin.getUiSettingsServiceFactory = () => mockUiSettingsClient; configGetStub.withArgs('csv', 'maxSizeBytes').returns(18); @@ -1013,18 +1013,18 @@ describe('CSV Execute Job', function() { )); }); - it(`shouldn't return max_size_reached`, async function() { + it(`shouldn't return max_size_reached`, async function () { expect(maxSizeReached).toBe(false); }); - it('should return headers and data in content', function() { + it('should return headers and data in content', function () { expect(content).toBe('one,two\nfoo,bar\n'); }); }); }); - describe('scroll settings', function() { - it('passes scroll duration to initial search call', async function() { + describe('scroll settings', function () { + it('passes scroll duration to initial search call', async function () { const scrollDuration = 'test'; configGetStub.withArgs('csv', 'scroll').returns({ duration: scrollDuration }); @@ -1050,7 +1050,7 @@ describe('CSV Execute Job', function() { expect(searchCall.args[1].scroll).toBe(scrollDuration); }); - it('passes scroll size to initial search call', async function() { + it('passes scroll size to initial search call', async function () { const scrollSize = 100; configGetStub.withArgs('csv', 'scroll').returns({ size: scrollSize }); @@ -1076,7 +1076,7 @@ describe('CSV Execute Job', function() { expect(searchCall.args[1].size).toBe(scrollSize); }); - it('passes scroll duration to subsequent scroll call', async function() { + it('passes scroll duration to subsequent scroll call', async function () { const scrollDuration = 'test'; configGetStub.withArgs('csv', 'scroll').returns({ duration: scrollDuration }); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/cell_has_formula.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/cell_has_formula.ts index b285e546ca5e3..1433d852ce630 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/cell_has_formula.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/cell_has_formula.ts @@ -8,4 +8,4 @@ import { startsWith } from 'lodash'; import { CSV_FORMULA_CHARS } from '../../../../common/constants'; export const cellHasFormulas = (val: string) => - CSV_FORMULA_CHARS.some(formulaChar => startsWith(val, formulaChar)); + CSV_FORMULA_CHARS.some((formulaChar) => startsWith(val, formulaChar)); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.test.ts index 972ca1777bd73..114512435a4c3 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.test.ts @@ -23,7 +23,7 @@ describe(`Check CSV Injected values`, () => { ).toBe(false); }); - formulaValues.forEach(formula => { + formulaValues.forEach((formula) => { it(`returns 'true' when cells start with "${formula}"`, () => { expect( checkIfRowsHaveFormulas( @@ -51,7 +51,7 @@ describe(`Check CSV Injected values`, () => { }); }); - formulaValues.forEach(formula => { + formulaValues.forEach((formula) => { it(`returns 'true' when headers start with "${formula}"`, () => { expect( checkIfRowsHaveFormulas( @@ -79,7 +79,7 @@ describe(`Check CSV Injected values`, () => { }); }); - nonRows.forEach(nonRow => { + nonRows.forEach((nonRow) => { it(`returns false when there's "${nonRow}" for rows`, () => { expect( checkIfRowsHaveFormulas( diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.ts index 0ec39c527d656..d89eb45ead75e 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/check_cells_for_formulas.ts @@ -15,5 +15,5 @@ export const checkIfRowsHaveFormulas = (flattened: IFlattened, fields: string[]) const pruned = _.pick(flattened, fields); const cells = [..._.keys(pruned), ...(_.values(pruned) as string[])]; - return _.some(cells, cell => cellHasFormulas(cell)); + return _.some(cells, (cell) => cellHasFormulas(cell)); }; diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/escape_value.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/escape_value.test.ts index dd0f9d08b864b..be1f34288bd25 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/escape_value.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/escape_value.test.ts @@ -7,49 +7,49 @@ import expect from '@kbn/expect'; import { createEscapeValue } from './escape_value'; -describe('escapeValue', function() { - describe('quoteValues is true', function() { +describe('escapeValue', function () { + describe('quoteValues is true', function () { let escapeValue: (val: string) => string; - beforeEach(function() { + beforeEach(function () { escapeValue = createEscapeValue(true, false); }); - it('should escape value with spaces', function() { + it('should escape value with spaces', function () { expect(escapeValue('baz qux')).to.be('"baz qux"'); }); - it('should escape values with hyphens', function() { + it('should escape values with hyphens', function () { expect(escapeValue('baz-qux')).to.be('"baz-qux"'); }); - it('should not escape small integers', function() { + it('should not escape small integers', function () { expect(escapeValue((1).toString())).to.be('1'); }); - it('should not escape small whole numbers', function() { + it('should not escape small whole numbers', function () { expect(escapeValue((1.0).toString())).to.be('1'); }); - it('should escape decimal numbers', function() { + it('should escape decimal numbers', function () { expect(escapeValue((1.1).toString())).to.be('"1.1"'); }); - it('should not comma-separate large integers', function() { + it('should not comma-separate large integers', function () { expect(escapeValue((1000000).toString())).to.be('1000000'); }); - it('should treat booleans like strings', function() { + it('should treat booleans like strings', function () { expect(escapeValue(true.toString())).to.be('true'); }); }); - describe('quoteValues is false', function() { + describe('quoteValues is false', function () { let escapeValue: (val: string) => string; - beforeEach(function() { + beforeEach(function () { escapeValue = createEscapeValue(false, false); }); - it('should return the value unescaped', function() { + it('should return the value unescaped', function () { const value = '"foo, bar & baz-qux"'; expect(escapeValue(value)).to.be(value); }); @@ -58,12 +58,12 @@ describe('escapeValue', function() { describe('escapeValues', () => { describe('when true', () => { let escapeValue: (val: string) => string; - beforeEach(function() { + beforeEach(function () { escapeValue = createEscapeValue(true, true); }); - ['@', '+', '-', '='].forEach(badChar => { - it(`should escape ${badChar} injection values`, function() { + ['@', '+', '-', '='].forEach((badChar) => { + it(`should escape ${badChar} injection values`, function () { expect(escapeValue(`${badChar}cmd|' /C calc'!A0`)).to.be( `"'${badChar}cmd|' /C calc'!A0"` ); @@ -73,12 +73,12 @@ describe('escapeValue', function() { describe('when false', () => { let escapeValue: (val: string) => string; - beforeEach(function() { + beforeEach(function () { escapeValue = createEscapeValue(true, false); }); - ['@', '+', '-', '='].forEach(badChar => { - it(`should not escape ${badChar} injection values`, function() { + ['@', '+', '-', '='].forEach((badChar) => { + it(`should not escape ${badChar} injection values`, function () { expect(escapeValue(`${badChar}cmd|' /C calc'!A0`)).to.be(`"${badChar}cmd|' /C calc'!A0"`); }); }); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts index 9ab434e6a058b..0434da3d11fe1 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.test.ts @@ -14,7 +14,7 @@ import { fieldFormatMapFactory } from './field_format_map'; type ConfigValue = { number: { id: string; params: {} } } | string; -describe('field format map', function() { +describe('field format map', function () { const indexPatternSavedObject = { id: 'logstash-*', type: 'index-pattern', @@ -40,17 +40,17 @@ describe('field format map', function() { const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormatsRegistry); - it('should build field format map with entry per index pattern field', function() { + it('should build field format map with entry per index pattern field', function () { expect(formatMap.has('field1')).to.be(true); expect(formatMap.has('field2')).to.be(true); expect(formatMap.has('field_not_in_index')).to.be(false); }); - it('should create custom FieldFormat for fields with configured field formatter', function() { + it('should create custom FieldFormat for fields with configured field formatter', function () { expect(formatMap.get('field1').convert(testValue)).to.be('3.9KB'); }); - it('should create default FieldFormat for fields with no field formatter', function() { + it('should create default FieldFormat for fields with no field formatter', function () { expect(formatMap.get('field2').convert(testValue)).to.be('4,000'); }); }); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts index e1459e195d9f6..6cb4d0bbb1c65 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/field_format_map.ts @@ -35,7 +35,7 @@ export function fieldFormatMapFactory( // Add FieldFormat instances for fields with custom formatters if (_.has(indexPatternSavedObject, 'attributes.fieldFormatMap')) { const fieldFormatMap = JSON.parse(indexPatternSavedObject.attributes.fieldFormatMap); - Object.keys(fieldFormatMap).forEach(fieldName => { + Object.keys(fieldFormatMap).forEach((fieldName) => { const formatConfig: FieldFormatConfig = fieldFormatMap[fieldName]; if (!_.isEmpty(formatConfig)) { diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.test.ts index 1e06e78357399..4dbdcbdd4f744 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.test.ts @@ -9,12 +9,12 @@ import { createFlattenHit } from './flatten_hit'; type Hit = Record; -describe('flattenHit', function() { +describe('flattenHit', function () { let flattenHit: (hit: Hit) => Record; let hit: Hit; let metaFields: string[]; - beforeEach(function() { + beforeEach(function () { const fields = [ 'tags.text', 'tags.label', @@ -69,7 +69,7 @@ describe('flattenHit', function() { }; }); - it('flattens keys as far down as the mapping goes', function() { + it('flattens keys as far down as the mapping goes', function () { const flat = flattenHit(hit); expect(flat).to.have.property('geo.coordinates', hit._source.geo.coordinates); @@ -82,7 +82,7 @@ describe('flattenHit', function() { expect(flat).to.have.property('bytes', 10039103); }); - it('flattens keys not in the mapping', function() { + it('flattens keys not in the mapping', function () { const flat = flattenHit(hit); expect(flat).to.have.property('noMapping', true); @@ -90,7 +90,7 @@ describe('flattenHit', function() { expect(flat.groups).to.eql(['loners']); }); - it('flattens conflicting types in the mapping', function() { + it('flattens conflicting types in the mapping', function () { const flat = flattenHit(hit); expect(flat).to.not.have.property('user'); @@ -98,13 +98,13 @@ describe('flattenHit', function() { expect(flat).to.have.property('user.id', hit._source.user.id); }); - it('should preserve objects in arrays', function() { + it('should preserve objects in arrays', function () { const flat = flattenHit(hit); expect(flat).to.have.property('tags', hit._source.tags); }); - it('does not enter into nested fields', function() { + it('does not enter into nested fields', function () { const flat = flattenHit(hit); expect(flat).to.have.property('team', hit._source.team); @@ -114,36 +114,36 @@ describe('flattenHit', function() { expect(flat).to.not.have.property('team.0'); }); - it('unwraps script fields', function() { + it('unwraps script fields', function () { const flat = flattenHit(hit); expect(flat).to.have.property('delta', 42); }); - it('assumes that all fields are "computed fields"', function() { + it('assumes that all fields are "computed fields"', function () { const flat = flattenHit(hit); expect(flat).to.have.property('random', 0.12345); }); - describe('metaFields', function() { - beforeEach(function() { + describe('metaFields', function () { + beforeEach(function () { metaFields.push('_metaKey'); }); - it('ignores fields that start with an _ and are not in the metaFields', function() { + it('ignores fields that start with an _ and are not in the metaFields', function () { hit.fields._notMetaKey = [100]; const flat = flattenHit(hit); expect(flat).to.not.have.property('_notMetaKey'); }); - it('includes underscore-prefixed keys that are in the metaFields', function() { + it('includes underscore-prefixed keys that are in the metaFields', function () { hit.fields._metaKey = [100]; const flat = flattenHit(hit); expect(flat).to.have.property('_metaKey', 100); }); - it('handles fields that are not arrays, like _timestamp', function() { + it('handles fields that are not arrays, like _timestamp', function () { hit.fields._metaKey = 20000; const flat = flattenHit(hit); expect(flat).to.have.property('_metaKey', 20000); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.ts index 328d49a27911c..a4c634439ec45 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/flatten_hit.ts @@ -40,7 +40,7 @@ export function createFlattenHit( }; const flattenMetaFields = (flat: Hit, hit: Hit) => { - _.each(metaFields, meta => { + _.each(metaFields, (meta) => { if (meta === '_source') return; flat[meta] = hit[meta]; }); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.test.ts index b38bad1179471..15bd52afc9118 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.test.ts @@ -7,11 +7,11 @@ import expect from '@kbn/expect'; import { createFormatCsvValues } from './format_csv_values'; -describe('formatCsvValues', function() { +describe('formatCsvValues', function () { const separator = ','; const fields = ['foo', 'bar']; const mockEscapeValue = (value: any, index: number, array: any[]) => value || ''; - describe('with _source as one of the fields', function() { + describe('with _source as one of the fields', function () { const formatsMap = new Map(); const formatCsvValues = createFormatCsvValues( mockEscapeValue, @@ -19,22 +19,22 @@ describe('formatCsvValues', function() { ['foo', '_source'], formatsMap ); - it('should return full _source for _source field', function() { + it('should return full _source for _source field', function () { const values = { foo: 'baz', }; expect(formatCsvValues(values)).to.be('baz,{"foo":"baz"}'); }); }); - describe('without field formats', function() { + describe('without field formats', function () { const formatsMap = new Map(); const formatCsvValues = createFormatCsvValues(mockEscapeValue, separator, fields, formatsMap); - it('should use the specified separator', function() { + it('should use the specified separator', function () { expect(formatCsvValues({})).to.be(separator); }); - it('should replace null and undefined with empty strings', function() { + it('should replace null and undefined with empty strings', function () { const values = { foo: undefined, bar: null, @@ -42,7 +42,7 @@ describe('formatCsvValues', function() { expect(formatCsvValues(values)).to.be(','); }); - it('should JSON.stringify objects', function() { + it('should JSON.stringify objects', function () { const values = { foo: { baz: 'qux', @@ -51,7 +51,7 @@ describe('formatCsvValues', function() { expect(formatCsvValues(values)).to.be('{"baz":"qux"},'); }); - it('should concatenate strings', function() { + it('should concatenate strings', function () { const values = { foo: 'baz', bar: 'qux', @@ -60,7 +60,7 @@ describe('formatCsvValues', function() { }); }); - describe('with field formats', function() { + describe('with field formats', function () { const mockFieldFormat = { convert: (val: string) => String(val).toUpperCase(), }; @@ -68,7 +68,7 @@ describe('formatCsvValues', function() { formatsMap.set('bar', mockFieldFormat); const formatCsvValues = createFormatCsvValues(mockEscapeValue, separator, fields, formatsMap); - it('should replace null and undefined with empty strings', function() { + it('should replace null and undefined with empty strings', function () { const values = { foo: undefined, bar: null, @@ -76,7 +76,7 @@ describe('formatCsvValues', function() { expect(formatCsvValues(values)).to.be(','); }); - it('should format value with appropriate FieldFormat', function() { + it('should format value with appropriate FieldFormat', function () { const values = { foo: 'baz', bar: 'qux', diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.ts index 35093f45fdd5b..bb4e2be86f5df 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/format_csv_values.ts @@ -15,7 +15,7 @@ export function createFormatCsvValues( ) { return function formatCsvValues(values: Record) { return fields - .map(field => { + .map((field) => { let value; if (field === '_source') { value = values; @@ -34,8 +34,8 @@ export function createFormatCsvValues( return formattedValue; }) - .map(value => (isObject(value) ? JSON.stringify(value) : value)) - .map(value => (value ? value.toString() : value)) + .map((value) => (isObject(value) ? JSON.stringify(value) : value)) + .map((value) => (value ? value.toString() : value)) .map(escapeValue) .join(separator); }; diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/hit_iterator.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/hit_iterator.test.ts index 905d9cd68b128..7ef4f502b34a3 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/hit_iterator.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/hit_iterator.test.ts @@ -25,7 +25,7 @@ const mockConfig: ScrollConfig = { duration: '2s', size: 123 }; let realCancellationToken = new CancellationToken(); let isCancelledStub: sinon.SinonStub<[], boolean>; -describe('hitIterator', function() { +describe('hitIterator', function () { beforeEach(() => { debugLogStub.resetHistory(); warnLogStub.resetHistory(); diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.test.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.test.ts index 843ff82e7c4bc..7a35de1cea19b 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.test.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.test.ts @@ -7,55 +7,55 @@ import expect from '@kbn/expect'; import { MaxSizeStringBuilder } from './max_size_string_builder'; -describe('MaxSizeStringBuilder', function() { - describe('tryAppend', function() { - it(`should return true if appended string is under maxSize`, function() { +describe('MaxSizeStringBuilder', function () { + describe('tryAppend', function () { + it(`should return true if appended string is under maxSize`, function () { const builder = new MaxSizeStringBuilder(100); const result = builder.tryAppend('aa'); expect(result).to.be(true); }); - it(`should return false if appended string is over the maxSize`, function() { + it(`should return false if appended string is over the maxSize`, function () { const builder = new MaxSizeStringBuilder(1); const result = builder.tryAppend('aa'); expect(result).to.be(false); }); - it(`should return true then false if second appended string puts total size over the maxSize`, function() { + it(`should return true then false if second appended string puts total size over the maxSize`, function () { const builder = new MaxSizeStringBuilder(1); expect(builder.tryAppend('a')).to.be(true); expect(builder.tryAppend('a')).to.be(false); }); }); - describe('getBuffer', function() { - it(`should return an empty string when we don't call tryAppend`, function() { + describe('getBuffer', function () { + it(`should return an empty string when we don't call tryAppend`, function () { const builder = new MaxSizeStringBuilder(100); expect(builder.getString()).to.be(''); }); - it('should return equivalent string if tryAppend called once and less than maxSize', function() { + it('should return equivalent string if tryAppend called once and less than maxSize', function () { const str = 'foo'; const builder = new MaxSizeStringBuilder(100); builder.tryAppend(str); expect(builder.getString()).to.be(str); }); - it('should return equivalent string if tryAppend called multiple times and total size less than maxSize', function() { + it('should return equivalent string if tryAppend called multiple times and total size less than maxSize', function () { const strs = ['foo', 'bar', 'baz']; const builder = new MaxSizeStringBuilder(100); - strs.forEach(str => builder.tryAppend(str)); + strs.forEach((str) => builder.tryAppend(str)); expect(builder.getString()).to.be(strs.join('')); }); - it('should return empty string if tryAppend called one time with size greater than maxSize', function() { + it('should return empty string if tryAppend called one time with size greater than maxSize', function () { const str = 'aa'; // each a is one byte const builder = new MaxSizeStringBuilder(1); builder.tryAppend(str); expect(builder.getString()).to.be(''); }); - it('should return partial string if tryAppend called multiple times with total size greater than maxSize', function() { + it('should return partial string if tryAppend called multiple times with total size greater than maxSize', function () { const str = 'a'; // each a is one byte const builder = new MaxSizeStringBuilder(1); builder.tryAppend(str); @@ -64,13 +64,13 @@ describe('MaxSizeStringBuilder', function() { }); }); - describe('getSizeInBytes', function() { - it(`should return 0 when no strings have been appended`, function() { + describe('getSizeInBytes', function () { + it(`should return 0 when no strings have been appended`, function () { const builder = new MaxSizeStringBuilder(100); expect(builder.getSizeInBytes()).to.be(0); }); - it(`should the size in bytes`, function() { + it(`should the size in bytes`, function () { const builder = new MaxSizeStringBuilder(100); const stringValue = 'foobar'; builder.tryAppend(stringValue); diff --git a/x-pack/legacy/plugins/reporting/export_types/png/server/execute_job/index.ts b/x-pack/legacy/plugins/reporting/export_types/png/server/execute_job/index.ts index c1a2c12cd9f82..0d0a9e748682a 100644 --- a/x-pack/legacy/plugins/reporting/export_types/png/server/execute_job/index.ts +++ b/x-pack/legacy/plugins/reporting/export_types/png/server/execute_job/index.ts @@ -39,9 +39,9 @@ export const executeJobFactory: QueuedPngExecutorFactory = async function execut const jobLogger = logger.clone([jobId]); const process$: Rx.Observable = Rx.of(1).pipe( mergeMap(() => decryptJobHeaders({ encryptionKey, job, logger })), - map(decryptedHeaders => omitBlacklistedHeaders({ job, decryptedHeaders })), - map(filteredHeaders => getConditionalHeaders({ config, job, filteredHeaders })), - mergeMap(conditionalHeaders => { + map((decryptedHeaders) => omitBlacklistedHeaders({ job, decryptedHeaders })), + map((filteredHeaders) => getConditionalHeaders({ config, job, filteredHeaders })), + mergeMap((conditionalHeaders) => { const urls = getFullUrls({ config, job }); const hashUrl = urls[0]; if (apmGetAssets) apmGetAssets.end(); @@ -66,7 +66,7 @@ export const executeJobFactory: QueuedPngExecutorFactory = async function execut warnings, }; }), - catchError(err => { + catchError((err) => { jobLogger.error(err); return Rx.throwError(err); }) diff --git a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/execute_job/index.ts b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/execute_job/index.ts index 619e3e9db70ad..b0b2d02305b9b 100644 --- a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/execute_job/index.ts +++ b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/execute_job/index.ts @@ -42,9 +42,11 @@ export const executeJobFactory: QueuedPdfExecutorFactory = async function execut const jobLogger = logger.clone([jobId]); const process$: Rx.Observable = Rx.of(1).pipe( mergeMap(() => decryptJobHeaders({ encryptionKey, job, logger })), - map(decryptedHeaders => omitBlacklistedHeaders({ job, decryptedHeaders })), - map(filteredHeaders => getConditionalHeaders({ config, job, filteredHeaders })), - mergeMap(conditionalHeaders => getCustomLogo({ reporting, config, job, conditionalHeaders })), + map((decryptedHeaders) => omitBlacklistedHeaders({ job, decryptedHeaders })), + map((filteredHeaders) => getConditionalHeaders({ config, job, filteredHeaders })), + mergeMap((conditionalHeaders) => + getCustomLogo({ reporting, config, job, conditionalHeaders }) + ), mergeMap(({ logo, conditionalHeaders }) => { const urls = getFullUrls({ config, job }); @@ -76,7 +78,7 @@ export const executeJobFactory: QueuedPdfExecutorFactory = async function execut warnings, }; }), - catchError(err => { + catchError((err) => { jobLogger.error(err); return Rx.throwError(err); }) diff --git a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/generate_pdf.ts b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/generate_pdf.ts index 0d23eb62fe37c..3b626c8f0da44 100644 --- a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/generate_pdf.ts +++ b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/generate_pdf.ts @@ -16,7 +16,7 @@ import { pdf } from './pdf'; import { getTracker } from './tracker'; const getTimeRange = (urlScreenshots: ScreenshotResults[]) => { - const grouped = groupBy(urlScreenshots.map(u => u.timeRange)); + const grouped = groupBy(urlScreenshots.map((u) => u.timeRange)); const values = Object.values(grouped); if (values.length === 1) { return values[0][0]; @@ -65,8 +65,8 @@ export async function generatePdfObservableFactory(reporting: ReportingCore) { } tracker.endSetup(); - results.forEach(r => { - r.screenshots.forEach(screenshot => { + results.forEach((r) => { + r.screenshots.forEach((screenshot) => { logger.debug(`Adding image to PDF. Image base64 size: ${screenshot.base64EncodedData?.length || 0}`); // prettier-ignore tracker.startAddImage(); tracker.endAddImage(); diff --git a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/pdf/index.js b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/pdf/index.js index fd3619c31dece..f9a9d9d85bfd3 100644 --- a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/pdf/index.js +++ b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/pdf/index.js @@ -31,7 +31,7 @@ function getFont(text) { class PdfMaker { constructor(layout, logo) { - const fontPath = filename => path.resolve(assetPath, 'fonts', filename); + const fontPath = (filename) => path.resolve(assetPath, 'fonts', filename); const fonts = { Roboto: { normal: fontPath('roboto/Roboto-Regular.ttf'), @@ -146,7 +146,7 @@ class PdfMaker { ); } return new Promise((resolve, reject) => { - const concatStream = concat(function(pdfBuffer) { + const concatStream = concat(function (pdfBuffer) { resolve(pdfBuffer); }); @@ -198,7 +198,7 @@ function getTemplate(layout, logo, title) { }), pageMargins: [pageMarginWidth, pageMarginTop, pageMarginWidth, pageMarginBottom], - header: function() { + header: function () { return { margin: [pageMarginWidth, pageMarginTop / 4, pageMarginWidth, 0], text: title, @@ -211,7 +211,7 @@ function getTemplate(layout, logo, title) { }; }, - footer: function(currentPage, pageCount) { + footer: function (currentPage, pageCount) { const logoPath = path.resolve(assetPath, 'img', 'logo-grey.png'); return { margin: [pageMarginWidth, pageMarginBottom / 4, pageMarginWidth, 0], diff --git a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/uri_encode.js b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/uri_encode.js index f764271c22a2d..d057cfba4ef30 100644 --- a/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/uri_encode.js +++ b/x-pack/legacy/plugins/reporting/export_types/printable_pdf/server/lib/uri_encode.js @@ -9,9 +9,9 @@ import { url } from '../../../../../../../../src/plugins/kibana_utils/server'; function toKeyValue(obj) { const parts = []; - forEach(obj, function(value, key) { + forEach(obj, function (value, key) { if (isArray(value)) { - forEach(value, function(arrayValue) { + forEach(value, function (arrayValue) { const keyStr = url.encodeUriQuery(key, true); const valStr = arrayValue === true ? '' : '=' + url.encodeUriQuery(arrayValue, true); parts.push(keyStr + valStr); diff --git a/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts b/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts index 3dce8bf4e6819..6480fb4413f04 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts @@ -178,7 +178,7 @@ export class HeadlessChromiumDriver { `Timed out waiting for the items selected to equal ${toEqual}. Found: ${result}. Context: ${context.context}` ); } - await new Promise(r => setTimeout(r, WAIT_FOR_DELAY_MS)); + await new Promise((r) => setTimeout(r, WAIT_FOR_DELAY_MS)); } } diff --git a/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver_factory/index.ts b/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver_factory/index.ts index 3189b262ea1bd..246c605f4bfe6 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver_factory/index.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/chromium/driver_factory/index.ts @@ -136,7 +136,7 @@ export class HeadlessChromiumDriverFactory { observer.add( terminate$ .pipe( - tap(signal => { + tap((signal) => { logger.debug(`Termination signal received: ${signal}`); }), ignoreElements() @@ -165,7 +165,7 @@ export class HeadlessChromiumDriverFactory { logger.debug(`deleting chromium user data directory at [${userDataDir}]`); // the unsubscribe function isn't `async` so we're going to make our best effort at // deleting the userDataDir and if it fails log an error. - del(userDataDir, { force: true }).catch(error => { + del(userDataDir, { force: true }).catch((error) => { logger.error(`error deleting user data directory at [${userDataDir}]: [${error}]`); }); }); @@ -174,7 +174,7 @@ export class HeadlessChromiumDriverFactory { getBrowserLogger(page: Page, logger: LevelLogger): Rx.Observable { const consoleMessages$ = Rx.fromEvent(page, 'console').pipe( - map(line => { + map((line) => { if (line.type() === 'error') { logger.error(line.text(), ['headless-browser-console']); } else { @@ -184,7 +184,7 @@ export class HeadlessChromiumDriverFactory { ); const pageRequestFailed$ = Rx.fromEvent(page, 'requestfailed').pipe( - map(req => { + map((req) => { const failure = req.failure && req.failure(); if (failure) { logger.warning( @@ -215,7 +215,7 @@ export class HeadlessChromiumDriverFactory { getPageExit(browser: Browser, page: Page) { const pageError$ = Rx.fromEvent(page, 'error').pipe( - mergeMap(err => { + mergeMap((err) => { return Rx.throwError( i18n.translate('xpack.reporting.browsers.chromium.errorDetected', { defaultMessage: 'Reporting detected an error: {err}', @@ -226,7 +226,7 @@ export class HeadlessChromiumDriverFactory { ); const uncaughtExceptionPageError$ = Rx.fromEvent(page, 'pageerror').pipe( - mergeMap(err => { + mergeMap((err) => { return Rx.throwError( i18n.translate('xpack.reporting.browsers.chromium.pageErrorDetected', { defaultMessage: `Reporting detected an error on the page: {err}`, diff --git a/x-pack/legacy/plugins/reporting/server/browsers/download/checksum.ts b/x-pack/legacy/plugins/reporting/server/browsers/download/checksum.ts index fd68a8e356e10..3191a8968383c 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/download/checksum.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/download/checksum.ts @@ -11,6 +11,6 @@ import { readableEnd } from './util'; export async function md5(path: string) { const hash = createHash('md5'); - await readableEnd(createReadStream(path).on('data', chunk => hash.update(chunk))); + await readableEnd(createReadStream(path).on('data', (chunk) => hash.update(chunk))); return hash.digest('hex'); } diff --git a/x-pack/legacy/plugins/reporting/server/browsers/download/clean.ts b/x-pack/legacy/plugins/reporting/server/browsers/download/clean.ts index a2d1fc7f91a29..8988cbd1c9ec2 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/download/clean.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/download/clean.ts @@ -27,7 +27,7 @@ export async function clean(dir: string, expectedPaths: string[]) { throw error; } - await asyncMap(filenames, async filename => { + await asyncMap(filenames, async (filename) => { const path = resolvePath(dir, filename); if (!expectedPaths.includes(path)) { log(`Deleting unexpected file ${path}`); diff --git a/x-pack/legacy/plugins/reporting/server/browsers/download/download.test.ts b/x-pack/legacy/plugins/reporting/server/browsers/download/download.test.ts index 901fc6ccf9b22..05ee2862f017b 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/download/download.test.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/download/download.test.ts @@ -43,9 +43,7 @@ test('downloads the url to the path', async () => { test('returns the md5 hex hash of the http body', async () => { const BODY = 'foobar'; - const HASH = createHash('md5') - .update(BODY) - .digest('hex'); + const HASH = createHash('md5').update(BODY).digest('hex'); request.mockImplementationOnce(async () => { return { data: new ReadableOf(BODY), diff --git a/x-pack/legacy/plugins/reporting/server/browsers/download/ensure_downloaded.ts b/x-pack/legacy/plugins/reporting/server/browsers/download/ensure_downloaded.ts index 1170e53669e33..f1f609ed5607b 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/download/ensure_downloaded.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/download/ensure_downloaded.ts @@ -39,12 +39,12 @@ export async function ensureAllBrowsersDownloaded() { * @return {Promise} */ async function ensureDownloaded(browsers: BrowserDownload[]) { - await asyncMap(browsers, async browser => { + await asyncMap(browsers, async (browser) => { const { archivesPath } = browser.paths; await clean( archivesPath, - browser.paths.packages.map(p => resolvePath(archivesPath, p.archiveFilename)) + browser.paths.packages.map((p) => resolvePath(archivesPath, p.archiveFilename)) ); const invalidChecksums: string[] = []; diff --git a/x-pack/legacy/plugins/reporting/server/browsers/extract/unzip.js b/x-pack/legacy/plugins/reporting/server/browsers/extract/unzip.js index 80499f8f76f37..d57d04a52f46e 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/extract/unzip.js +++ b/x-pack/legacy/plugins/reporting/server/browsers/extract/unzip.js @@ -8,8 +8,8 @@ import extractZip from 'extract-zip'; import { ExtractError } from './extract_error'; export function unzip(filepath, target) { - return new Promise(function(resolve, reject) { - extractZip(filepath, { dir: target }, err => { + return new Promise(function (resolve, reject) { + extractZip(filepath, { dir: target }, (err) => { if (err) { return reject(new ExtractError(err)); } diff --git a/x-pack/legacy/plugins/reporting/server/browsers/safe_child_process.ts b/x-pack/legacy/plugins/reporting/server/browsers/safe_child_process.ts index 6f86a62c21575..92ef1bc6f8704 100644 --- a/x-pack/legacy/plugins/reporting/server/browsers/safe_child_process.ts +++ b/x-pack/legacy/plugins/reporting/server/browsers/safe_child_process.ts @@ -25,7 +25,7 @@ export function safeChildProcess( ).pipe(take(1), share()); const ownTerminateMapToKill$ = ownTerminateSignal$.pipe( - tap(signal => { + tap((signal) => { logger.debug(`Kibana process received terminate signal: ${signal}`); }), mapTo('SIGKILL') @@ -33,7 +33,7 @@ export function safeChildProcess( const kibanaForceExit$ = Rx.fromEvent(process as NodeJS.EventEmitter, 'exit').pipe( take(1), - tap(signal => { + tap((signal) => { logger.debug(`Kibana process forcefully exited with signal: ${signal}`); }), mapTo('SIGKILL') @@ -52,7 +52,7 @@ export function safeChildProcess( ownTerminateSignal$.pipe( delay(1), - tap(signal => { + tap((signal) => { logger.debug(`Kibana process terminate signal was: ${signal}. Closing the browser...`); return process.kill(process.pid, signal); }) diff --git a/x-pack/legacy/plugins/reporting/server/lib/__tests__/check_license.js b/x-pack/legacy/plugins/reporting/server/lib/__tests__/check_license.js index 394f88c37087c..294a0df56756e 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/__tests__/check_license.js +++ b/x-pack/legacy/plugins/reporting/server/lib/__tests__/check_license.js @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { set } from 'lodash'; import { checkLicenseFactory } from '../check_license'; -describe('check_license', function() { +describe('check_license', function () { let mockLicenseInfo; let checkLicense; diff --git a/x-pack/legacy/plugins/reporting/server/lib/__tests__/export_types_registry.js b/x-pack/legacy/plugins/reporting/server/lib/__tests__/export_types_registry.js index 9e78d5aa8c9c4..3f8b7e7e75af1 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/__tests__/export_types_registry.js +++ b/x-pack/legacy/plugins/reporting/server/lib/__tests__/export_types_registry.js @@ -7,32 +7,32 @@ import expect from '@kbn/expect'; import { ExportTypesRegistry } from '../export_types_registry'; -describe('ExportTypesRegistry', function() { +describe('ExportTypesRegistry', function () { let exportTypesRegistry; - beforeEach(function() { + beforeEach(function () { exportTypesRegistry = new ExportTypesRegistry(); }); - describe('register', function() { - it(`doesn't throw an Error when using a new type with a string id`, function() { + describe('register', function () { + it(`doesn't throw an Error when using a new type with a string id`, function () { expect(() => { exportTypesRegistry.register({ id: 'foo' }); }).to.not.throwError(); }); - it('throws an Error when registering a type without an id', function() { + it('throws an Error when registering a type without an id', function () { expect(() => { exportTypesRegistry.register({}); }).to.throwError(); }); - it('throws an Error when registering a type with an integer id', function() { + it('throws an Error when registering a type with an integer id', function () { expect(() => { exportTypesRegistry.register({ id: 1 }); }).to.throwError(); }); - it('throws an Error when registering the same id twice', function() { + it('throws an Error when registering the same id twice', function () { const id = 'foo'; expect(() => { exportTypesRegistry.register({ id }); @@ -44,8 +44,8 @@ describe('ExportTypesRegistry', function() { }); }); - describe('getById', function() { - it('returns the same object that was registered', function() { + describe('getById', function () { + it('returns the same object that was registered', function () { const id = 'foo'; const obj = { id }; exportTypesRegistry.register(obj); @@ -53,37 +53,37 @@ describe('ExportTypesRegistry', function() { expect(exportTypesRegistry.getById(id)).to.be(obj); }); - it(`throws an Error if the id isn't found`, function() { + it(`throws an Error if the id isn't found`, function () { expect(() => { exportTypesRegistry.getById('foo'); }).to.throwError(); }); }); - describe('getAll', function() { - it('returns an empty Iterator if no objects have been registered', function() { + describe('getAll', function () { + it('returns an empty Iterator if no objects have been registered', function () { const array = Array.from(exportTypesRegistry.getAll()); expect(array.length).to.be(0); }); - it('returns all objects that have been registered', function() { + it('returns all objects that have been registered', function () { const obj1 = { id: 'foo' }; const obj2 = { id: 'bar' }; const objs = [obj1, obj2]; - objs.forEach(obj => exportTypesRegistry.register(obj)); + objs.forEach((obj) => exportTypesRegistry.register(obj)); const all = Array.from(exportTypesRegistry.getAll()); expect(all).to.contain(obj1); expect(all).to.contain(obj2); }); }); - describe('getSize', function() { - it('returns 0 initially', function() { + describe('getSize', function () { + it('returns 0 initially', function () { const size = exportTypesRegistry.getSize(); expect(size).to.be(0); }); - it('returns the number of objects that have been added', function() { + it('returns the number of objects that have been added', function () { exportTypesRegistry.register({ id: 'foo' }); exportTypesRegistry.register({ id: 'bar' }); exportTypesRegistry.register({ id: 'baz' }); @@ -92,33 +92,33 @@ describe('ExportTypesRegistry', function() { }); }); - describe('get', function() { - it('returns obj that matches the predicate', function() { + describe('get', function () { + it('returns obj that matches the predicate', function () { const prop = 'fooProp'; const match = { id: 'foo', prop }; - [match, { id: 'bar' }, { id: 'baz' }].forEach(obj => exportTypesRegistry.register(obj)); - expect(exportTypesRegistry.get(item => item.prop === prop)).to.be(match); + [match, { id: 'bar' }, { id: 'baz' }].forEach((obj) => exportTypesRegistry.register(obj)); + expect(exportTypesRegistry.get((item) => item.prop === prop)).to.be(match); }); - it('throws Error if multiple items match predicate', function() { + it('throws Error if multiple items match predicate', function () { const prop = 'fooProp'; [ { id: 'foo', prop }, { id: 'bar', prop }, - ].forEach(obj => exportTypesRegistry.register(obj)); + ].forEach((obj) => exportTypesRegistry.register(obj)); expect(() => { - exportTypesRegistry.get(item => item.prop === prop); + exportTypesRegistry.get((item) => item.prop === prop); }).to.throwError(); }); - it('throws Error if no items match predicate', function() { + it('throws Error if no items match predicate', function () { const prop = 'fooProp'; [ { id: 'foo', prop }, { id: 'bar', prop }, - ].forEach(obj => exportTypesRegistry.register(obj)); + ].forEach((obj) => exportTypesRegistry.register(obj)); expect(() => { - exportTypesRegistry.get(item => item.prop !== prop); + exportTypesRegistry.get((item) => item.prop !== prop); }).to.throwError(); }); }); diff --git a/x-pack/legacy/plugins/reporting/server/lib/check_license.ts b/x-pack/legacy/plugins/reporting/server/lib/check_license.ts index b25021c2ed09b..80cf315539441 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/check_license.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/check_license.ts @@ -47,8 +47,8 @@ const makeManagementFeature = ( } const validJobTypes = exportTypes - .filter(exportType => license.isOneOf(exportType.validLicenses)) - .map(exportType => exportType.jobType); + .filter((exportType) => license.isOneOf(exportType.validLicenses)) + .map((exportType) => exportType.jobType); return { showLinks: validJobTypes.length > 0, diff --git a/x-pack/legacy/plugins/reporting/server/lib/create_tagged_logger.ts b/x-pack/legacy/plugins/reporting/server/lib/create_tagged_logger.ts index aaed46e629ccc..775930ec83bdf 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/create_tagged_logger.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/create_tagged_logger.ts @@ -11,13 +11,13 @@ export function createTaggedLogger(logger: LevelLogger, tags: string[]) { const allTags = [...tags, ...additionalTags]; if (allTags.includes('info')) { - const newTags = allTags.filter(t => t !== 'info'); // Ensure 'info' is not included twice + const newTags = allTags.filter((t) => t !== 'info'); // Ensure 'info' is not included twice logger.info(msg, newTags); } else if (allTags.includes('debug')) { - const newTags = allTags.filter(t => t !== 'debug'); + const newTags = allTags.filter((t) => t !== 'debug'); logger.debug(msg, newTags); } else if (allTags.includes('warn') || allTags.includes('warning')) { - const newTags = allTags.filter(t => t !== 'warn' && t !== 'warning'); + const newTags = allTags.filter((t) => t !== 'warn' && t !== 'warning'); logger.warn(msg, newTags); } else { logger.error(msg, allTags); diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/create_index.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/create_index.js index 2944574534a82..691bd4f618a1c 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/create_index.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/create_index.js @@ -10,29 +10,29 @@ import { createIndex } from '../../helpers/create_index'; import { ClientMock } from '../fixtures/legacy_elasticsearch'; import { constants } from '../../constants'; -describe('Create Index', function() { - describe('Does not exist', function() { +describe('Create Index', function () { + describe('Does not exist', function () { let client; let createSpy; - beforeEach(function() { + beforeEach(function () { client = new ClientMock(); createSpy = sinon.spy(client, 'callAsInternalUser').withArgs('indices.create'); }); - it('should return true', function() { + it('should return true', function () { const indexName = 'test-index'; const result = createIndex(client, indexName); - return result.then(exists => expect(exists).to.be(true)); + return result.then((exists) => expect(exists).to.be(true)); }); - it('should create the index with mappings and default settings', function() { + it('should create the index with mappings and default settings', function () { const indexName = 'test-index'; const settings = constants.DEFAULT_SETTING_INDEX_SETTINGS; const result = createIndex(client, indexName); - return result.then(function() { + return result.then(function () { const payload = createSpy.getCall(0).args[1]; sinon.assert.callCount(createSpy, 1); expect(payload).to.have.property('index', indexName); @@ -44,7 +44,7 @@ describe('Create Index', function() { }); }); - it('should create the index with custom settings', function() { + it('should create the index with custom settings', function () { const indexName = 'test-index'; const settings = { ...constants.DEFAULT_SETTING_INDEX_SETTINGS, @@ -55,7 +55,7 @@ describe('Create Index', function() { }; const result = createIndex(client, indexName, settings); - return result.then(function() { + return result.then(function () { const payload = createSpy.getCall(0).args[1]; sinon.assert.callCount(createSpy, 1); expect(payload).to.have.property('index', indexName); @@ -68,11 +68,11 @@ describe('Create Index', function() { }); }); - describe('Does exist', function() { + describe('Does exist', function () { let client; let createSpy; - beforeEach(function() { + beforeEach(function () { client = new ClientMock(); sinon .stub(client, 'callAsInternalUser') @@ -81,18 +81,18 @@ describe('Create Index', function() { createSpy = client.callAsInternalUser.withArgs('indices.create'); }); - it('should return true', function() { + it('should return true', function () { const indexName = 'test-index'; const result = createIndex(client, indexName); - return result.then(exists => expect(exists).to.be(true)); + return result.then((exists) => expect(exists).to.be(true)); }); - it('should not create the index', function() { + it('should not create the index', function () { const indexName = 'test-index'; const result = createIndex(client, indexName); - return result.then(function() { + return result.then(function () { sinon.assert.callCount(createSpy, 0); }); }); diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/errors.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/errors.js index a59355bd426d0..d41b29106bb9d 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/errors.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/errors.js @@ -7,49 +7,49 @@ import expect from '@kbn/expect'; import { WorkerTimeoutError, UnspecifiedWorkerError } from '../../helpers/errors'; -describe('custom errors', function() { - describe('WorkerTimeoutError', function() { +describe('custom errors', function () { + describe('WorkerTimeoutError', function () { it('should be function', () => { expect(WorkerTimeoutError).to.be.a('function'); }); - it('should have a name', function() { + it('should have a name', function () { const err = new WorkerTimeoutError('timeout error'); expect(err).to.have.property('name', 'WorkerTimeoutError'); }); - it('should take a jobId property', function() { + it('should take a jobId property', function () { const err = new WorkerTimeoutError('timeout error', { jobId: 'il7hl34rqlo8ro' }); expect(err).to.have.property('jobId', 'il7hl34rqlo8ro'); }); - it('should take a timeout property', function() { + it('should take a timeout property', function () { const err = new WorkerTimeoutError('timeout error', { timeout: 15000 }); expect(err).to.have.property('timeout', 15000); }); - it('should be stringifyable', function() { + it('should be stringifyable', function () { const err = new WorkerTimeoutError('timeout error'); expect(`${err}`).to.equal('WorkerTimeoutError: timeout error'); }); }); - describe('UnspecifiedWorkerError', function() { + describe('UnspecifiedWorkerError', function () { it('should be function', () => { expect(UnspecifiedWorkerError).to.be.a('function'); }); - it('should have a name', function() { + it('should have a name', function () { const err = new UnspecifiedWorkerError('unspecified error'); expect(err).to.have.property('name', 'UnspecifiedWorkerError'); }); - it('should take a jobId property', function() { + it('should take a jobId property', function () { const err = new UnspecifiedWorkerError('unspecified error', { jobId: 'il7hl34rqlo8ro' }); expect(err).to.have.property('jobId', 'il7hl34rqlo8ro'); }); - it('should be stringifyable', function() { + it('should be stringifyable', function () { const err = new UnspecifiedWorkerError('unspecified error'); expect(`${err}`).to.equal('UnspecifiedWorkerError: unspecified error'); }); diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/index_timestamp.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/index_timestamp.js index 33605dce66b28..71dc8a363e429 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/index_timestamp.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/helpers/index_timestamp.js @@ -12,78 +12,78 @@ import { indexTimestamp } from '../../helpers/index_timestamp'; const anchor = '2016-04-02T01:02:03.456'; // saturday -describe('Index timestamp interval', function() { - describe('construction', function() { - it('should throw given an invalid interval', function() { +describe('Index timestamp interval', function () { + describe('construction', function () { + it('should throw given an invalid interval', function () { const init = () => indexTimestamp('bananas'); expect(init).to.throwException(/invalid.+interval/i); }); }); - describe('timestamps', function() { + describe('timestamps', function () { let clock; let separator; - beforeEach(function() { + beforeEach(function () { separator = constants.DEFAULT_SETTING_DATE_SEPARATOR; clock = sinon.useFakeTimers(moment(anchor).valueOf()); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - describe('formats', function() { - it('should return the year', function() { + describe('formats', function () { + it('should return the year', function () { const timestamp = indexTimestamp('year'); const str = `2016`; expect(timestamp).to.equal(str); }); - it('should return the year and month', function() { + it('should return the year and month', function () { const timestamp = indexTimestamp('month'); const str = `2016${separator}04`; expect(timestamp).to.equal(str); }); - it('should return the year, month, and first day of the week', function() { + it('should return the year, month, and first day of the week', function () { const timestamp = indexTimestamp('week'); const str = `2016${separator}03${separator}27`; expect(timestamp).to.equal(str); }); - it('should return the year, month, and day of the week', function() { + it('should return the year, month, and day of the week', function () { const timestamp = indexTimestamp('day'); const str = `2016${separator}04${separator}02`; expect(timestamp).to.equal(str); }); - it('should return the year, month, day and hour', function() { + it('should return the year, month, day and hour', function () { const timestamp = indexTimestamp('hour'); const str = `2016${separator}04${separator}02${separator}01`; expect(timestamp).to.equal(str); }); - it('should return the year, month, day, hour and minute', function() { + it('should return the year, month, day, hour and minute', function () { const timestamp = indexTimestamp('minute'); const str = `2016${separator}04${separator}02${separator}01${separator}02`; expect(timestamp).to.equal(str); }); }); - describe('date separator', function() { - it('should be customizable', function() { + describe('date separator', function () { + it('should be customizable', function () { const separators = ['-', '.', '_']; - separators.forEach(customSep => { + separators.forEach((customSep) => { const str = `2016${customSep}04${customSep}02${customSep}01${customSep}02`; const timestamp = indexTimestamp('minute', customSep); expect(timestamp).to.equal(str); }); }); - it('should throw if a letter is used', function() { + it('should throw if a letter is used', function () { const separators = ['a', 'B', 'YYYY']; - separators.forEach(customSep => { + separators.forEach((customSep) => { const fn = () => indexTimestamp('minute', customSep); expect(fn).to.throwException(); }); diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/index.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/index.js index 428c0f0bc0736..7cdae152ad0d7 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/index.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/index.js @@ -19,53 +19,53 @@ const { Esqueue } = proxyquire.noPreserveCache()('../index', { './worker': { Worker: WorkerMock }, }); -describe('Esqueue class', function() { +describe('Esqueue class', function () { let client; - beforeEach(function() { + beforeEach(function () { client = new ClientMock(); }); - it('should be an event emitter', function() { + it('should be an event emitter', function () { const queue = new Esqueue('esqueue', { client }); expect(queue).to.be.an(events.EventEmitter); }); - describe('Option validation', function() { - it('should throw without an index', function() { + describe('Option validation', function () { + it('should throw without an index', function () { const init = () => new Esqueue(); expect(init).to.throwException(/must.+specify.+index/i); }); }); - describe('Queue construction', function() { - it('should ping the ES server', function() { + describe('Queue construction', function () { + it('should ping the ES server', function () { const pingSpy = sinon.spy(client, 'callAsInternalUser').withArgs('ping'); new Esqueue('esqueue', { client }); sinon.assert.calledOnce(pingSpy); }); }); - describe('Adding jobs', function() { + describe('Adding jobs', function () { let indexName; let jobType; let payload; let queue; - beforeEach(function() { + beforeEach(function () { indexName = 'esqueue-index'; jobType = 'test-test'; payload = { payload: true }; queue = new Esqueue(indexName, { client }); }); - it('should throw with invalid dateSeparator setting', function() { + it('should throw with invalid dateSeparator setting', function () { queue = new Esqueue(indexName, { client, dateSeparator: 'a' }); const fn = () => queue.addJob(jobType, payload); expect(fn).to.throwException(); }); - it('should pass queue instance, index name, type and payload', function() { + it('should pass queue instance, index name, type and payload', function () { const job = queue.addJob(jobType, payload); expect(job.getProp('queue')).to.equal(queue); expect(job.getProp('index')).to.match(new RegExp(indexName)); @@ -73,13 +73,13 @@ describe('Esqueue class', function() { expect(job.getProp('payload')).to.equal(payload); }); - it('should pass default settings', function() { + it('should pass default settings', function () { const job = queue.addJob(jobType, payload); const options = job.getProp('options'); expect(options).to.have.property('timeout', constants.DEFAULT_SETTING_TIMEOUT); }); - it('should pass queue index settings', function() { + it('should pass queue index settings', function () { const indexSettings = { index: { number_of_shards: 1, @@ -91,7 +91,7 @@ describe('Esqueue class', function() { expect(job.getProp('options')).to.have.property('indexSettings', indexSettings); }); - it('should pass headers from options', function() { + it('should pass headers from options', function () { const options = { headers: { authorization: 'Basic cXdlcnR5', @@ -102,14 +102,14 @@ describe('Esqueue class', function() { }); }); - describe('Registering workers', function() { + describe('Registering workers', function () { let queue; - beforeEach(function() { + beforeEach(function () { queue = new Esqueue('esqueue', { client }); }); - it('should keep track of workers', function() { + it('should keep track of workers', function () { expect(queue.getWorkers()).to.eql([]); expect(queue.getWorkers()).to.have.length(0); @@ -119,7 +119,7 @@ describe('Esqueue class', function() { expect(queue.getWorkers()).to.have.length(3); }); - it('should pass instance of queue, type, and worker function', function() { + it('should pass instance of queue, type, and worker function', function () { const workerType = 'test-worker'; const workerFn = () => true; @@ -129,7 +129,7 @@ describe('Esqueue class', function() { expect(worker.getProp('workerFn')).to.equal(workerFn); }); - it('should pass worker options', function() { + it('should pass worker options', function () { const workerOptions = { size: 12, }; @@ -141,17 +141,17 @@ describe('Esqueue class', function() { }); }); - describe('Destroy', function() { - it('should destroy workers', function() { + describe('Destroy', function () { + it('should destroy workers', function () { const queue = new Esqueue('esqueue', { client }); const stubs = times(3, () => { return { destroy: sinon.stub() }; }); - stubs.forEach(stub => queue._workers.push(stub)); + stubs.forEach((stub) => queue._workers.push(stub)); expect(queue.getWorkers()).to.have.length(3); queue.destroy(); - stubs.forEach(stub => sinon.assert.calledOnce(stub.destroy)); + stubs.forEach((stub) => sinon.assert.calledOnce(stub.destroy)); expect(queue.getWorkers()).to.have.length(0); }); }); diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/job.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/job.js index c7812ec151b00..955eed8d65722 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/job.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/job.js @@ -28,7 +28,7 @@ function validateDoc(spy) { return spyCall.args[1]; } -describe('Job Class', function() { +describe('Job Class', function () { let mockQueue; let client; let index; @@ -37,7 +37,7 @@ describe('Job Class', function() { let payload; let options; - beforeEach(function() { + beforeEach(function () { createIndexMock.resetHistory(); createIndexMock.returns(Promise.resolve('mock')); index = 'test'; @@ -47,42 +47,42 @@ describe('Job Class', function() { mockQueue.setClient(client); }); - it('should be an event emitter', function() { + it('should be an event emitter', function () { const job = new Job(mockQueue, index, 'test', {}); expect(job).to.be.an(events.EventEmitter); }); - describe('invalid construction', function() { - it('should throw with a missing type', function() { + describe('invalid construction', function () { + it('should throw with a missing type', function () { const init = () => new Job(mockQueue, index); expect(init).to.throwException(/type.+string/i); }); - it('should throw with an invalid type', function() { + it('should throw with an invalid type', function () { const init = () => new Job(mockQueue, index, { 'not a string': true }); expect(init).to.throwException(/type.+string/i); }); - it('should throw with an invalid payload', function() { + it('should throw with an invalid payload', function () { const init = () => new Job(mockQueue, index, 'type1', [1, 2, 3]); expect(init).to.throwException(/plain.+object/i); }); - it(`should throw error if invalid maxAttempts`, function() { + it(`should throw error if invalid maxAttempts`, function () { const init = () => new Job(mockQueue, index, 'type1', { id: '123' }, { max_attempts: -1 }); expect(init).to.throwException(/invalid.+max_attempts/i); }); }); - describe('construction', function() { + describe('construction', function () { let indexSpy; - beforeEach(function() { + beforeEach(function () { type = 'type1'; payload = { id: '123' }; indexSpy = sinon.spy(client, 'callAsInternalUser').withArgs('index'); }); - it('should create the target index', function() { + it('should create the target index', function () { const job = new Job(mockQueue, index, type, payload, options); return job.ready.then(() => { sinon.assert.calledOnce(createIndexMock); @@ -92,7 +92,7 @@ describe('Job Class', function() { }); }); - it('should index the payload', function() { + it('should index the payload', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -102,7 +102,7 @@ describe('Job Class', function() { }); }); - it('should index the job type', function() { + it('should index the job type', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -112,7 +112,7 @@ describe('Job Class', function() { }); }); - it('should set event creation time', function() { + it('should set event creation time', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -120,7 +120,7 @@ describe('Job Class', function() { }); }); - it('should refresh the index', function() { + it('should refresh the index', function () { const refreshSpy = client.callAsInternalUser.withArgs('indices.refresh'); const job = new Job(mockQueue, index, type, payload); @@ -131,9 +131,9 @@ describe('Job Class', function() { }); }); - it('should emit the job information on success', function(done) { + it('should emit the job information on success', function (done) { const job = new Job(mockQueue, index, type, payload); - job.once(constants.EVENT_JOB_CREATED, jobDoc => { + job.once(constants.EVENT_JOB_CREATED, (jobDoc) => { try { expect(jobDoc).to.have.property('id'); expect(jobDoc).to.have.property('index'); @@ -146,13 +146,13 @@ describe('Job Class', function() { }); }); - it('should emit error on index creation failure', function(done) { + it('should emit error on index creation failure', function (done) { const errMsg = 'test index creation failure'; createIndexMock.returns(Promise.reject(new Error(errMsg))); const job = new Job(mockQueue, index, type, payload); - job.once(constants.EVENT_JOB_CREATE_ERROR, err => { + job.once(constants.EVENT_JOB_CREATE_ERROR, (err) => { try { expect(err.message).to.equal(errMsg); done(); @@ -162,7 +162,7 @@ describe('Job Class', function() { }); }); - it('should emit error on client index failure', function(done) { + it('should emit error on client index failure', function (done) { const errMsg = 'test document index failure'; client.callAsInternalUser.restore(); @@ -172,7 +172,7 @@ describe('Job Class', function() { .callsFake(() => Promise.reject(new Error(errMsg))); const job = new Job(mockQueue, index, type, payload); - job.once(constants.EVENT_JOB_CREATE_ERROR, err => { + job.once(constants.EVENT_JOB_CREATE_ERROR, (err) => { try { expect(err.message).to.equal(errMsg); done(); @@ -183,8 +183,8 @@ describe('Job Class', function() { }); }); - describe('event emitting', function() { - it('should trigger events on the queue instance', function(done) { + describe('event emitting', function () { + it('should trigger events on the queue instance', function (done) { const eventName = 'test event'; const payload1 = { test: true, @@ -210,15 +210,15 @@ describe('Job Class', function() { }); }); - describe('default values', function() { + describe('default values', function () { let indexSpy; - beforeEach(function() { + beforeEach(function () { type = 'type1'; payload = { id: '123' }; indexSpy = sinon.spy(client, 'callAsInternalUser').withArgs('index'); }); - it('should set attempt count to 0', function() { + it('should set attempt count to 0', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -226,7 +226,7 @@ describe('Job Class', function() { }); }); - it('should index default created_by value', function() { + it('should index default created_by value', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -234,7 +234,7 @@ describe('Job Class', function() { }); }); - it('should set an expired process_expiration time', function() { + it('should set an expired process_expiration time', function () { const now = new Date().getTime(); const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { @@ -244,7 +244,7 @@ describe('Job Class', function() { }); }); - it('should set status as pending', function() { + it('should set status as pending', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -252,7 +252,7 @@ describe('Job Class', function() { }); }); - it('should have a default priority of 10', function() { + it('should have a default priority of 10', function () { const job = new Job(mockQueue, index, type, payload, options); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -260,7 +260,7 @@ describe('Job Class', function() { }); }); - it('should set a browser type', function() { + it('should set a browser type', function () { const job = new Job(mockQueue, index, type, payload); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -269,9 +269,9 @@ describe('Job Class', function() { }); }); - describe('option passing', function() { + describe('option passing', function () { let indexSpy; - beforeEach(function() { + beforeEach(function () { type = 'type1'; payload = { id: '123' }; options = { @@ -284,7 +284,7 @@ describe('Job Class', function() { indexSpy = sinon.spy(client, 'callAsInternalUser').withArgs('index'); }); - it('should index the created_by value', function() { + it('should index the created_by value', function () { const createdBy = 'user_identifier'; const job = new Job(mockQueue, index, type, payload, { created_by: createdBy, @@ -296,7 +296,7 @@ describe('Job Class', function() { }); }); - it('should index timeout value from options', function() { + it('should index timeout value from options', function () { const job = new Job(mockQueue, index, type, payload, options); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -304,7 +304,7 @@ describe('Job Class', function() { }); }); - it('should set max attempt count', function() { + it('should set max attempt count', function () { const job = new Job(mockQueue, index, type, payload, options); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -312,7 +312,7 @@ describe('Job Class', function() { }); }); - it('should add headers to the request params', function() { + it('should add headers to the request params', function () { const job = new Job(mockQueue, index, type, payload, options); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -320,7 +320,7 @@ describe('Job Class', function() { }); }); - it(`should use upper priority of ${maxPriority}`, function() { + it(`should use upper priority of ${maxPriority}`, function () { const job = new Job(mockQueue, index, type, payload, { priority: maxPriority * 2 }); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -328,7 +328,7 @@ describe('Job Class', function() { }); }); - it(`should use lower priority of ${minPriority}`, function() { + it(`should use lower priority of ${minPriority}`, function () { const job = new Job(mockQueue, index, type, payload, { priority: minPriority * 2 }); return job.ready.then(() => { const indexArgs = validateDoc(indexSpy); @@ -337,16 +337,16 @@ describe('Job Class', function() { }); }); - describe('get method', function() { - beforeEach(function() { + describe('get method', function () { + beforeEach(function () { type = 'type2'; payload = { id: '123' }; }); - it('should return the job document', function() { + it('should return the job document', function () { const job = new Job(mockQueue, index, type, payload); - return job.get().then(doc => { + return job.get().then((doc) => { const jobDoc = job.document; // document should be resolved expect(doc).to.have.property('index', index); expect(doc).to.have.property('id', jobDoc.id); @@ -361,29 +361,26 @@ describe('Job Class', function() { }); }); - it('should contain optional data', function() { + it('should contain optional data', function () { const optionals = { created_by: 'some_ident', }; const job = new Job(mockQueue, index, type, payload, optionals); return Promise.resolve(client.callAsInternalUser('get', {}, optionals)) - .then(doc => { - sinon - .stub(client, 'callAsInternalUser') - .withArgs('get') - .returns(Promise.resolve(doc)); + .then((doc) => { + sinon.stub(client, 'callAsInternalUser').withArgs('get').returns(Promise.resolve(doc)); }) .then(() => { - return job.get().then(doc => { + return job.get().then((doc) => { expect(doc).to.have.property('created_by', optionals.created_by); }); }); }); }); - describe('toJSON method', function() { - beforeEach(function() { + describe('toJSON method', function () { + beforeEach(function () { type = 'type2'; payload = { id: '123' }; options = { @@ -393,7 +390,7 @@ describe('Job Class', function() { }; }); - it('should return the static information about the job', function() { + it('should return the static information about the job', function () { const job = new Job(mockQueue, index, type, payload, options); // toJSON is sync, should work before doc is written to elasticsearch @@ -410,7 +407,7 @@ describe('Job Class', function() { expect(doc).to.not.have.property('version'); }); - it('should contain optional data', function() { + it('should contain optional data', function () { const optionals = { created_by: 'some_ident', }; diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/worker.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/worker.js index ea80a652bb506..b31a39a6f90cc 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/worker.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/__tests__/worker.js @@ -26,7 +26,7 @@ const defaultWorkerOptions = { intervalErrorMultiplier: 10, }; -describe('Worker class', function() { +describe('Worker class', function () { // some of these tests might be a little slow, give them a little extra time this.timeout(10000); @@ -40,65 +40,65 @@ describe('Worker class', function() { // Allowing the Poller to poll requires intimate knowledge of the inner workings of the Poller. // We have to ensure that the Promises internal to the `_poll` method are resolved to queue up // the next setTimeout before incrementing the clock. - const allowPoll = async interval => { + const allowPoll = async (interval) => { clock.tick(interval); await Promise.resolve(); await Promise.resolve(); }; - beforeEach(function() { + beforeEach(function () { client = new ClientMock(); mockQueue = new QueueMock(); mockQueue.setClient(client); }); - afterEach(function() { - [worker, worker2].forEach(actualWorker => { + afterEach(function () { + [worker, worker2].forEach((actualWorker) => { if (actualWorker) { actualWorker.destroy(); } }); }); - describe('invalid construction', function() { - it('should throw without a type', function() { + describe('invalid construction', function () { + it('should throw without a type', function () { const init = () => new Worker(mockQueue); expect(init).to.throwException(/type.+string/i); }); - it('should throw without an invalid type', function() { + it('should throw without an invalid type', function () { const init = () => new Worker(mockQueue, { string: false }); expect(init).to.throwException(/type.+string/i); }); - it('should throw without a workerFn', function() { + it('should throw without a workerFn', function () { const init = () => new Worker(mockQueue, 'test'); expect(init).to.throwException(/workerFn.+function/i); }); - it('should throw with an invalid workerFn', function() { + it('should throw with an invalid workerFn', function () { const init = () => new Worker(mockQueue, 'test', { function: false }); expect(init).to.throwException(/workerFn.+function/i); }); - it('should throw without an opts', function() { + it('should throw without an opts', function () { const init = () => new Worker(mockQueue, 'test', noop); expect(init).to.throwException(/opts.+object/i); }); - it('should throw with an invalid opts.interval', function() { + it('should throw with an invalid opts.interval', function () { const init = () => new Worker(mockQueue, 'test', noop, {}); expect(init).to.throwException(/opts\.interval.+number/i); }); - it('should throw with an invalid opts.intervalErrorMultiplier', function() { + it('should throw with an invalid opts.intervalErrorMultiplier', function () { const init = () => new Worker(mockQueue, 'test', noop, { interval: 1 }); expect(init).to.throwException(/opts\.intervalErrorMultiplier.+number/i); }); }); - describe('construction', function() { - it('should assign internal properties', function() { + describe('construction', function () { + it('should assign internal properties', function () { const jobtype = 'testjob'; const workerFn = noop; worker = new Worker(mockQueue, jobtype, workerFn, defaultWorkerOptions); @@ -108,7 +108,7 @@ describe('Worker class', function() { expect(worker).to.have.property('workerFn', workerFn); }); - it('should have a unique ID', function() { + it('should have a unique ID', function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); expect(worker.id).to.be.a('string'); @@ -119,12 +119,12 @@ describe('Worker class', function() { }); }); - describe('event emitting', function() { - beforeEach(function() { + describe('event emitting', function () { + beforeEach(function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); }); - it('should trigger events on the queue instance', function(done) { + it('should trigger events on the queue instance', function (done) { const eventName = 'test event'; const payload1 = { test: true, @@ -148,24 +148,24 @@ describe('Worker class', function() { }); }); - describe('output formatting', function() { + describe('output formatting', function () { let f; - beforeEach(function() { + beforeEach(function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); - f = output => worker._formatOutput(output); + f = (output) => worker._formatOutput(output); }); - it('should handle primitives', function() { + it('should handle primitives', function () { const primitives = ['test', true, 1234, { one: 1 }, [5, 6, 7, 8]]; - primitives.forEach(val => { + primitives.forEach((val) => { expect(f(val)).to.have.property('content_type', defaults.unknownMime); expect(f(val)).to.have.property('content', val); }); }); - it('should accept content object without type', function() { + it('should accept content object without type', function () { const output = { content: 'test output', }; @@ -174,7 +174,7 @@ describe('Worker class', function() { expect(f(output)).to.have.property('content', output.content); }); - it('should accept a content type', function() { + it('should accept a content type', function () { const output = { content_type: 'test type', content: 'test output', @@ -184,13 +184,13 @@ describe('Worker class', function() { expect(f(output)).to.have.property('content', output.content); }); - it('should work with no input', function() { + it('should work with no input', function () { expect(f()).to.have.property('content_type', defaults.unknownMime); expect(f()).to.have.property('content', defaults.contentBody); }); }); - describe('polling for jobs', function() { + describe('polling for jobs', function () { beforeEach(() => { anchorMoment = moment(anchor); clock = sinon.useFakeTimers(anchorMoment.valueOf()); @@ -200,7 +200,7 @@ describe('Worker class', function() { clock.restore(); }); - it('should start polling for jobs after interval', async function() { + it('should start polling for jobs after interval', async function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); const processPendingJobsStub = sinon .stub(worker, '_processPendingJobs') @@ -210,7 +210,7 @@ describe('Worker class', function() { sinon.assert.calledOnce(processPendingJobsStub); }); - it('should use interval option to control polling', async function() { + it('should use interval option to control polling', async function () { const interval = 567; worker = new Worker(mockQueue, 'test', noop, { ...defaultWorkerOptions, interval }); const processPendingJobsStub = sinon @@ -222,7 +222,7 @@ describe('Worker class', function() { sinon.assert.calledOnce(processPendingJobsStub); }); - it('should not poll once destroyed', async function() { + it('should not poll once destroyed', async function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); const processPendingJobsStub = sinon @@ -247,7 +247,7 @@ describe('Worker class', function() { sinon.assert.calledTwice(processPendingJobsStub); }); - it('should use error multiplier when processPendingJobs rejects the Promise', async function() { + it('should use error multiplier when processPendingJobs rejects the Promise', async function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); const processPendingJobsStub = sinon @@ -262,7 +262,7 @@ describe('Worker class', function() { expect(processPendingJobsStub.callCount).to.be(2); }); - it('should not use error multiplier when processPendingJobs resolved the Promise', async function() { + it('should not use error multiplier when processPendingJobs resolved the Promise', async function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); const processPendingJobsStub = sinon @@ -276,7 +276,7 @@ describe('Worker class', function() { }); }); - describe('query for pending jobs', function() { + describe('query for pending jobs', function () { let searchStub; function getSearchParams(jobtype = 'test', params = {}) { @@ -285,8 +285,8 @@ describe('Worker class', function() { return searchStub.firstCall.args[1]; } - describe('error handling', function() { - it('should pass search errors', function(done) { + describe('error handling', function () { + it('should pass search errors', function (done) { searchStub = sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('search') @@ -300,8 +300,8 @@ describe('Worker class', function() { }); }); - describe('missing index', function() { - it('should swallow error', function(done) { + describe('missing index', function () { + it('should swallow error', function (done) { searchStub = sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('search') @@ -315,7 +315,7 @@ describe('Worker class', function() { .catch(() => done(new Error('should not reject'))); }); - it('should return an empty array', function(done) { + it('should return an empty array', function (done) { searchStub = sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('search') @@ -323,7 +323,7 @@ describe('Worker class', function() { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); worker ._getPendingJobs() - .then(res => { + .then((res) => { try { expect(res).to.be.an(Array); expect(res).to.have.length(0); @@ -337,7 +337,7 @@ describe('Worker class', function() { }); }); - describe('query body', function() { + describe('query body', function () { const conditionPath = 'query.bool.filter.bool'; const jobtype = 'test_jobtype'; @@ -354,19 +354,19 @@ describe('Worker class', function() { clock.restore(); }); - it('should query with seq_no_primary_term', function() { + it('should query with seq_no_primary_term', function () { const { body } = getSearchParams(jobtype); expect(body).to.have.property('seq_no_primary_term', true); }); - it('should filter unwanted source data', function() { + it('should filter unwanted source data', function () { const excludedFields = ['output.content']; const { body } = getSearchParams(jobtype); expect(body).to.have.property('_source'); expect(body._source).to.eql({ excludes: excludedFields }); }); - it('should search for pending or expired jobs', function() { + it('should search for pending or expired jobs', function () { const { body } = getSearchParams(jobtype); const conditions = get(body, conditionPath); expect(conditions).to.have.property('should'); @@ -390,25 +390,25 @@ describe('Worker class', function() { expect(expiredMatch).to.not.be(undefined); }); - it('specify that there should be at least one match', function() { + it('specify that there should be at least one match', function () { const { body } = getSearchParams(jobtype); const conditions = get(body, conditionPath); expect(conditions).to.have.property('minimum_should_match', 1); }); - it('should use default size', function() { + it('should use default size', function () { const { body } = getSearchParams(jobtype); expect(body).to.have.property('size', defaults.size); }); }); }); - describe('claiming a job', function() { + describe('claiming a job', function () { let params; let job; let updateSpy; - beforeEach(function() { + beforeEach(function () { anchorMoment = moment(anchor); clock = sinon.useFakeTimers(anchorMoment.valueOf()); @@ -417,7 +417,7 @@ describe('Worker class', function() { type: 'test', id: 12345, }; - return mockQueue.client.callAsInternalUser('get', params).then(jobDoc => { + return mockQueue.client.callAsInternalUser('get', params).then((jobDoc) => { job = jobDoc; worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); updateSpy = sinon.spy(mockQueue.client, 'callAsInternalUser').withArgs('update'); @@ -428,7 +428,7 @@ describe('Worker class', function() { clock.restore(); }); - it('should use seqNo and primaryTerm on update', function() { + it('should use seqNo and primaryTerm on update', function () { worker._claimJob(job); const query = updateSpy.firstCall.args[1]; expect(query).to.have.property('index', job._index); @@ -437,33 +437,33 @@ describe('Worker class', function() { expect(query).to.have.property('if_primary_term', job._primary_term); }); - it('should increment the job attempts', function() { + it('should increment the job attempts', function () { worker._claimJob(job); const doc = updateSpy.firstCall.args[1].body.doc; expect(doc).to.have.property('attempts', job._source.attempts + 1); }); - it('should update the job status', function() { + it('should update the job status', function () { worker._claimJob(job); const doc = updateSpy.firstCall.args[1].body.doc; expect(doc).to.have.property('status', constants.JOB_STATUS_PROCESSING); }); - it('should set job expiration time', function() { + it('should set job expiration time', function () { worker._claimJob(job); const doc = updateSpy.firstCall.args[1].body.doc; const expiration = anchorMoment.add(defaults.timeout).toISOString(); expect(doc).to.have.property('process_expiration', expiration); }); - it('should fail job if max_attempts are hit', function() { + it('should fail job if max_attempts are hit', function () { const failSpy = sinon.spy(worker, '_failJob'); job._source.attempts = job._source.max_attempts; worker._claimJob(job); sinon.assert.calledOnce(failSpy); }); - it('should append error message if no existing content', function() { + it('should append error message if no existing content', function () { const failSpy = sinon.spy(worker, '_failJob'); job._source.attempts = job._source.max_attempts; expect(job._source.output).to.be(undefined); @@ -473,7 +473,7 @@ describe('Worker class', function() { expect(msg).to.contain(job._source.max_attempts); }); - it('should not append message if existing output', function() { + it('should not append message if existing output', function () { const failSpy = sinon.spy(worker, '_failJob'); job._source.attempts = job._source.max_attempts; job._source.output = 'i have some output'; @@ -482,30 +482,30 @@ describe('Worker class', function() { expect(msg).to.equal(false); }); - it('should reject the promise on conflict errors', function() { + it('should reject the promise on conflict errors', function () { mockQueue.client.callAsInternalUser.restore(); sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .returns(Promise.reject({ statusCode: 409 })); - return worker._claimJob(job).catch(err => { + return worker._claimJob(job).catch((err) => { expect(err).to.eql({ statusCode: 409 }); }); }); - it('should reject the promise on other errors', function() { + it('should reject the promise on other errors', function () { mockQueue.client.callAsInternalUser.restore(); sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .returns(Promise.reject({ statusCode: 401 })); - return worker._claimJob(job).catch(err => { + return worker._claimJob(job).catch((err) => { expect(err).to.eql({ statusCode: 401 }); }); }); }); - describe('find a pending job to claim', function() { + describe('find a pending job to claim', function () { const getMockJobs = (status = 'pending') => [ { _index: 'myIndex', @@ -527,7 +527,7 @@ describe('Worker class', function() { }, ]; - beforeEach(function() { + beforeEach(function () { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); }); @@ -535,13 +535,13 @@ describe('Worker class', function() { mockQueue.client.callAsInternalUser.restore(); }); - it('should emit for errors from claiming job', function(done) { + it('should emit for errors from claiming job', function (done) { sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .rejects({ statusCode: 401 }); - worker.once(constants.EVENT_WORKER_JOB_CLAIM_ERROR, function(err) { + worker.once(constants.EVENT_WORKER_JOB_CLAIM_ERROR, function (err) { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -556,23 +556,23 @@ describe('Worker class', function() { worker._claimPendingJobs(getMockJobs()).catch(() => {}); }); - it('should reject the promise if an error claiming the job', function() { + it('should reject the promise if an error claiming the job', function () { sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .rejects({ statusCode: 409 }); - return worker._claimPendingJobs(getMockJobs()).catch(err => { + return worker._claimPendingJobs(getMockJobs()).catch((err) => { expect(err).to.eql({ statusCode: 409 }); }); }); - it('should get the pending job', function() { + it('should get the pending job', function () { sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .resolves({ test: 'cool' }); sinon.stub(worker, '_performJob').callsFake(identity); - return worker._claimPendingJobs(getMockJobs()).then(claimedJob => { + return worker._claimPendingJobs(getMockJobs()).then((claimedJob) => { expect(claimedJob._index).to.be('myIndex'); expect(claimedJob._source.jobtype).to.be('jobtype'); expect(claimedJob._source.status).to.be('processing'); @@ -582,15 +582,15 @@ describe('Worker class', function() { }); }); - describe('failing a job', function() { + describe('failing a job', function () { let job; let updateSpy; - beforeEach(function() { + beforeEach(function () { anchorMoment = moment(anchor); clock = sinon.useFakeTimers(anchorMoment.valueOf()); - return mockQueue.client.callAsInternalUser('get').then(jobDoc => { + return mockQueue.client.callAsInternalUser('get').then((jobDoc) => { job = jobDoc; worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); updateSpy = sinon.spy(mockQueue.client, 'callAsInternalUser').withArgs('update'); @@ -601,7 +601,7 @@ describe('Worker class', function() { clock.restore(); }); - it('should use _seq_no and _primary_term on update', function() { + it('should use _seq_no and _primary_term on update', function () { worker._failJob(job); const query = updateSpy.firstCall.args[1]; expect(query).to.have.property('index', job._index); @@ -610,13 +610,13 @@ describe('Worker class', function() { expect(query).to.have.property('if_primary_term', job._primary_term); }); - it('should set status to failed', function() { + it('should set status to failed', function () { worker._failJob(job); const doc = updateSpy.firstCall.args[1].body.doc; expect(doc).to.have.property('status', constants.JOB_STATUS_FAILED); }); - it('should append error message if supplied', function() { + it('should append error message if supplied', function () { const msg = 'test message'; worker._failJob(job, msg); const doc = updateSpy.firstCall.args[1].body.doc; @@ -624,25 +624,25 @@ describe('Worker class', function() { expect(doc.output).to.have.property('content', msg); }); - it('should return true on conflict errors', function() { + it('should return true on conflict errors', function () { mockQueue.client.callAsInternalUser.restore(); sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .rejects({ statusCode: 409 }); - return worker._failJob(job).then(res => expect(res).to.equal(true)); + return worker._failJob(job).then((res) => expect(res).to.equal(true)); }); - it('should return false on other document update errors', function() { + it('should return false on other document update errors', function () { mockQueue.client.callAsInternalUser.restore(); sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .rejects({ statusCode: 401 }); - return worker._failJob(job).then(res => expect(res).to.equal(false)); + return worker._failJob(job).then((res) => expect(res).to.equal(false)); }); - it('should set completed time and status to failure', function() { + it('should set completed time and status to failure', function () { const startTime = moment().valueOf(); const msg = 'test message'; clock.tick(100); @@ -656,8 +656,8 @@ describe('Worker class', function() { expect(completedTimestamp).to.be.greaterThan(startTime); }); - it('should emit worker failure event', function(done) { - worker.on(constants.EVENT_WORKER_JOB_FAIL, err => { + it('should emit worker failure event', function (done) { + worker.on(constants.EVENT_WORKER_JOB_FAIL, (err) => { try { expect(err).to.have.property('output'); expect(err).to.have.property('job'); @@ -671,14 +671,14 @@ describe('Worker class', function() { return worker._failJob(job); }); - it('should emit on other document update errors', function(done) { + it('should emit on other document update errors', function (done) { mockQueue.client.callAsInternalUser.restore(); sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('update') .rejects({ statusCode: 401 }); - worker.on(constants.EVENT_WORKER_FAIL_UPDATE_ERROR, function(err) { + worker.on(constants.EVENT_WORKER_FAIL_UPDATE_ERROR, function (err) { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -693,25 +693,25 @@ describe('Worker class', function() { }); }); - describe('performing a job', function() { + describe('performing a job', function () { let job; let payload; let updateSpy; - beforeEach(function() { + beforeEach(function () { payload = { value: random(0, 100, true), }; - return mockQueue.client.callAsInternalUser('get', {}, { payload }).then(jobDoc => { + return mockQueue.client.callAsInternalUser('get', {}, { payload }).then((jobDoc) => { job = jobDoc; updateSpy = sinon.spy(mockQueue.client, 'callAsInternalUser').withArgs('update'); }); }); - describe('worker success', function() { - it('should call the workerFn with the payload', function(done) { - const workerFn = function(jobPayload) { + describe('worker success', function () { + it('should call the workerFn with the payload', function (done) { + const workerFn = function (jobPayload) { expect(jobPayload).to.eql(payload); }; worker = new Worker(mockQueue, 'test', workerFn, defaultWorkerOptions); @@ -719,8 +719,8 @@ describe('Worker class', function() { worker._performJob(job).then(() => done()); }); - it('should update the job with the workerFn output', function() { - const workerFn = function(job, jobPayload) { + it('should update the job with the workerFn output', function () { + const workerFn = function (job, jobPayload) { expect(jobPayload).to.eql(payload); return payload; }; @@ -740,11 +740,11 @@ describe('Worker class', function() { }); }); - it('should update the job status and completed time', function() { + it('should update the job status and completed time', function () { const startTime = moment().valueOf(); - const workerFn = function(job, jobPayload) { + const workerFn = function (job, jobPayload) { expect(jobPayload).to.eql(payload); - return new Promise(function(resolve) { + return new Promise(function (resolve) { setTimeout(() => resolve(payload), 10); }); }; @@ -781,10 +781,10 @@ describe('Worker class', function() { }); }); - it('should emit completion event', function(done) { + it('should emit completion event', function (done) { worker = new Worker(mockQueue, 'test', noop, defaultWorkerOptions); - worker.once(constants.EVENT_WORKER_COMPLETE, workerJob => { + worker.once(constants.EVENT_WORKER_COMPLETE, (workerJob) => { try { expect(workerJob).to.not.have.property('_source'); @@ -806,9 +806,9 @@ describe('Worker class', function() { }); }); - describe('worker failure', function() { - it('should append error output to job', function() { - const workerFn = function() { + describe('worker failure', function () { + it('should append error output to job', function () { + const workerFn = function () { throw new Error('test error'); }; worker = new Worker(mockQueue, 'test', workerFn, defaultWorkerOptions); @@ -820,8 +820,8 @@ describe('Worker class', function() { }); }); - it('should handle async errors', function() { - const workerFn = function() { + it('should handle async errors', function () { + const workerFn = function () { return new Promise((resolve, reject) => { reject(new Error('test error')); }); @@ -835,9 +835,9 @@ describe('Worker class', function() { }); }); - it('should handle rejecting with strings', function() { + it('should handle rejecting with strings', function () { const errorMessage = 'this is a string error'; - const workerFn = function() { + const workerFn = function () { return new Promise((resolve, reject) => { reject(errorMessage); }); @@ -851,15 +851,15 @@ describe('Worker class', function() { }); }); - it('should handle empty rejection', function(done) { - const workerFn = function() { + it('should handle empty rejection', function (done) { + const workerFn = function () { return new Promise((resolve, reject) => { reject(); }); }; worker = new Worker(mockQueue, 'test', workerFn, defaultWorkerOptions); - worker.once(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, err => { + worker.once(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, (err) => { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -876,7 +876,7 @@ describe('Worker class', function() { }); }); - describe('job failures', function() { + describe('job failures', function () { function getFailStub(workerWithFailure) { return sinon.stub(workerWithFailure, '_failJob').resolves(); } @@ -896,8 +896,8 @@ describe('Worker class', function() { .withArgs('update') .rejects({ statusCode: 413 }); - const workerFn = function(jobPayload) { - return new Promise(function(resolve) { + const workerFn = function (jobPayload) { + return new Promise(function (resolve) { setTimeout(() => resolve(jobPayload), 10); }); }; @@ -911,8 +911,8 @@ describe('Worker class', function() { }); }); - describe('search failure', function() { - it('causes _processPendingJobs to reject the Promise', function() { + describe('search failure', function () { + it('causes _processPendingJobs to reject the Promise', function () { sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('search') @@ -922,25 +922,25 @@ describe('Worker class', function() { () => { expect().fail('expected rejected Promise'); }, - err => { + (err) => { expect(err).to.be.an(Error); } ); }); }); - describe('timeout', function() { + describe('timeout', function () { let failStub; let job; let cancellationCallback; - beforeEach(function() { + beforeEach(function () { const timeout = 20; - cancellationCallback = function() {}; + cancellationCallback = function () {}; - const workerFn = function(job, payload, cancellationToken) { + const workerFn = function (job, payload, cancellationToken) { cancellationToken.on(cancellationCallback); - return new Promise(function(resolve) { + return new Promise(function (resolve) { setTimeout(() => { resolve(); }, timeout * 2); @@ -958,15 +958,15 @@ describe('Worker class', function() { }; }); - it('should not fail job', function() { + it('should not fail job', function () { // fire of the job worker return worker._performJob(job).then(() => { sinon.assert.notCalled(failStub); }); }); - it('should emit timeout if not completed in time', function(done) { - worker.once(constants.EVENT_WORKER_JOB_TIMEOUT, err => { + it('should emit timeout if not completed in time', function (done) { + worker.once(constants.EVENT_WORKER_JOB_TIMEOUT, (err) => { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -982,7 +982,7 @@ describe('Worker class', function() { worker._performJob(job); }); - it('should call cancellation token callback if not completed in time', function(done) { + it('should call cancellation token callback if not completed in time', function (done) { let called = false; cancellationCallback = () => { @@ -1003,7 +1003,7 @@ describe('Worker class', function() { }); }); - describe('worker failure', function() { + describe('worker failure', function () { let failStub; const timeout = 20; @@ -1015,17 +1015,17 @@ describe('Worker class', function() { }, }; - beforeEach(function() { + beforeEach(function () { sinon .stub(mockQueue.client, 'callAsInternalUser') .withArgs('search') .callsFake(() => Promise.resolve({ hits: { hits: [] } })); }); - describe('workerFn rejects promise', function() { - beforeEach(function() { - const workerFn = function() { - return new Promise(function(resolve, reject) { + describe('workerFn rejects promise', function () { + beforeEach(function () { + const workerFn = function () { + return new Promise(function (resolve, reject) { setTimeout(() => { reject(); }, timeout / 2); @@ -1035,14 +1035,14 @@ describe('Worker class', function() { failStub = getFailStub(worker); }); - it('should fail the job', function() { + it('should fail the job', function () { return worker._performJob(job).then(() => { sinon.assert.calledOnce(failStub); }); }); - it('should emit worker execution error', function(done) { - worker.on(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, err => { + it('should emit worker execution error', function (done) { + worker.on(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, (err) => { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -1058,9 +1058,9 @@ describe('Worker class', function() { }); }); - describe('workerFn throws error', function() { - beforeEach(function() { - const workerFn = function() { + describe('workerFn throws error', function () { + beforeEach(function () { + const workerFn = function () { throw new Error('test throw'); }; worker = new Worker(mockQueue, 'test', workerFn, defaultWorkerOptions); @@ -1068,14 +1068,14 @@ describe('Worker class', function() { failStub = getFailStub(worker); }); - it('should fail the job', function() { + it('should fail the job', function () { return worker._performJob(job).then(() => { sinon.assert.calledOnce(failStub); }); }); - it('should emit worker execution error', function(done) { - worker.on(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, err => { + it('should emit worker execution error', function (done) { + worker.on(constants.EVENT_WORKER_JOB_EXECUTION_ERROR, (err) => { try { expect(err).to.have.property('error'); expect(err).to.have.property('job'); @@ -1095,7 +1095,7 @@ describe('Worker class', function() { }); describe('Format Job Object', () => { - it('pulls index and ID', function() { + it('pulls index and ID', function () { const jobMock = { _index: 'foo', _id: 'booId', @@ -1108,7 +1108,7 @@ describe('Format Job Object', () => { }); describe('Get Doc Path from ES Response', () => { - it('returns a formatted string after response of an update', function() { + it('returns a formatted string after response of an update', function () { const responseMock = { _index: 'foo', _id: 'booId', diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/helpers/create_index.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/helpers/create_index.js index 465f27a817ba7..c0ce7548e2e1a 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/helpers/create_index.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/helpers/create_index.js @@ -81,7 +81,7 @@ export function createIndex(client, indexName, indexSettings = {}) { .callAsInternalUser('indices.exists', { index: indexName, }) - .then(exists => { + .then((exists) => { if (!exists) { return client .callAsInternalUser('indices.create', { @@ -89,7 +89,7 @@ export function createIndex(client, indexName, indexSettings = {}) { body: body, }) .then(() => true) - .catch(err => { + .catch((err) => { /* FIXME creating the index will fail if there were multiple jobs staged in parallel. * Each staged job checks `client.indices.exists` and could each get `false` as a response. * Only the first job in line can successfully create it though. diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/index.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/index.js index bd30ca9ae0f29..735d19f8f6c47 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/index.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/index.js @@ -26,15 +26,15 @@ export class Esqueue extends EventEmitter { ...omit(options, ['client']), }; this.client = options.client; - this._logger = options.logger || function() {}; + this._logger = options.logger || function () {}; this._workers = []; - this._initTasks().catch(err => this.emit(constants.EVENT_QUEUE_ERROR, err)); + this._initTasks().catch((err) => this.emit(constants.EVENT_QUEUE_ERROR, err)); } _initTasks() { const initTasks = [this.client.callAsInternalUser('ping')]; - return Promise.all(initTasks).catch(err => { + return Promise.all(initTasks).catch((err) => { this._logger(['initTasks', 'error'], err); throw err; }); @@ -62,11 +62,11 @@ export class Esqueue extends EventEmitter { } getWorkers() { - return this._workers.map(fn => fn); + return this._workers.map((fn) => fn); } destroy() { - const workers = this._workers.filter(worker => worker.destroy()); + const workers = this._workers.filter((worker) => worker.destroy()); this._workers = workers; } } diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/job.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/job.js index 826fcf360a4ca..6ab78eeb1b86b 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/job.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/job.js @@ -37,7 +37,7 @@ export class Job extends events.EventEmitter { } this.debug = (msg, err) => { - const logger = options.logger || function() {}; + const logger = options.logger || function () {}; const message = `${this.id} - ${msg}`; const tags = ['debug']; @@ -79,7 +79,7 @@ export class Job extends events.EventEmitter { this.ready = createIndex(this._client, this.index, this.indexSettings) .then(() => this._client.callAsInternalUser('index', indexParams)) - .then(doc => { + .then((doc) => { this.document = { id: doc._id, index: doc._index, @@ -97,7 +97,7 @@ export class Job extends events.EventEmitter { this.emit(constants.EVENT_JOB_CREATED, this.document); }); }) - .catch(err => { + .catch((err) => { this.debug('Job creation failed', err); this.emit(constants.EVENT_JOB_CREATE_ERROR, err); }); @@ -116,7 +116,7 @@ export class Job extends events.EventEmitter { id: this.id, }); }) - .then(doc => { + .then((doc) => { return Object.assign(doc._source, { index: doc._index, id: doc._id, diff --git a/x-pack/legacy/plugins/reporting/server/lib/esqueue/worker.js b/x-pack/legacy/plugins/reporting/server/lib/esqueue/worker.js index 17a7fd0e9a26f..f852ac9c92404 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/esqueue/worker.js +++ b/x-pack/legacy/plugins/reporting/server/lib/esqueue/worker.js @@ -36,7 +36,7 @@ function getLogger(opts, id, logLevel) { * This does not get the logger instance from queue.registerWorker in the createWorker function. * The logger instance in the Equeue lib comes from createTaggedLogger, so logLevel tags are passed differently */ - const logger = opts.logger || function() {}; + const logger = opts.logger || function () {}; const message = `${id} - ${msg}`; const tags = [logLevel]; @@ -167,7 +167,7 @@ export class Worker extends events.EventEmitter { if_primary_term: job._primary_term, body: { doc }, }) - .then(response => { + .then((response) => { this.info(`Job marked as claimed: ${getUpdatedDocPath(response)}`); const updatedJob = { ...job, @@ -206,10 +206,10 @@ export class Worker extends events.EventEmitter { if_primary_term: job._primary_term, body: { doc }, }) - .then(response => { + .then((response) => { this.info(`Job marked as failed: ${getUpdatedDocPath(response)}`); }) - .catch(err => { + .catch((err) => { if (err.statusCode === 409) return true; this.error(`_failJob failed to update job ${job._id}`, err); this.emit(constants.EVENT_WORKER_FAIL_UPDATE_ERROR, this._formatErrorParams(err, job)); @@ -248,7 +248,7 @@ export class Worker extends events.EventEmitter { const jobSource = job._source; Promise.resolve(this.workerFn.call(null, job, jobSource.payload, cancellationToken)) - .then(res => { + .then((res) => { // job execution was successful if (res && res.warnings && res.warnings.length > 0) { this.warn(`Job execution completed with warnings`); @@ -259,7 +259,7 @@ export class Worker extends events.EventEmitter { isResolved = true; resolve(res); }) - .catch(err => { + .catch((err) => { isResolved = true; reject(err); }); @@ -281,7 +281,7 @@ export class Worker extends events.EventEmitter { }); return workerOutput.then( - output => { + (output) => { const completedTime = moment().toISOString(); const docOutput = this._formatOutput(output); @@ -303,7 +303,7 @@ export class Worker extends events.EventEmitter { if_primary_term: job._primary_term, body: { doc }, }) - .then(response => { + .then((response) => { const eventOutput = { job: formatJobObject(job), output: docOutput, @@ -312,14 +312,14 @@ export class Worker extends events.EventEmitter { this.info(`Job data saved successfully: ${getUpdatedDocPath(response)}`); }) - .catch(err => { + .catch((err) => { if (err.statusCode === 409) return false; this.error(`Failure saving job output ${job._id}`, err); this.emit(constants.EVENT_WORKER_JOB_UPDATE_ERROR, this._formatErrorParams(err, job)); return this._failJob(job, err.message ? err.message : false); }); }, - jobErr => { + (jobErr) => { if (!jobErr) { jobErr = new UnspecifiedWorkerError('Unspecified worker error', { jobId: job._id, @@ -361,7 +361,7 @@ export class Worker extends events.EventEmitter { } _processPendingJobs() { - return this._getPendingJobs().then(jobs => { + return this._getPendingJobs().then((jobs) => { return this._claimPendingJobs(jobs); }); } @@ -374,16 +374,16 @@ export class Worker extends events.EventEmitter { // claim a single job, stopping after first successful claim return jobs .reduce((chain, job) => { - return chain.then(claimedJob => { + return chain.then((claimedJob) => { // short-circuit the promise chain if a job has been claimed if (claimed) return claimedJob; return this._claimJob(job) - .then(claimResult => { + .then((claimResult) => { claimed = true; return claimResult; }) - .catch(err => { + .catch((err) => { if (err.statusCode === 409) { this.warn( `_claimPendingJobs encountered a version conflict on updating pending job ${job._id}`, @@ -396,14 +396,14 @@ export class Worker extends events.EventEmitter { }); }); }, Promise.resolve()) - .then(claimedJob => { + .then((claimedJob) => { if (!claimedJob) { this.debug(`Found no claimable jobs out of ${jobs.length} total`); return; } return this._performJob(claimedJob); }) - .catch(err => { + .catch((err) => { this.error('Error claiming jobs', err); return Promise.reject(err); }); @@ -445,14 +445,14 @@ export class Worker extends events.EventEmitter { index: `${this.queue.index}-*`, body: query, }) - .then(results => { + .then((results) => { const jobs = results.hits.hits; if (jobs.length > 0) { this.debug(`${jobs.length} outstanding jobs returned`); } return jobs; }) - .catch(err => { + .catch((err) => { // ignore missing indices errors if (err && err.status === 404) return []; diff --git a/x-pack/legacy/plugins/reporting/server/lib/export_types_registry.ts b/x-pack/legacy/plugins/reporting/server/lib/export_types_registry.ts index ecaabb305e23e..0d5459a7c106b 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/export_types_registry.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/export_types_registry.ts @@ -103,7 +103,7 @@ function getExportTypesRegistryFn(): ExportTypesRegistry { getTypePng, getTypePrintablePdf, ]; - getTypeFns.forEach(getType => { + getTypeFns.forEach((getType) => { registry.register(getType()); }); return registry; diff --git a/x-pack/legacy/plugins/reporting/server/lib/jobs_query.ts b/x-pack/legacy/plugins/reporting/server/lib/jobs_query.ts index e0c9fc05ea2b4..1abf58c29b481 100644 --- a/x-pack/legacy/plugins/reporting/server/lib/jobs_query.ts +++ b/x-pack/legacy/plugins/reporting/server/lib/jobs_query.ts @@ -67,7 +67,7 @@ export function jobsQueryFactory( body: Object.assign(defaultBody[queryType] || {}, body), }; - return callAsInternalUser(queryType, query).catch(err => { + return callAsInternalUser(queryType, query).catch((err) => { if (err instanceof esErrors['401']) return; if (err instanceof esErrors['403']) return; if (err instanceof esErrors['404']) return; @@ -78,7 +78,7 @@ export function jobsQueryFactory( type Result = number; function getHits(query: Promise) { - return query.then(res => get(res, 'hits.hits', [])); + return query.then((res) => get(res, 'hits.hits', [])); } return { @@ -153,7 +153,7 @@ export function jobsQueryFactory( }; } - return getHits(execQuery('search', body)).then(hits => { + return getHits(execQuery('search', body)).then((hits) => { if (hits.length !== 1) return; return hits[0]; }); diff --git a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts index 70a1a32e76a65..3f79d51382a81 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generate_from_jobparams.ts @@ -48,9 +48,7 @@ export function registerGenerateFromJobParams( exportType: Joi.string().required(), }).required(), payload: Joi.object({ - jobParams: Joi.string() - .optional() - .default(null), + jobParams: Joi.string().optional().default(null), }).allow(null), // allow optional payload query: Joi.object({ jobParams: Joi.string().default(null), diff --git a/x-pack/legacy/plugins/reporting/server/routes/generation.test.ts b/x-pack/legacy/plugins/reporting/server/routes/generation.test.ts index 74401f8228f7d..d767d37a477ab 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/generation.test.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/generation.test.ts @@ -51,7 +51,7 @@ const mockPlugins = { const getErrorsFromRequest = (request: Hapi.Request) => { // @ts-ignore error property doesn't exist on RequestLog - return request.logs.filter(log => log.tags.includes('error')).map(log => log.error); // NOTE: error stack is available + return request.logs.filter((log) => log.tags.includes('error')).map((log) => log.error); // NOTE: error stack is available }; test(`returns 400 if there are no job params`, async () => { diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.js b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.js index b5d6ae59ce5dd..2c80965432cd2 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.js +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.test.js @@ -6,17 +6,17 @@ import { authorizedUserPreRoutingFactory } from './authorized_user_pre_routing'; -describe('authorized_user_pre_routing', function() { +describe('authorized_user_pre_routing', function () { const createMockConfig = (mockConfig = {}) => { return { get: (...keys) => mockConfig[keys.join('.')], kbnConfig: { get: (...keys) => mockConfig[keys.join('.')] }, }; }; - const createMockPlugins = (function() { + const createMockPlugins = (function () { const getUserStub = jest.fn(); - return function({ + return function ({ securityEnabled = true, xpackInfoUndefined = false, xpackInfoAvailable = true, @@ -69,12 +69,12 @@ describe('authorized_user_pre_routing', function() { const getMockLogger = () => ({ warn: jest.fn(), - error: msg => { + error: (msg) => { throw new Error(msg); }, }); - it('should return with boom notFound when xpackInfo is undefined', async function() { + it('should return with boom notFound when xpackInfo is undefined', async function () { const authorizedUserPreRouting = authorizedUserPreRoutingFactory( createMockConfig(), createMockPlugins({ xpackInfoUndefined: true }), @@ -85,7 +85,7 @@ describe('authorized_user_pre_routing', function() { expect(response.output.statusCode).toBe(404); }); - it(`should return with boom notFound when xpackInfo isn't available`, async function() { + it(`should return with boom notFound when xpackInfo isn't available`, async function () { const authorizedUserPreRouting = authorizedUserPreRoutingFactory( createMockConfig(), createMockPlugins({ xpackInfoAvailable: false }), @@ -96,7 +96,7 @@ describe('authorized_user_pre_routing', function() { expect(response.output.statusCode).toBe(404); }); - it('should return with null user when security is disabled in Elasticsearch', async function() { + it('should return with null user when security is disabled in Elasticsearch', async function () { const authorizedUserPreRouting = authorizedUserPreRoutingFactory( createMockConfig(), createMockPlugins({ securityEnabled: false }), @@ -106,7 +106,7 @@ describe('authorized_user_pre_routing', function() { expect(response).toBe(null); }); - it('should return with boom unauthenticated when security is enabled but no authenticated user', async function() { + it('should return with boom unauthenticated when security is enabled but no authenticated user', async function () { const mockPlugins = createMockPlugins({ user: null, config: { 'xpack.reporting.roles.allow': ['.reporting_user'] }, @@ -123,7 +123,7 @@ describe('authorized_user_pre_routing', function() { expect(response.output.statusCode).toBe(401); }); - it(`should return with boom forbidden when security is enabled but user doesn't have allowed role`, async function() { + it(`should return with boom forbidden when security is enabled but user doesn't have allowed role`, async function () { const mockConfig = createMockConfig({ 'roles.allow': ['.reporting_user'] }); const mockPlugins = createMockPlugins({ user: { roles: [] }, @@ -140,7 +140,7 @@ describe('authorized_user_pre_routing', function() { expect(response.output.statusCode).toBe(403); }); - it('should return with user when security is enabled and user has explicitly allowed role', async function() { + it('should return with user when security is enabled and user has explicitly allowed role', async function () { const user = { roles: ['.reporting_user', 'something_else'] }; const mockConfig = createMockConfig({ 'roles.allow': ['.reporting_user'] }); const mockPlugins = createMockPlugins({ @@ -157,7 +157,7 @@ describe('authorized_user_pre_routing', function() { expect(response).toEqual(user); }); - it('should return with user when security is enabled and user has superuser role', async function() { + it('should return with user when security is enabled and user has superuser role', async function () { const user = { roles: ['superuser', 'something_else'] }; const mockConfig = createMockConfig({ 'roles.allow': [] }); const mockPlugins = createMockPlugins({ diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts index 0d297a60a3559..0c4e75a53831e 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts @@ -46,7 +46,7 @@ export const authorizedUserPreRoutingFactory = function authorizedUserPreRouting } const authorizedRoles = [superuserRole, ...(config.get('roles', 'allow') as string[])]; - if (!user.roles.find(role => authorizedRoles.includes(role))) { + if (!user.roles.find((role) => authorizedRoles.includes(role))) { return Boom.forbidden(`Sorry, you don't have access to Reporting`); } diff --git a/x-pack/legacy/plugins/reporting/server/routes/lib/job_response_handler.ts b/x-pack/legacy/plugins/reporting/server/routes/lib/job_response_handler.ts index 59aa7d904dcf4..174ec15c81d8a 100644 --- a/x-pack/legacy/plugins/reporting/server/routes/lib/job_response_handler.ts +++ b/x-pack/legacy/plugins/reporting/server/routes/lib/job_response_handler.ts @@ -38,7 +38,7 @@ export function downloadJobResponseHandlerFactory( ) { const { docId } = params; // TODO: async/await - return jobsQuery.get(user, docId, { includeContent: !opts.excludeContent }).then(doc => { + return jobsQuery.get(user, docId, { includeContent: !opts.excludeContent }).then((doc) => { if (!doc) return Boom.notFound(); const { jobtype: jobType } = doc._source; @@ -54,13 +54,10 @@ export function downloadJobResponseHandlerFactory( ); } - const response = h - .response(output.content) - .type(output.contentType) - .code(output.statusCode); + const response = h.response(output.content).type(output.contentType).code(output.statusCode); if (output.headers) { - Object.keys(output.headers).forEach(key => { + Object.keys(output.headers).forEach((key) => { response.header(key, output.headers[key]); }); } diff --git a/x-pack/legacy/plugins/reporting/server/usage/decorate_range_stats.ts b/x-pack/legacy/plugins/reporting/server/usage/decorate_range_stats.ts index ef985d2dd1cf3..30befcf291a54 100644 --- a/x-pack/legacy/plugins/reporting/server/usage/decorate_range_stats.ts +++ b/x-pack/legacy/plugins/reporting/server/usage/decorate_range_stats.ts @@ -21,7 +21,7 @@ function getForFeature( type AdditionalType = { [K in keyof typeof additional]: K }; const filledAdditional: AdditionalType = {}; if (additional) { - Object.keys(additional).forEach(k => { + Object.keys(additional).forEach((k) => { filledAdditional[k] = { ...additional[k], ...jobType[k] }; }); } diff --git a/x-pack/legacy/plugins/security/public/hacks/legacy.ts b/x-pack/legacy/plugins/security/public/hacks/legacy.ts index 2c683fe4ecf80..ca7e3b7ce5190 100644 --- a/x-pack/legacy/plugins/security/public/hacks/legacy.ts +++ b/x-pack/legacy/plugins/security/public/hacks/legacy.ts @@ -56,7 +56,7 @@ if (securityPluginSetup) { } return { - response: interceptorFactory(response => response), + response: interceptorFactory((response) => response), responseError: interceptorFactory($q.reject), }; }); diff --git a/x-pack/legacy/plugins/xpack_main/index.js b/x-pack/legacy/plugins/xpack_main/index.js index 1f8a4a62ea156..b3d4a5fa8214b 100644 --- a/x-pack/legacy/plugins/xpack_main/index.js +++ b/x-pack/legacy/plugins/xpack_main/index.js @@ -13,7 +13,7 @@ import { xpackInfoRoute, settingsRoute } from './server/routes/api/v1'; export { callClusterFactory } from './server/lib/call_cluster_factory'; -export const xpackMain = kibana => { +export const xpackMain = (kibana) => { return new kibana.Plugin({ id: 'xpack_main', configPrefix: 'xpack.xpack_main', diff --git a/x-pack/legacy/plugins/xpack_main/public/hacks/check_xpack_info_change.js b/x-pack/legacy/plugins/xpack_main/public/hacks/check_xpack_info_change.js index 6d45be4bda3d5..9047cdc15e93c 100644 --- a/x-pack/legacy/plugins/xpack_main/public/hacks/check_xpack_info_change.js +++ b/x-pack/legacy/plugins/xpack_main/public/hacks/check_xpack_info_change.js @@ -43,11 +43,11 @@ module.factory('checkXPackInfoChange', ($q, Private, $injector) => { } return { - response: response => interceptor(response, identity), - responseError: response => interceptor(response, $q.reject), + response: (response) => interceptor(response, identity), + responseError: (response) => interceptor(response, $q.reject), }; }); -module.config($httpProvider => { +module.config(($httpProvider) => { $httpProvider.interceptors.push('checkXPackInfoChange'); }); diff --git a/x-pack/legacy/plugins/xpack_main/public/services/xpack_info.js b/x-pack/legacy/plugins/xpack_main/public/services/xpack_info.js index 8e71e2f63fa73..8e514b7040520 100644 --- a/x-pack/legacy/plugins/xpack_main/public/services/xpack_info.js +++ b/x-pack/legacy/plugins/xpack_main/public/services/xpack_info.js @@ -23,7 +23,7 @@ export class XPackInfo { return get(xpackInfoValues, path, defaultValue); }; - setAll = updatedXPackInfo => { + setAll = (updatedXPackInfo) => { // The decision to convert kebab-case/snake-case keys to camel-case keys stemmed from an old // convention of using kebabe-case/snake-case in API response bodies but camel-case in JS // objects. See pull #29304 for more info. @@ -37,7 +37,7 @@ export class XPackInfo { sessionStorage.removeItem(XPACK_INFO_KEY); }; - refresh = $injector => { + refresh = ($injector) => { if (this.inProgressRefreshPromise) { return this.inProgressRefreshPromise; } @@ -47,14 +47,14 @@ export class XPackInfo { const $http = $injector.get('$http'); this.inProgressRefreshPromise = $http .get(chrome.addBasePath('/api/xpack/v1/info')) - .catch(err => { + .catch((err) => { // if we are unable to fetch the updated info, we should // prevent reusing stale info this.clear(); xpackInfoSignature.clear(); throw err; }) - .then(xpackInfoResponse => { + .then((xpackInfoResponse) => { this.setAll(xpackInfoResponse.data); xpackInfoSignature.set(xpackInfoResponse.headers('kbn-xpack-sig')); }) diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/call_cluster_factory.js b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/call_cluster_factory.js index 155cbc7a272a4..abe0d327d7b5c 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/call_cluster_factory.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/call_cluster_factory.js @@ -20,10 +20,7 @@ describe('callClusterFactory', () => { mockServer = { plugins: { elasticsearch: { - getCluster: sinon - .stub() - .withArgs('admin') - .returns(mockCluster), + getCluster: sinon.stub().withArgs('admin').returns(mockCluster), }, }, log() {}, diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/inject_xpack_info_signature.js b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/inject_xpack_info_signature.js index b6a61ce62a3bb..420f3b2d6631c 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/inject_xpack_info_signature.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/inject_xpack_info_signature.js @@ -39,7 +39,7 @@ describe('injectXPackInfoSignature()', () => { // We need this to make sure the code waits for `refreshNow` to complete before it tries // to access its properties. mockXPackInfo.refreshNow = () => { - return new Promise(resolve => { + return new Promise((resolve) => { mockXPackInfo.isAvailable.returns(false); resolve(); }); @@ -64,7 +64,7 @@ describe('injectXPackInfoSignature()', () => { // We need this to make sure the code waits for `refreshNow` to complete before it tries // to access its properties. mockXPackInfo.refreshNow = () => { - return new Promise(resolve => { + return new Promise((resolve) => { mockXPackInfo.getSignature.returns('new-signature'); resolve(); }); diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/replace_injected_vars.js b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/replace_injected_vars.js index cb70a7cb446a9..f2dda63e689b9 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/replace_injected_vars.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/replace_injected_vars.js @@ -28,7 +28,7 @@ const buildRequest = (path = '/app/kibana') => { create: sinon.stub(), errors: { - isNotFoundError: error => { + isNotFoundError: (error) => { return error.message === 'not found exception'; }, }, diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/setup_xpack_main.js b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/setup_xpack_main.js index f540da1368792..b4a2c090d6309 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/setup_xpack_main.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/setup_xpack_main.js @@ -102,7 +102,7 @@ describe('setupXPackMain()', () => { // We need this to make sure the code waits for `refreshNow` to complete before it tries // to access its properties. sinon.stub(xPackInfo, 'refreshNow').callsFake(() => { - return new Promise(resolve => { + return new Promise((resolve) => { xPackInfo.isAvailable.returns(true); resolve(); }); @@ -121,7 +121,7 @@ describe('setupXPackMain()', () => { // We need this to make sure the code waits for `refreshNow` to complete before it tries // to access its properties. sinon.stub(xPackInfo, 'refreshNow').callsFake(() => { - return new Promise(resolve => { + return new Promise((resolve) => { xPackInfo.isAvailable.returns(false); xPackInfo.unavailableReason.returns('Some weird error.'); resolve(); diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/xpack_info.js b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/xpack_info.js index 2e0d608e522d7..81fb822882817 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/xpack_info.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/__tests__/xpack_info.js @@ -38,9 +38,7 @@ function createLicense(license = {}, features = {}) { } function getSignature(object) { - return createHash('md5') - .update(JSON.stringify(object)) - .digest('hex'); + return createHash('md5').update(JSON.stringify(object)).digest('hex'); } describe('XPackInfo', () => { @@ -208,7 +206,7 @@ describe('XPackInfo', () => { expect(xPackInfo.toJSON().features.security).to.be(undefined); expect(xPackInfo.toJSON().features.watcher).to.be(undefined); - securityFeature.registerLicenseCheckResultsGenerator(info => { + securityFeature.registerLicenseCheckResultsGenerator((info) => { return { isXPackInfo: info instanceof XPackInfo, license: info.license.getType(), @@ -223,7 +221,7 @@ describe('XPackInfo', () => { }); expect(xPackInfo.toJSON().features.watcher).to.be(undefined); - watcherFeature.registerLicenseCheckResultsGenerator(info => { + watcherFeature.registerLicenseCheckResultsGenerator((info) => { return { isXPackInfo: info instanceof XPackInfo, license: info.license.getType(), @@ -263,7 +261,7 @@ describe('XPackInfo', () => { expect(securityFeature.getLicenseCheckResults()).to.be(undefined); expect(watcherFeature.getLicenseCheckResults()).to.be(undefined); - securityFeature.registerLicenseCheckResultsGenerator(info => { + securityFeature.registerLicenseCheckResultsGenerator((info) => { return { isXPackInfo: info instanceof XPackInfo, license: info.license.getType(), @@ -278,7 +276,7 @@ describe('XPackInfo', () => { }); expect(watcherFeature.getLicenseCheckResults()).to.be(undefined); - watcherFeature.registerLicenseCheckResultsGenerator(info => { + watcherFeature.registerLicenseCheckResultsGenerator((info) => { return { isXPackInfo: info instanceof XPackInfo, license: info.license.getType(), @@ -323,7 +321,7 @@ describe('XPackInfo', () => { }); const watcherFeature = xPackInfo.feature('watcher'); - watcherFeature.registerLicenseCheckResultsGenerator(info => ({ + watcherFeature.registerLicenseCheckResultsGenerator((info) => ({ type: info.license.getType(), })); @@ -349,7 +347,7 @@ describe('XPackInfo', () => { const watcherFeature = xPackInfo.feature('watcher'); - watcherFeature.registerLicenseCheckResultsGenerator(info => ({ + watcherFeature.registerLicenseCheckResultsGenerator((info) => ({ type: info.license.getType(), })); diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info.ts b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info.ts index 9d5a8e64645ec..aa66532a2897d 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info.ts +++ b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info.ts @@ -102,7 +102,7 @@ export class XPackInfo { }; } - this._licenseInfoChangedListeners.forEach(fn => fn()); + this._licenseInfoChangedListeners.forEach((fn) => fn()); }); this._license = new XPackInfoLicense(() => this._cache.license); @@ -204,9 +204,7 @@ export class XPackInfo { return this._cache.signature; } - this._cache.signature = createHash('md5') - .update(JSON.stringify(this.toJSON())) - .digest('hex'); + this._cache.signature = createHash('md5').update(JSON.stringify(this.toJSON())).digest('hex'); return this._cache.signature; } diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.test.js b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.test.js index ed2043e00b9a7..ccb5742216ca7 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.test.js +++ b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.test.js @@ -108,7 +108,7 @@ describe('XPackInfoLicense', () => { }); test('isActiveLicense returns the true if active and typeChecker matches', () => { - const expectAbc123 = type => type === 'abc123'; + const expectAbc123 = (type) => type === 'abc123'; getRawLicense.mockReturnValue( licensingMock.createLicense({ license: { status: 'active', mode: 'abc123' } }) diff --git a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.ts b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.ts index e1951a4bca047..dd53f63909475 100644 --- a/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.ts +++ b/x-pack/legacy/plugins/xpack_main/server/lib/xpack_info_license.ts @@ -95,7 +95,7 @@ export class XPackInfoLicense { * @returns {boolean} */ isBasic() { - return this.isActiveLicense(mode => mode === 'basic'); + return this.isActiveLicense((mode) => mode === 'basic'); } /** @@ -106,6 +106,6 @@ export class XPackInfoLicense { * @returns {boolean} */ isNotBasic() { - return this.isActiveLicense(mode => mode !== 'basic'); + return this.isActiveLicense((mode) => mode !== 'basic'); } } diff --git a/x-pack/legacy/plugins/xpack_main/server/routes/api/v1/settings.js b/x-pack/legacy/plugins/xpack_main/server/routes/api/v1/settings.js index 99071a2f85e13..34fc4d97c1328 100644 --- a/x-pack/legacy/plugins/xpack_main/server/routes/api/v1/settings.js +++ b/x-pack/legacy/plugins/xpack_main/server/routes/api/v1/settings.js @@ -8,7 +8,7 @@ import { boomify } from 'boom'; import { get } from 'lodash'; import { KIBANA_SETTINGS_TYPE } from '../../../../../../../plugins/monitoring/common/constants'; -const getClusterUuid = async callCluster => { +const getClusterUuid = async (callCluster) => { const { cluster_uuid: uuid } = await callCluster('info', { filterPath: 'cluster_uuid' }); return uuid; }; diff --git a/x-pack/legacy/server/lib/__tests__/kibana_state.js b/x-pack/legacy/server/lib/__tests__/kibana_state.js index 1865c3ecb6cdb..d1b4142b10446 100644 --- a/x-pack/legacy/server/lib/__tests__/kibana_state.js +++ b/x-pack/legacy/server/lib/__tests__/kibana_state.js @@ -15,28 +15,28 @@ const stateIndices = { const globalTime = '(refreshInterval:(display:Off,pause:!f,value:0),time:(from:now-15m,mode:quick,to:now))'; -describe('Kibana state', function() { - describe('type checking', function() { - it('should throw if not given an object', function() { +describe('Kibana state', function () { + describe('type checking', function () { + it('should throw if not given an object', function () { const fn = () => parseKibanaState('i am not an object', 'global'); const fn2 = () => parseKibanaState(['arrays are not valid either'], 'global'); expect(fn).to.throwException(/must be an object/i); expect(fn2).to.throwException(/must be an object/i); }); - it('should throw with invalid type', function() { + it('should throw with invalid type', function () { const fn = () => parseKibanaState({}, 'this is an invalid state type'); expect(fn).to.throwException(/unknown state type/i); }); }); - describe('value of exists', function() { - it('should be false if state does not exist', function() { + describe('value of exists', function () { + it('should be false if state does not exist', function () { const state = parseKibanaState({}, 'global'); expect(state.exists).to.equal(false); }); - it('should be true if state exists', function() { + it('should be true if state exists', function () { const query = {}; query[stateIndices.global] = rison.encode({ hello: 'world' }); const state = parseKibanaState(query, 'global'); @@ -44,30 +44,30 @@ describe('Kibana state', function() { }); }); - describe('instance methods', function() { + describe('instance methods', function () { let query; - beforeEach(function() { + beforeEach(function () { query = {}; query[stateIndices.global] = globalTime; }); - describe('get', function() { - it('should return the value', function() { + describe('get', function () { + it('should return the value', function () { const state = parseKibanaState(query, 'global'); const { refreshInterval } = rison.decode(globalTime); expect(state.get('refreshInterval')).to.eql(refreshInterval); }); - it('should use the default value for missing props', function() { + it('should use the default value for missing props', function () { const defaultValue = 'default value'; const state = parseKibanaState(query, 'global'); expect(state.get('no such value', defaultValue)).to.equal(defaultValue); }); }); - describe('set', function() { - it('should update the value of the state', function() { + describe('set', function () { + it('should update the value of the state', function () { const state = parseKibanaState(query, 'global'); expect(state.get('refreshInterval.pause')).to.equal(false); @@ -75,7 +75,7 @@ describe('Kibana state', function() { expect(state.get('refreshInterval.pause')).to.equal(true); }); - it('should create new properties', function() { + it('should create new properties', function () { const prop = 'newProp'; const value = 12345; const state = parseKibanaState(query, 'global'); @@ -87,8 +87,8 @@ describe('Kibana state', function() { }); }); - describe('removing properties', function() { - it('should remove a single value', function() { + describe('removing properties', function () { + it('should remove a single value', function () { const state = parseKibanaState(query, 'global'); expect(state.get('refreshInterval')).to.be.an('object'); @@ -96,7 +96,7 @@ describe('Kibana state', function() { expect(state.get('refreshInterval')).to.be(undefined); }); - it('should remove multiple values', function() { + it('should remove multiple values', function () { const state = parseKibanaState(query, 'global'); expect(state.get('refreshInterval')).to.be.an('object'); expect(state.get('time')).to.be.an('object'); @@ -107,20 +107,20 @@ describe('Kibana state', function() { }); }); - describe('toString', function() { - it('should rison encode the state', function() { + describe('toString', function () { + it('should rison encode the state', function () { const state = parseKibanaState(query, 'global'); expect(state.toString()).to.equal(globalTime); }); }); - describe('toQuery', function() { - it('should return an object', function() { + describe('toQuery', function () { + it('should return an object', function () { const state = parseKibanaState(query, 'global'); expect(state.toQuery()).to.be.an('object'); }); - it('should contain the kibana state property', function() { + it('should contain the kibana state property', function () { const state = parseKibanaState(query, 'global'); expect(state.toQuery()).to.have.property(stateIndices.global, globalTime); }); diff --git a/x-pack/legacy/server/lib/__tests__/mirror_plugin_status.js b/x-pack/legacy/server/lib/__tests__/mirror_plugin_status.js index d6199fd0f402b..c7cae0785c9eb 100644 --- a/x-pack/legacy/server/lib/__tests__/mirror_plugin_status.js +++ b/x-pack/legacy/server/lib/__tests__/mirror_plugin_status.js @@ -61,7 +61,7 @@ describe('mirror_plugin_status', () => { }, 100); }); - it('should mirror all downstream plugin statuses to upstream plugin statuses', done => { + it('should mirror all downstream plugin statuses to upstream plugin statuses', (done) => { mirrorPluginStatus(upstreamPlugin, downstreamPlugin); downstreamPlugin.status.on('change', () => { clearTimeout(eventNotEmittedTimeout); @@ -77,7 +77,7 @@ describe('mirror_plugin_status', () => { mirrorPluginStatus(upstreamPlugin, downstreamPlugin, 'yellow', 'red'); }); - it('yellow', done => { + it('yellow', (done) => { downstreamPlugin.status.on('change', () => { clearTimeout(eventNotEmittedTimeout); expect(downstreamPlugin.status.state).to.be('yellow'); @@ -87,7 +87,7 @@ describe('mirror_plugin_status', () => { upstreamPlugin.status.yellow('test yellow message'); }); - it('red', done => { + it('red', (done) => { downstreamPlugin.status.on('change', () => { clearTimeout(eventNotEmittedTimeout); expect(downstreamPlugin.status.state).to.be('red'); diff --git a/x-pack/legacy/server/lib/audit_logger.js b/x-pack/legacy/server/lib/audit_logger.js index 98c8acc14c1a3..7d3467b323b3f 100644 --- a/x-pack/legacy/server/lib/audit_logger.js +++ b/x-pack/legacy/server/lib/audit_logger.js @@ -17,7 +17,7 @@ export class AuditLogger { this._enabled = config.get('xpack.security.enabled') && config.get('xpack.security.audit.enabled'); this._licensed = false; - this._checkLicense = xPackInfo => { + this._checkLicense = (xPackInfo) => { this._licensed = checkLicense(FEATURE.ID, LICENSE_TYPE_STANDARD, xPackInfo).status === LICENSE_STATUS_VALID; }; diff --git a/x-pack/legacy/server/lib/audit_logger.test.js b/x-pack/legacy/server/lib/audit_logger.test.js index a9c030cf1a21c..51a239801caac 100644 --- a/x-pack/legacy/server/lib/audit_logger.test.js +++ b/x-pack/legacy/server/lib/audit_logger.test.js @@ -10,12 +10,12 @@ import { LICENSE_TYPE_GOLD, } from '../../common/constants'; -const createMockConfig = settings => { +const createMockConfig = (settings) => { const mockConfig = { get: jest.fn(), }; - mockConfig.get.mockImplementation(key => { + mockConfig.get.mockImplementation((key) => { return settings[key]; }); @@ -172,7 +172,7 @@ test(`calls server.log after basic -> gold upgrade`, () => { isAvailable: () => true, feature: () => { return { - registerLicenseCheckResultsGenerator: fn => { + registerLicenseCheckResultsGenerator: (fn) => { licenseCheckResultsGenerator = fn; }, }; diff --git a/x-pack/legacy/server/lib/check_license/check_license.test.js b/x-pack/legacy/server/lib/check_license/check_license.test.js index 7ef5804487cd2..0545e1a2d16f4 100644 --- a/x-pack/legacy/server/lib/check_license/check_license.test.js +++ b/x-pack/legacy/server/lib/check_license/check_license.test.js @@ -13,7 +13,7 @@ import { LICENSE_TYPE_BASIC, } from '../../../common/constants'; -describe('check_license', function() { +describe('check_license', function () { const pluginName = 'Foo'; const minimumLicenseRequired = LICENSE_TYPE_BASIC; let mockLicenseInfo; diff --git a/x-pack/legacy/server/lib/create_router/index.js b/x-pack/legacy/server/lib/create_router/index.js index 8da61f7151c9f..e4d66bdb5a48b 100644 --- a/x-pack/legacy/server/lib/create_router/index.js +++ b/x-pack/legacy/server/lib/create_router/index.js @@ -12,7 +12,7 @@ import { licensePreRoutingFactory } from './license_pre_routing_factory'; export { wrapEsError, wrapUnknownError, wrapCustomError } from './error_wrappers'; // Sometimes consumers will need to check if errors are ES errors, too. -export const isEsErrorFactory = server => { +export const isEsErrorFactory = (server) => { return createIsEsError(server); }; @@ -25,7 +25,7 @@ export const createRouter = (server, pluginId, apiBasePath = '', config) => { const callWithRequestInstance = callWithRequestFactory(server, pluginId, config); - const requestHandler = handler => async (request, h) => { + const requestHandler = (handler) => async (request, h) => { try { const callWithRequest = (...args) => { return callWithRequestInstance(request, ...args); diff --git a/x-pack/legacy/server/lib/create_router/is_es_error_factory/is_es_error_factory.js b/x-pack/legacy/server/lib/create_router/is_es_error_factory/is_es_error_factory.js index 6c17554385ef8..80daac5bd496d 100644 --- a/x-pack/legacy/server/lib/create_router/is_es_error_factory/is_es_error_factory.js +++ b/x-pack/legacy/server/lib/create_router/is_es_error_factory/is_es_error_factory.js @@ -6,7 +6,7 @@ import { memoize } from 'lodash'; -const esErrorsFactory = memoize(server => { +const esErrorsFactory = memoize((server) => { return server.plugins.elasticsearch.getCluster('admin').errors; }); diff --git a/x-pack/legacy/server/lib/create_router/license_pre_routing_factory/__tests__/license_pre_routing_factory.js b/x-pack/legacy/server/lib/create_router/license_pre_routing_factory/__tests__/license_pre_routing_factory.js index cc9fd3615064b..dde18a0ccd7dd 100644 --- a/x-pack/legacy/server/lib/create_router/license_pre_routing_factory/__tests__/license_pre_routing_factory.js +++ b/x-pack/legacy/server/lib/create_router/license_pre_routing_factory/__tests__/license_pre_routing_factory.js @@ -44,7 +44,7 @@ describe('license_pre_routing_factory', () => { it('replies with 403', () => { const licensePreRouting = licensePreRoutingFactory(mockServer); const stubRequest = {}; - expect(() => licensePreRouting(stubRequest)).to.throwException(response => { + expect(() => licensePreRouting(stubRequest)).to.throwException((response) => { expect(response).to.be.an(Error); expect(response.isBoom).to.be(true); expect(response.output.statusCode).to.be(403); diff --git a/x-pack/legacy/server/lib/mirror_plugin_status.js b/x-pack/legacy/server/lib/mirror_plugin_status.js index 0ec34e80d65d5..7b1ac215f5e4c 100644 --- a/x-pack/legacy/server/lib/mirror_plugin_status.js +++ b/x-pack/legacy/server/lib/mirror_plugin_status.js @@ -17,6 +17,6 @@ export function mirrorPluginStatus(upstreamPlugin, downstreamPlugin, ...statesTo statesToMirror.push('change'); } - statesToMirror.map(state => upstreamPlugin.status.on(state, mirror)); + statesToMirror.map((state) => upstreamPlugin.status.on(state, mirror)); mirror(null, null, upstreamPlugin.status.state, upstreamPlugin.status.message); // initial mirroring } diff --git a/x-pack/legacy/server/lib/register_license_checker/register_license_checker.js b/x-pack/legacy/server/lib/register_license_checker/register_license_checker.js index 9839237237ae1..eabe375eefd02 100644 --- a/x-pack/legacy/server/lib/register_license_checker/register_license_checker.js +++ b/x-pack/legacy/server/lib/register_license_checker/register_license_checker.js @@ -17,7 +17,7 @@ export function registerLicenseChecker(server, pluginId, pluginName, minimumLice // to re-compute the license check results for this plugin xpackMainPlugin.info .feature(pluginId) - .registerLicenseCheckResultsGenerator(xpackLicenseInfo => { + .registerLicenseCheckResultsGenerator((xpackLicenseInfo) => { return checkLicense(pluginName, minimumLicenseRequired, xpackLicenseInfo); }); }); diff --git a/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.js b/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.js index 84800c80e1d86..109dbbb20e35d 100644 --- a/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.js +++ b/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.js @@ -9,7 +9,7 @@ import { catchError, mergeMap, map, switchMap, tap } from 'rxjs/operators'; export const RETRY_SCALE_DURATION = 100; export const RETRY_DURATION_MAX = 10000; -const calculateDuration = i => { +const calculateDuration = (i) => { const duration = i * RETRY_SCALE_DURATION; if (duration > RETRY_DURATION_MAX) { return RETRY_DURATION_MAX; diff --git a/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.test.js b/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.test.js index b4dabb02ef2d7..33282b7591db7 100644 --- a/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.test.js +++ b/x-pack/legacy/server/lib/watch_status_and_license_to_initialize.test.js @@ -11,7 +11,7 @@ import { RETRY_DURATION_MAX, } from './watch_status_and_license_to_initialize'; -const createMockXpackMainPluginAndFeature = featureId => { +const createMockXpackMainPluginAndFeature = (featureId) => { const licenseChangeCallbacks = []; const mockFeature = { @@ -22,7 +22,7 @@ const createMockXpackMainPluginAndFeature = featureId => { callback(); } }, - setLicenseCheckResults: value => { + setLicenseCheckResults: (value) => { mockFeature.getLicenseCheckResults.mockReturnValue(value); }, }, @@ -30,10 +30,10 @@ const createMockXpackMainPluginAndFeature = featureId => { const mockXpackMainPlugin = { info: { - onLicenseInfoChange: callback => { + onLicenseInfoChange: (callback) => { licenseChangeCallbacks.push(callback); }, - feature: id => { + feature: (id) => { if (id === featureId) { return mockFeature; } @@ -53,7 +53,7 @@ const createMockXpackMainPluginAndFeature = featureId => { return { mockXpackMainPlugin, mockFeature }; }; -const createMockDownstreamPlugin = id => { +const createMockDownstreamPlugin = (id) => { const defaultImplementation = () => { throw new Error('Not implemented'); }; @@ -68,7 +68,7 @@ const createMockDownstreamPlugin = id => { }; }; -const advanceRetry = async initializeCount => { +const advanceRetry = async (initializeCount) => { await Promise.resolve(); let duration = initializeCount * RETRY_SCALE_DURATION; if (duration > RETRY_DURATION_MAX) { @@ -77,7 +77,7 @@ const advanceRetry = async initializeCount => { jest.advanceTimersByTime(duration); }; -['red', 'yellow', 'disabled'].forEach(state => { +['red', 'yellow', 'disabled'].forEach((state) => { test(`mirrors ${state} immediately`, () => { const pluginId = 'foo-plugin'; const message = `${state} is now the state`; @@ -111,7 +111,7 @@ test(`calls initialize and doesn't immediately set downstream status when the in expect(downstreamPlugin.status.green).toHaveBeenCalledTimes(0); }); -test(`sets downstream plugin's status to green when initialize resolves`, done => { +test(`sets downstream plugin's status to green when initialize resolves`, (done) => { const pluginId = 'foo-plugin'; const { mockXpackMainPlugin, mockFeature } = createMockXpackMainPluginAndFeature(pluginId); mockXpackMainPlugin.mock.setStatus('green', 'green is now the state'); @@ -124,13 +124,13 @@ test(`sets downstream plugin's status to green when initialize resolves`, done = expect(initializeMock).toHaveBeenCalledTimes(1); expect(initializeMock).toHaveBeenCalledWith(licenseCheckResults); - downstreamPlugin.status.green.mockImplementation(actualMessage => { + downstreamPlugin.status.green.mockImplementation((actualMessage) => { expect(actualMessage).toBe('Ready'); done(); }); }); -test(`sets downstream plugin's status to red when initialize initially rejects, and continually polls initialize`, done => { +test(`sets downstream plugin's status to red when initialize initially rejects, and continually polls initialize`, (done) => { jest.useFakeTimers(); const pluginId = 'foo-plugin'; @@ -168,13 +168,13 @@ test(`sets downstream plugin's status to red when initialize initially rejects, expect(initializeMock).toHaveBeenCalledTimes(1); expect(initializeMock).toHaveBeenCalledWith(licenseCheckResults); - downstreamPlugin.status.red.mockImplementation(message => { + downstreamPlugin.status.red.mockImplementation((message) => { isRed = true; expect(message).toBe(errorMessage); }); }); -test(`sets downstream plugin's status to green when initialize resolves after rejecting 10 times`, done => { +test(`sets downstream plugin's status to green when initialize resolves after rejecting 10 times`, (done) => { jest.useFakeTimers(); const pluginId = 'foo-plugin'; @@ -206,18 +206,18 @@ test(`sets downstream plugin's status to green when initialize resolves after re expect(initializeMock).toHaveBeenCalledTimes(1); expect(initializeMock).toHaveBeenCalledWith(licenseCheckResults); - downstreamPlugin.status.red.mockImplementation(message => { + downstreamPlugin.status.red.mockImplementation((message) => { expect(initializeCount).toBeLessThan(10); expect(message).toBe(errorMessage); }); - downstreamPlugin.status.green.mockImplementation(message => { + downstreamPlugin.status.green.mockImplementation((message) => { expect(initializeCount).toBe(10); expect(message).toBe('Ready'); done(); }); }); -test(`calls initialize twice when it gets a new license and the status is green`, done => { +test(`calls initialize twice when it gets a new license and the status is green`, (done) => { const pluginId = 'foo-plugin'; const { mockXpackMainPlugin, mockFeature } = createMockXpackMainPluginAndFeature(pluginId); mockXpackMainPlugin.mock.setStatus('green'); @@ -228,7 +228,7 @@ test(`calls initialize twice when it gets a new license and the status is green` const initializeMock = jest.fn().mockImplementation(() => Promise.resolve()); let count = 0; - downstreamPlugin.status.green.mockImplementation(message => { + downstreamPlugin.status.green.mockImplementation((message) => { expect(message).toBe('Ready'); ++count; if (count === 1) { @@ -246,7 +246,7 @@ test(`calls initialize twice when it gets a new license and the status is green` watchStatusAndLicenseToInitialize(mockXpackMainPlugin, downstreamPlugin, initializeMock); }); -test(`doesn't call initialize twice when it gets a new license when the status isn't green`, done => { +test(`doesn't call initialize twice when it gets a new license when the status isn't green`, (done) => { const pluginId = 'foo-plugin'; const redMessage = 'the red message'; const { mockXpackMainPlugin, mockFeature } = createMockXpackMainPluginAndFeature(pluginId); @@ -257,14 +257,14 @@ test(`doesn't call initialize twice when it gets a new license when the status i const downstreamPlugin = createMockDownstreamPlugin(pluginId); const initializeMock = jest.fn().mockImplementation(() => Promise.resolve()); - downstreamPlugin.status.green.mockImplementation(message => { + downstreamPlugin.status.green.mockImplementation((message) => { expect(message).toBe('Ready'); mockXpackMainPlugin.mock.setStatus('red', redMessage); mockFeature.mock.setLicenseCheckResults(secondLicenseCheckResults); mockFeature.mock.triggerLicenseChange(); }); - downstreamPlugin.status.red.mockImplementation(message => { + downstreamPlugin.status.red.mockImplementation((message) => { expect(message).toBe(redMessage); expect(initializeMock).toHaveBeenCalledTimes(1); expect(initializeMock).toHaveBeenCalledWith(firstLicenseCheckResults); @@ -274,7 +274,7 @@ test(`doesn't call initialize twice when it gets a new license when the status i watchStatusAndLicenseToInitialize(mockXpackMainPlugin, downstreamPlugin, initializeMock); }); -test(`calls initialize twice when the status changes to green twice`, done => { +test(`calls initialize twice when the status changes to green twice`, (done) => { const pluginId = 'foo-plugin'; const { mockXpackMainPlugin, mockFeature } = createMockXpackMainPluginAndFeature(pluginId); mockXpackMainPlugin.mock.setStatus('green'); @@ -284,7 +284,7 @@ test(`calls initialize twice when the status changes to green twice`, done => { const initializeMock = jest.fn().mockImplementation(() => Promise.resolve()); let count = 0; - downstreamPlugin.status.green.mockImplementation(message => { + downstreamPlugin.status.green.mockImplementation((message) => { expect(message).toBe('Ready'); ++count; if (count === 1) { diff --git a/x-pack/plugins/actions/server/action_type_registry.test.ts b/x-pack/plugins/actions/server/action_type_registry.test.ts index a8f50ec3535e2..ce5c1fe8500fb 100644 --- a/x-pack/plugins/actions/server/action_type_registry.test.ts +++ b/x-pack/plugins/actions/server/action_type_registry.test.ts @@ -41,7 +41,7 @@ beforeEach(() => { }; }); -const executor: ExecutorType = async options => { +const executor: ExecutorType = async (options) => { return { status: 'ok', actionId: options.actionId }; }; diff --git a/x-pack/plugins/actions/server/action_type_registry.ts b/x-pack/plugins/actions/server/action_type_registry.ts index 73ae49a7e69c2..1f7409fedd2c2 100644 --- a/x-pack/plugins/actions/server/action_type_registry.ts +++ b/x-pack/plugins/actions/server/action_type_registry.ts @@ -69,7 +69,7 @@ export class ActionTypeRegistry { this.isActionTypeEnabled(actionTypeId) || (!this.isActionTypeEnabled(actionTypeId) && this.preconfiguredActions.find( - preconfiguredAction => preconfiguredAction.id === actionId + (preconfiguredAction) => preconfiguredAction.id === actionId ) !== undefined) ); } diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index c96c993fef606..0132cc8bdb01a 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -30,7 +30,7 @@ let actionsClient: ActionsClient; let mockedLicenseState: jest.Mocked; let actionTypeRegistry: ActionTypeRegistry; let actionTypeRegistryParams: ActionTypeRegistryOpts; -const executor: ExecutorType = async options => { +const executor: ExecutorType = async (options) => { return { status: 'ok', actionId: options.actionId }; }; diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index 618bc8a85e856..c9052cf53d948 100644 --- a/x-pack/plugins/actions/server/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client.ts @@ -102,7 +102,7 @@ export class ActionsClient { */ public async update({ id, action }: UpdateOptions): Promise { if ( - this.preconfiguredActions.find(preconfiguredAction => preconfiguredAction.id === id) !== + this.preconfiguredActions.find((preconfiguredAction) => preconfiguredAction.id === id) !== undefined ) { throw new PreconfiguredActionDisabledModificationError( @@ -145,7 +145,7 @@ export class ActionsClient { */ public async get({ id }: { id: string }): Promise { const preconfiguredActionsList = this.preconfiguredActions.find( - preconfiguredAction => preconfiguredAction.id === id + (preconfiguredAction) => preconfiguredAction.id === id ); if (preconfiguredActionsList !== undefined) { return { @@ -179,7 +179,7 @@ export class ActionsClient { const mergedResult = [ ...savedObjectsActions, - ...this.preconfiguredActions.map(preconfiguredAction => ({ + ...this.preconfiguredActions.map((preconfiguredAction) => ({ id: preconfiguredAction.id, actionTypeId: preconfiguredAction.actionTypeId, name: preconfiguredAction.name, @@ -198,7 +198,7 @@ export class ActionsClient { */ public async delete({ id }: { id: string }) { if ( - this.preconfiguredActions.find(preconfiguredAction => preconfiguredAction.id === id) !== + this.preconfiguredActions.find((preconfiguredAction) => preconfiguredAction.id === id) !== undefined ) { throw new PreconfiguredActionDisabledModificationError( @@ -272,7 +272,7 @@ async function injectExtraFindData( }, }, }); - return actionResults.map(actionResult => ({ + return actionResults.map((actionResult) => ({ ...actionResult, referencedByCount: aggregationResult.aggregations[actionResult.id].doc_count, })); diff --git a/x-pack/plugins/actions/server/actions_config.ts b/x-pack/plugins/actions/server/actions_config.ts index 64d1fd7fe90ac..b15fe5b4007c5 100644 --- a/x-pack/plugins/actions/server/actions_config.ts +++ b/x-pack/plugins/actions/server/actions_config.ts @@ -66,8 +66,8 @@ function isWhitelisted({ whitelistedHosts }: ActionsConfigType, hostname: string function isWhitelistedHostnameInUri(config: ActionsConfigType, uri: string): boolean { return pipe( tryCatch(() => new URL(uri)), - map(url => url.hostname), - mapNullable(hostname => isWhitelisted(config, hostname)), + map((url) => url.hostname), + mapNullable((hostname) => isWhitelisted(config, hostname)), getOrElse(() => false) ); } diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts b/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts index 1e8cc3eda20e5..017fc73efae20 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts @@ -98,9 +98,9 @@ const fullParams: PushToServiceApiParams = { describe('normalizeMapping', () => { test('remove malicious fields', () => { const sanitizedMapping = normalizeMapping(SUPPORTED_SOURCE_FIELDS, maliciousMapping); - expect(sanitizedMapping.every(m => m.source !== '__proto__' && m.target !== '__proto__')).toBe( - true - ); + expect( + sanitizedMapping.every((m) => m.source !== '__proto__' && m.target !== '__proto__') + ).toBe(true); }); test('remove unsuppported source fields', () => { diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts b/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts index 7d69b2791f624..315d13b5aa773 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts @@ -33,7 +33,8 @@ import { SUPPORTED_SOURCE_FIELDS } from './constants'; export const normalizeMapping = (supportedFields: string[], mapping: MapRecord[]): MapRecord[] => { // Prevent prototype pollution and remove unsupported fields return mapping.filter( - m => m.source !== '__proto__' && m.target !== '__proto__' && supportedFields.includes(m.source) + (m) => + m.source !== '__proto__' && m.target !== '__proto__' && supportedFields.includes(m.source) ); }; @@ -188,8 +189,8 @@ export const prepareFieldsForTransformation = ({ defaultPipes = ['informationCreated'], }: PrepareFieldsForTransformArgs): PipedField[] => { return Object.keys(params.externalCase) - .filter(p => mapping.get(p)?.actionType != null && mapping.get(p)?.actionType !== 'nothing') - .map(p => { + .filter((p) => mapping.get(p)?.actionType != null && mapping.get(p)?.actionType !== 'nothing') + .map((p) => { const actionType = mapping.get(p)?.actionType ?? 'nothing'; return { key: p, @@ -206,7 +207,7 @@ export const transformFields = ({ currentIncident, }: TransformFieldsArgs): Record => { return fields.reduce((prev, cur) => { - const transform = flow(...cur.pipes.map(p => transformers[p])); + const transform = flow(...cur.pipes.map((p) => transformers[p])); return { ...prev, [cur.key]: transform({ @@ -227,9 +228,9 @@ export const transformFields = ({ }; export const transformComments = (comments: Comment[], pipes: string[]): Comment[] => { - return comments.map(c => ({ + return comments.map((c) => ({ ...c, - comment: flow(...pipes.map(p => transformers[p]))({ + comment: flow(...pipes.map((p) => transformers[p]))({ value: c.comment, date: c.updatedAt ?? c.createdAt, user: diff --git a/x-pack/plugins/actions/server/builtin_action_types/email.test.ts b/x-pack/plugins/actions/server/builtin_action_types/email.test.ts index 18b434e980eb9..1a24622e1cabb 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/email.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/email.test.ts @@ -121,7 +121,7 @@ describe('config validation', () => { logger: mockedLogger, configurationUtilities: { ...actionsConfigMock.create(), - isWhitelistedHostname: hostname => hostname === NODEMAILER_AOL_SERVICE_HOST, + isWhitelistedHostname: (hostname) => hostname === NODEMAILER_AOL_SERVICE_HOST, }, }); const baseConfig = { diff --git a/x-pack/plugins/actions/server/builtin_action_types/index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/index.test.ts index 9150633f06117..459ffd7667f15 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/index.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/index.test.ts @@ -44,7 +44,7 @@ beforeEach(() => { describe('action is registered', () => { test('gets registered with builtin actions', () => { const { actionTypeRegistry } = createActionTypeRegistry(); - ACTION_TYPE_IDS.forEach(ACTION_TYPE_ID => + ACTION_TYPE_IDS.forEach((ACTION_TYPE_ID) => expect(actionTypeRegistry.has(ACTION_TYPE_ID)).toEqual(true) ); }); diff --git a/x-pack/plugins/actions/server/builtin_action_types/lib/http_rersponse_retry_header.ts b/x-pack/plugins/actions/server/builtin_action_types/lib/http_rersponse_retry_header.ts index ef2462064d3a2..9fbc134491145 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/lib/http_rersponse_retry_header.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/lib/http_rersponse_retry_header.ts @@ -10,7 +10,7 @@ import { pipe } from 'fp-ts/lib/pipeable'; export function getRetryAfterIntervalFromHeaders(headers: Record): Option { return pipe( fromNullable(headers['retry-after']), - map(retryAfter => parseInt(retryAfter, 10)), - filter(retryAfter => !isNaN(retryAfter)) + map((retryAfter) => parseInt(retryAfter, 10)), + filter((retryAfter) => !isNaN(retryAfter)) ); } diff --git a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts index 1bca7c18e4e1b..b1ed3728edfae 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts @@ -58,7 +58,7 @@ describe('validateConfig()', () => { logger: mockedLogger, configurationUtilities: { ...actionsConfigMock.create(), - ensureWhitelistedUri: url => { + ensureWhitelistedUri: (url) => { expect(url).toEqual('https://events.pagerduty.com/v2/enqueue'); }, }, @@ -74,7 +74,7 @@ describe('validateConfig()', () => { logger: mockedLogger, configurationUtilities: { ...actionsConfigMock.create(), - ensureWhitelistedUri: _ => { + ensureWhitelistedUri: (_) => { throw new Error(`target url is not whitelisted`); }, }, diff --git a/x-pack/plugins/actions/server/builtin_action_types/slack.test.ts b/x-pack/plugins/actions/server/builtin_action_types/slack.test.ts index cbcd4b2954518..d1a739c2304f2 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/slack.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/slack.test.ts @@ -88,7 +88,7 @@ describe('validateActionTypeSecrets()', () => { actionType = getActionType({ configurationUtilities: { ...actionsConfigMock.create(), - ensureWhitelistedUri: url => { + ensureWhitelistedUri: (url) => { expect(url).toEqual('https://api.slack.com/'); }, }, @@ -103,7 +103,7 @@ describe('validateActionTypeSecrets()', () => { actionType = getActionType({ configurationUtilities: { ...actionsConfigMock.create(), - ensureWhitelistedHostname: url => { + ensureWhitelistedHostname: (url) => { throw new Error(`target hostname is not whitelisted`); }, }, diff --git a/x-pack/plugins/actions/server/builtin_action_types/slack.ts b/x-pack/plugins/actions/server/builtin_action_types/slack.ts index edf3e485f3c57..55c373f14cd69 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/slack.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/slack.ts @@ -121,7 +121,7 @@ async function slackExecutor( if (status === 429) { return pipe( getRetryAfterIntervalFromHeaders(headers), - map(retry => retryResultSeconds(actionId, err.message, retry)), + map((retry) => retryResultSeconds(actionId, err.message, retry)), getOrElse(() => retryResult(actionId, err.message)) ); } diff --git a/x-pack/plugins/actions/server/builtin_action_types/webhook.test.ts b/x-pack/plugins/actions/server/builtin_action_types/webhook.test.ts index d28856954cca5..6daf15208f4d9 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/webhook.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/webhook.test.ts @@ -78,7 +78,7 @@ describe('config validation', () => { }); test('config validation passes when valid methods are provided', () => { - ['post', 'put'].forEach(method => { + ['post', 'put'].forEach((method) => { const config: Record = { url: 'http://mylisteningserver:9200/endpoint', method, @@ -164,7 +164,7 @@ describe('config validation', () => { logger: mockedLogger, configurationUtilities: { ...actionsConfigMock.create(), - ensureWhitelistedUri: _ => { + ensureWhitelistedUri: (_) => { throw new Error(`target url is not whitelisted`); }, }, diff --git a/x-pack/plugins/actions/server/builtin_action_types/webhook.ts b/x-pack/plugins/actions/server/builtin_action_types/webhook.ts index 0191ff1d9dbc1..4a34fea762164 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/webhook.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/webhook.ts @@ -40,7 +40,7 @@ const secretSchemaProps = { password: schema.nullable(schema.string()), }; const SecretsSchema = schema.object(secretSchemaProps, { - validate: secrets => { + validate: (secrets) => { // user and password must be set together (or not at all) if (!secrets.password && !secrets.user) return; if (secrets.password && secrets.user) return; @@ -147,7 +147,7 @@ export async function executor( if (status === 429) { return pipe( getRetryAfterIntervalFromHeaders(responseHeaders), - map(retry => retryResultSeconds(actionId, message, retry)), + map((retry) => retryResultSeconds(actionId, message, retry)), getOrElse(() => retryResult(actionId, message)) ); } diff --git a/x-pack/plugins/actions/server/create_execute_function.ts b/x-pack/plugins/actions/server/create_execute_function.ts index db38431b02cac..a16b2f4295072 100644 --- a/x-pack/plugins/actions/server/create_execute_function.ts +++ b/x-pack/plugins/actions/server/create_execute_function.ts @@ -91,7 +91,7 @@ export function createExecuteFunction({ }); async function getActionTypeId(actionId: string): Promise { - const pcAction = preconfiguredActions.find(action => action.id === actionId); + const pcAction = preconfiguredActions.find((action) => action.id === actionId); if (pcAction) { return pcAction.actionTypeId; } diff --git a/x-pack/plugins/actions/server/lib/action_executor.ts b/x-pack/plugins/actions/server/lib/action_executor.ts index aad93a04248eb..df1b2f13a5ce4 100644 --- a/x-pack/plugins/actions/server/lib/action_executor.ts +++ b/x-pack/plugins/actions/server/lib/action_executor.ts @@ -203,7 +203,7 @@ async function getActionInfo( ): Promise { // check to see if it's a pre-configured action first const pcAction = preconfiguredActions.find( - preconfiguredAction => preconfiguredAction.id === actionId + (preconfiguredAction) => preconfiguredAction.id === actionId ); if (pcAction) { return { diff --git a/x-pack/plugins/actions/server/lib/validate_with_schema.test.ts b/x-pack/plugins/actions/server/lib/validate_with_schema.test.ts index 1ccd25664374d..03ae7a9b35a81 100644 --- a/x-pack/plugins/actions/server/lib/validate_with_schema.test.ts +++ b/x-pack/plugins/actions/server/lib/validate_with_schema.test.ts @@ -9,7 +9,7 @@ import { schema } from '@kbn/config-schema'; import { validateParams, validateConfig, validateSecrets } from './validate_with_schema'; import { ActionType, ExecutorType } from '../types'; -const executor: ExecutorType = async options => { +const executor: ExecutorType = async (options) => { return { status: 'ok', actionId: options.actionId }; }; diff --git a/x-pack/plugins/actions/server/mocks.ts b/x-pack/plugins/actions/server/mocks.ts index 4160ace50f491..09bc137da736f 100644 --- a/x-pack/plugins/actions/server/mocks.ts +++ b/x-pack/plugins/actions/server/mocks.ts @@ -33,9 +33,11 @@ const createStartMock = () => { }; const createServicesMock = () => { - const mock: jest.Mocked; - }> = { + const mock: jest.Mocked< + Services & { + savedObjectsClient: ReturnType; + } + > = { callCluster: elasticsearchServiceMock.createScopedClusterClient().callAsCurrentUser, getScopedCallCluster: jest.fn(), savedObjectsClient: savedObjectsClientMock.create(), diff --git a/x-pack/plugins/actions/server/plugin.ts b/x-pack/plugins/actions/server/plugin.ts index 75e15815d0787..3bc31be16c7cb 100644 --- a/x-pack/plugins/actions/server/plugin.ts +++ b/x-pack/plugins/actions/server/plugin.ts @@ -103,10 +103,7 @@ export class ActionsPlugin implements Plugin, Plugi private readonly preconfiguredActions: PreConfiguredAction[]; constructor(initContext: PluginInitializerContext) { - this.config = initContext.config - .create() - .pipe(first()) - .toPromise(); + this.config = initContext.config.create().pipe(first()).toPromise(); this.kibanaIndex = initContext.config.legacy.globalConfig$ .pipe( @@ -264,7 +261,7 @@ export class ActionsPlugin implements Plugin, Plugi isESOUsingEphemeralEncryptionKey: isESOUsingEphemeralEncryptionKey!, preconfiguredActions, }), - isActionTypeEnabled: id => { + isActionTypeEnabled: (id) => { return this.actionTypeRegistry!.isActionTypeEnabled(id); }, isActionExecutable: (actionId: string, actionTypeId: string) => { @@ -293,7 +290,7 @@ export class ActionsPlugin implements Plugin, Plugi savedObjects: SavedObjectsServiceStart, elasticsearch: ElasticsearchServiceStart ): (request: KibanaRequest) => Services { - return request => ({ + return (request) => ({ callCluster: elasticsearch.legacy.client.asScoped(request).callAsCurrentUser, savedObjectsClient: savedObjects.getScopedClient(request), getScopedCallCluster(clusterClient: IClusterClient) { diff --git a/x-pack/plugins/actions/server/routes/create.ts b/x-pack/plugins/actions/server/routes/create.ts index 7f239bda41a60..e9d7c2d8d00eb 100644 --- a/x-pack/plugins/actions/server/routes/create.ts +++ b/x-pack/plugins/actions/server/routes/create.ts @@ -34,7 +34,7 @@ export const createActionRoute = (router: IRouter, licenseState: ILicenseState) tags: ['access:actions-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest>, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/delete.ts b/x-pack/plugins/actions/server/routes/delete.ts index b76aa27fa5d9b..d1f9693e1c8d4 100644 --- a/x-pack/plugins/actions/server/routes/delete.ts +++ b/x-pack/plugins/actions/server/routes/delete.ts @@ -35,7 +35,7 @@ export const deleteActionRoute = (router: IRouter, licenseState: ILicenseState) tags: ['access:actions-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/execute.ts b/x-pack/plugins/actions/server/routes/execute.ts index 79d3c1dfb8d22..4093ed4511939 100644 --- a/x-pack/plugins/actions/server/routes/execute.ts +++ b/x-pack/plugins/actions/server/routes/execute.ts @@ -41,7 +41,7 @@ export const executeActionRoute = ( tags: ['access:actions-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, TypeOf>, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/get.ts b/x-pack/plugins/actions/server/routes/get.ts index 30e4289ed30c8..09c47c94029e7 100644 --- a/x-pack/plugins/actions/server/routes/get.ts +++ b/x-pack/plugins/actions/server/routes/get.ts @@ -30,7 +30,7 @@ export const getActionRoute = (router: IRouter, licenseState: ILicenseState) => tags: ['access:actions-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/get_all.ts b/x-pack/plugins/actions/server/routes/get_all.ts index f6745427f74c7..6d02872ea64e1 100644 --- a/x-pack/plugins/actions/server/routes/get_all.ts +++ b/x-pack/plugins/actions/server/routes/get_all.ts @@ -23,7 +23,7 @@ export const getAllActionRoute = (router: IRouter, licenseState: ILicenseState) tags: ['access:actions-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/list_action_types.ts b/x-pack/plugins/actions/server/routes/list_action_types.ts index 50bc7405f4d6b..bc91d4854e638 100644 --- a/x-pack/plugins/actions/server/routes/list_action_types.ts +++ b/x-pack/plugins/actions/server/routes/list_action_types.ts @@ -23,7 +23,7 @@ export const listActionTypesRoute = (router: IRouter, licenseState: ILicenseStat tags: ['access:actions-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/routes/update.ts b/x-pack/plugins/actions/server/routes/update.ts index 45ced77be922e..efad39c1cd453 100644 --- a/x-pack/plugins/actions/server/routes/update.ts +++ b/x-pack/plugins/actions/server/routes/update.ts @@ -37,7 +37,7 @@ export const updateActionRoute = (router: IRouter, licenseState: ILicenseState) tags: ['access:actions-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, TypeOf>, res: KibanaResponseFactory diff --git a/x-pack/plugins/actions/server/usage/task.ts b/x-pack/plugins/actions/server/usage/task.ts index ed0d876ed0208..862a170ca1343 100644 --- a/x-pack/plugins/actions/server/usage/task.ts +++ b/x-pack/plugins/actions/server/usage/task.ts @@ -84,7 +84,7 @@ export function telemetryTaskRunner(logger: Logger, core: CoreSetup, kibanaIndex runAt: getNextMidnight(), }; }) - .catch(errMsg => { + .catch((errMsg) => { logger.warn(`Error executing actions telemetry task: ${errMsg}`); return { state: {}, @@ -97,8 +97,5 @@ export function telemetryTaskRunner(logger: Logger, core: CoreSetup, kibanaIndex } function getNextMidnight() { - return moment() - .add(1, 'd') - .startOf('d') - .toDate(); + return moment().add(1, 'd').startOf('d').toDate(); } diff --git a/x-pack/plugins/advanced_ui_actions/public/components/action_wizard/action_wizard.tsx b/x-pack/plugins/advanced_ui_actions/public/components/action_wizard/action_wizard.tsx index 4d14226777a0b..ccadf60426edf 100644 --- a/x-pack/plugins/advanced_ui_actions/public/components/action_wizard/action_wizard.tsx +++ b/x-pack/plugins/advanced_ui_actions/public/components/action_wizard/action_wizard.tsx @@ -75,7 +75,7 @@ export const ActionWizard: React.FC = ({ }} context={context} config={config} - onConfigChange={newConfig => { + onConfigChange={(newConfig) => { onConfigChange(newConfig); }} /> @@ -86,7 +86,7 @@ export const ActionWizard: React.FC = ({ { + onActionFactorySelected={(actionFactory) => { onActionFactoryChange(actionFactory); }} /> @@ -179,7 +179,7 @@ const ActionFactorySelector: React.FC = ({ {[...actionFactories] .sort((f1, f2) => f2.order - f1.order) - .map(actionFactory => ( + .map((actionFactory) => ( ({ value: id, text: title }))} value={config.dashboardId} - onChange={e => { + onChange={(e) => { props.onConfig({ ...config, dashboardId: e.target.value }); }} /> @@ -122,7 +122,7 @@ function UrlDrilldownCollectConfig(props: CollectConfigProps placeholder="Enter URL" name="url" value={config.url} - onChange={event => props.onConfig({ ...config, url: event.target.value })} + onChange={(event) => props.onConfig({ ...config, url: event.target.value })} /> @@ -184,13 +184,13 @@ export function Demo({ actionFactories }: { actionFactories: Array { + onConfigChange={(newConfig) => { setState({ ...state, config: newConfig, }); }} - onActionFactoryChange={newActionFactory => { + onActionFactoryChange={(newActionFactory) => { changeActionFactory(newActionFactory); }} currentActionFactory={state.currentActionFactory} diff --git a/x-pack/plugins/advanced_ui_actions/public/custom_time_range_action.test.ts b/x-pack/plugins/advanced_ui_actions/public/custom_time_range_action.test.ts index 10860fe471a3b..e82ebd9a5a4ad 100644 --- a/x-pack/plugins/advanced_ui_actions/public/custom_time_range_action.test.ts +++ b/x-pack/plugins/advanced_ui_actions/public/custom_time_range_action.test.ts @@ -34,7 +34,7 @@ const createOpenModalMock = () => { return mock; }; -test('Custom time range action prevents embeddable from using container time', async done => { +test('Custom time range action prevents embeddable from using container time', async (done) => { const container = new TimeRangeContainer( { timeRange: { from: 'now-15m', to: 'now' }, @@ -98,7 +98,7 @@ test('Custom time range action prevents embeddable from using container time', a container.updateInput({ timeRange: { from: 'now-30m', to: 'now-1m' } }); }); -test('Removing custom time range action resets embeddable back to container time', async done => { +test('Removing custom time range action resets embeddable back to container time', async (done) => { const container = new TimeRangeContainer( { timeRange: { from: 'now-15m', to: 'now' }, @@ -172,7 +172,7 @@ test('Removing custom time range action resets embeddable back to container time container.updateInput({ timeRange: { from: 'now-10m', to: 'now-5m' } }); }); -test('Cancelling custom time range action leaves state alone', async done => { +test('Cancelling custom time range action leaves state alone', async (done) => { const container = new TimeRangeContainer( { timeRange: { from: 'now-15m', to: 'now' }, diff --git a/x-pack/plugins/advanced_ui_actions/public/custom_time_range_badge.test.ts b/x-pack/plugins/advanced_ui_actions/public/custom_time_range_badge.test.ts index 3bf763470f002..49fe305e3602b 100644 --- a/x-pack/plugins/advanced_ui_actions/public/custom_time_range_badge.test.ts +++ b/x-pack/plugins/advanced_ui_actions/public/custom_time_range_badge.test.ts @@ -14,7 +14,7 @@ import { CustomTimeRangeBadge } from './custom_time_range_badge'; import { ReactElement } from 'react'; import { nextTick } from 'test_utils/enzyme_helpers'; -test('Removing custom time range from badge resets embeddable back to container time', async done => { +test('Removing custom time range from badge resets embeddable back to container time', async (done) => { const container = new TimeRangeContainer( { timeRange: { from: 'now-15m', to: 'now' }, diff --git a/x-pack/plugins/advanced_ui_actions/public/customize_time_range_modal.tsx b/x-pack/plugins/advanced_ui_actions/public/customize_time_range_modal.tsx index 9880a2b811f8b..96e2a7e1a8a0c 100644 --- a/x-pack/plugins/advanced_ui_actions/public/customize_time_range_modal.tsx +++ b/x-pack/plugins/advanced_ui_actions/public/customize_time_range_modal.tsx @@ -55,7 +55,7 @@ export class CustomizeTimeRangeModal extends Component { - this.setState(prevState => ({ + this.setState((prevState) => ({ inheritTimeRange: !prevState.inheritTimeRange, })); }; diff --git a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.test.ts b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.test.ts index b7f1b36f8f358..516b1f3cd2773 100644 --- a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.test.ts +++ b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.test.ts @@ -291,7 +291,7 @@ describe('DynamicActionManager', () => { expect(manager.state.get().events.length).toBe(0); - const promise = manager.createEvent(action, ['VALUE_CLICK_TRIGGER']).catch(e => e); + const promise = manager.createEvent(action, ['VALUE_CLICK_TRIGGER']).catch((e) => e); expect(manager.state.get().events.length).toBe(1); @@ -378,7 +378,7 @@ describe('DynamicActionManager', () => { expect(manager.state.get().events.length).toBe(0); - const promise = manager.createEvent(action, ['VALUE_CLICK_TRIGGER']).catch(e => e); + const promise = manager.createEvent(action, ['VALUE_CLICK_TRIGGER']).catch((e) => e); expect(manager.state.get().events.length).toBe(1); @@ -502,7 +502,7 @@ describe('DynamicActionManager', () => { const promise = manager .updateEvent(event3.eventId, action, ['VALUE_CLICK_TRIGGER']) - .catch(e => e); + .catch((e) => e); expect(manager.state.get().events[0].action.name).toBe('foo'); diff --git a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.ts b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.ts index df214bfe80cc7..3e37bac0a17af 100644 --- a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.ts +++ b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager.ts @@ -109,7 +109,7 @@ export class DynamicActionManager { for (const event of this.ui.get().events) this.killAction(event); for (const event of events) this.reviveAction(event); this.ui.transitions.finishFetching(events); - })().catch(error => { + })().catch((error) => { /* eslint-disable */ console.log('Dynamic action manager storage reload failed.'); console.error(error); diff --git a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager_state.ts b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager_state.ts index 61e8604baa913..9540e52b440cf 100644 --- a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager_state.ts +++ b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_manager_state.ts @@ -55,9 +55,9 @@ export const defaultState: State = { }; export const transitions: Transitions = { - startFetching: state => () => ({ ...state, isFetchingEvents: true }), + startFetching: (state) => () => ({ ...state, isFetchingEvents: true }), - finishFetching: state => events => ({ + finishFetching: (state) => (events) => ({ ...state, isFetchingEvents: false, fetchCount: state.fetchCount + 1, @@ -65,24 +65,24 @@ export const transitions: Transitions = { events, }), - failFetching: state => ({ message }) => ({ + failFetching: (state) => ({ message }) => ({ ...state, isFetchingEvents: false, fetchCount: state.fetchCount + 1, fetchError: { message }, }), - addEvent: state => (event: SerializedEvent) => ({ + addEvent: (state) => (event: SerializedEvent) => ({ ...state, events: [...state.events, event], }), - removeEvent: state => (eventId: string) => ({ + removeEvent: (state) => (eventId: string) => ({ ...state, - events: state.events ? state.events.filter(event => event.eventId !== eventId) : state.events, + events: state.events ? state.events.filter((event) => event.eventId !== eventId) : state.events, }), - replaceEvent: state => event => { + replaceEvent: (state) => (event) => { const index = state.events.findIndex(({ eventId }) => eventId === event.eventId); if (index === -1) return state; @@ -94,5 +94,5 @@ export const transitions: Transitions = { }; export const selectors: Selectors = { - getEvent: state => eventId => state.events.find(event => event.eventId === eventId) || null, + getEvent: (state) => (eventId) => state.events.find((event) => event.eventId === eventId) || null, }; diff --git a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_storage.ts b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_storage.ts index e40441e67f033..205245e73c690 100644 --- a/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_storage.ts +++ b/x-pack/plugins/advanced_ui_actions/public/dynamic_actions/dynamic_action_storage.ts @@ -38,7 +38,7 @@ export abstract class AbstractActionStorage implements ActionStorage { public async read(eventId: string): Promise { const events = await this.list(); - const event = events.find(ev => ev.eventId === eventId); + const event = events.find((ev) => ev.eventId === eventId); if (!event) throw new Error(`Event [eventId = ${eventId}] not found.`); return event; } @@ -59,7 +59,7 @@ export class MemoryActionStorage extends AbstractActionStorage { } public async list() { - return this.events.map(event => ({ ...event })); + return this.events.map((event) => ({ ...event })); } public async create(event: SerializedEvent) { @@ -73,7 +73,7 @@ export class MemoryActionStorage extends AbstractActionStorage { } public async remove(eventId: string) { - const index = this.events.findIndex(ev => eventId === ev.eventId); + const index = this.events.findIndex((ev) => eventId === ev.eventId); if (index < 0) throw new Error(`Event [eventId = ${eventId}] not found`); this.events = [...this.events.slice(0, index), ...this.events.slice(index + 1)]; } diff --git a/x-pack/plugins/advanced_ui_actions/public/services/ui_actions_service_enhancements.ts b/x-pack/plugins/advanced_ui_actions/public/services/ui_actions_service_enhancements.ts index 8befbf43d3c6a..b7bdced228584 100644 --- a/x-pack/plugins/advanced_ui_actions/public/services/ui_actions_service_enhancements.ts +++ b/x-pack/plugins/advanced_ui_actions/public/services/ui_actions_service_enhancements.ts @@ -82,13 +82,13 @@ export class UiActionsServiceEnhancements { getDisplayName, getIconType: () => euiIcon, isCompatible: async () => true, - create: serializedAction => ({ + create: (serializedAction) => ({ id: '', type: factoryId, getIconType: () => euiIcon, getDisplayName: () => serializedAction.name, - execute: async context => await execute(serializedAction.config, context), - getHref: getHref ? async context => getHref(serializedAction.config, context) : undefined, + execute: async (context) => await execute(serializedAction.config, context), + getHref: getHref ? async (context) => getHref(serializedAction.config, context) : undefined, }), } as ActionFactoryDefinition; diff --git a/x-pack/plugins/alerting/common/date_from_string.ts b/x-pack/plugins/alerting/common/date_from_string.ts index 831891fc12d92..22c18b08d0ff6 100644 --- a/x-pack/plugins/alerting/common/date_from_string.ts +++ b/x-pack/plugins/alerting/common/date_from_string.ts @@ -17,10 +17,10 @@ export const DateFromString = new t.Type( // validate this is a string t.string.validate(valueToDecode, context), // decode - value => { + (value) => { const decoded = new Date(value); return isNaN(decoded.getTime()) ? t.failure(valueToDecode, context) : t.success(decoded); } ), - valueToEncode => valueToEncode.toISOString() + (valueToEncode) => valueToEncode.toISOString() ); diff --git a/x-pack/plugins/alerting/public/alert_api.ts b/x-pack/plugins/alerting/public/alert_api.ts index 1df39e9f38b1d..ee9432885d671 100644 --- a/x-pack/plugins/alerting/public/alert_api.ts +++ b/x-pack/plugins/alerting/public/alert_api.ts @@ -26,7 +26,7 @@ export async function loadAlertType({ http: HttpSetup; id: AlertType['id']; }): Promise { - const maybeAlertType = findFirst(type => type.id === id)( + const maybeAlertType = findFirst((type) => type.id === id)( await http.get(`${BASE_ALERT_API_PATH}/types`) ); if (isNone(maybeAlertType)) { diff --git a/x-pack/plugins/alerting/server/alerts_client.test.ts b/x-pack/plugins/alerting/server/alerts_client.test.ts index 93b98f6a0fe03..fa86c27651136 100644 --- a/x-pack/plugins/alerting/server/alerts_client.test.ts +++ b/x-pack/plugins/alerting/server/alerts_client.test.ts @@ -2805,7 +2805,7 @@ describe('update()', () => { expect(taskManager.runNow).not.toHaveBeenCalled(); }); - test('updating the alert should not wait for the rerun the task to complete', async done => { + test('updating the alert should not wait for the rerun the task to complete', async (done) => { const alertId = uuid.v4(); const taskId = uuid.v4(); diff --git a/x-pack/plugins/alerting/server/alerts_client.ts b/x-pack/plugins/alerting/server/alerts_client.ts index 01687f33f631d..e43939e2f44c3 100644 --- a/x-pack/plugins/alerting/server/alerts_client.ts +++ b/x-pack/plugins/alerting/server/alerts_client.ts @@ -417,9 +417,7 @@ export class AlertsClient { } try { - const apiKeyId = Buffer.from(apiKey, 'base64') - .toString() - .split(':')[0]; + const apiKeyId = Buffer.from(apiKey, 'base64').toString().split(':')[0]; const response = await this.invalidateAPIKey({ id: apiKeyId }); if (response.apiKeysEnabled === true && response.result.error_count > 0) { this.logger.error(`Failed to invalidate API Key [id="${apiKeyId}"]`); @@ -603,7 +601,7 @@ export class AlertsClient { references: SavedObjectReference[] ) { return actions.map((action, i) => { - const reference = references.find(ref => ref.name === action.actionRef); + const reference = references.find((ref) => ref.name === action.actionRef); if (!reference) { throw new Error(`Reference ${action.actionRef} not found`); } @@ -648,10 +646,10 @@ export class AlertsClient { private validateActions(alertType: AlertType, actions: NormalizedAlertAction[]): void { const { actionGroups: alertTypeActionGroups } = alertType; - const usedAlertActionGroups = actions.map(action => action.group); + const usedAlertActionGroups = actions.map((action) => action.group); const availableAlertTypeActionGroups = new Set(pluck(alertTypeActionGroups, 'id')); const invalidActionGroups = usedAlertActionGroups.filter( - group => !availableAlertTypeActionGroups.has(group) + (group) => !availableAlertTypeActionGroups.has(group) ); if (invalidActionGroups.length) { throw Boom.badRequest( @@ -672,7 +670,7 @@ export class AlertsClient { // map preconfigured actions for (const alertAction of alertActions) { const action = this.preconfiguredActions.find( - preconfiguredAction => preconfiguredAction.id === alertAction.id + (preconfiguredAction) => preconfiguredAction.id === alertAction.id ); if (action !== undefined) { actionMap.set(action.id, action); @@ -683,12 +681,12 @@ export class AlertsClient { const actionIds = [ ...new Set( alertActions - .filter(alertAction => !actionMap.has(alertAction.id)) - .map(alertAction => alertAction.id) + .filter((alertAction) => !actionMap.has(alertAction.id)) + .map((alertAction) => alertAction.id) ), ]; if (actionIds.length > 0) { - const bulkGetOpts = actionIds.map(id => ({ id, type: 'action' })); + const bulkGetOpts = actionIds.map((id) => ({ id, type: 'action' })); const bulkGetResult = await this.savedObjectsClient.bulkGet(bulkGetOpts); for (const action of bulkGetResult.saved_objects) { @@ -712,7 +710,7 @@ export class AlertsClient { const actionMapValue = actionMap.get(id); // if action is a save object, than actionTypeId should be under attributes property // if action is a preconfigured, than actionTypeId is the action property - const actionTypeId = actionIds.find(actionId => actionId === id) + const actionTypeId = actionIds.find((actionId) => actionId === id) ? (actionMapValue as SavedObject>).attributes.actionTypeId : (actionMapValue as RawAlertAction).actionTypeId; return { diff --git a/x-pack/plugins/alerting/server/lib/types.ts b/x-pack/plugins/alerting/server/lib/types.ts index 6df593ab17ce8..22464aca21f9b 100644 --- a/x-pack/plugins/alerting/server/lib/types.ts +++ b/x-pack/plugins/alerting/server/lib/types.ts @@ -16,10 +16,10 @@ export const DateFromString = new t.Type( // validate this is a string t.string.validate(valueToDecode, context), // decode - value => { + (value) => { const decoded = new Date(value); return isNaN(decoded.getTime()) ? t.failure(valueToDecode, context) : t.success(decoded); } ), - valueToEncode => valueToEncode.toISOString() + (valueToEncode) => valueToEncode.toISOString() ); diff --git a/x-pack/plugins/alerting/server/plugin.ts b/x-pack/plugins/alerting/server/plugin.ts index 4d64a1cd9fcf0..378394e8d36f3 100644 --- a/x-pack/plugins/alerting/server/plugin.ts +++ b/x-pack/plugins/alerting/server/plugin.ts @@ -270,7 +270,7 @@ export class AlertingPlugin { savedObjects: SavedObjectsServiceStart, elasticsearch: ElasticsearchServiceStart ): (request: KibanaRequest) => Services { - return request => ({ + return (request) => ({ callCluster: elasticsearch.legacy.client.asScoped(request).callAsCurrentUser, savedObjectsClient: this.getScopedClientWithAlertSavedObjectType(savedObjects, request), getScopedCallCluster(clusterClient: IClusterClient) { diff --git a/x-pack/plugins/alerting/server/routes/create.ts b/x-pack/plugins/alerting/server/routes/create.ts index 0c038b6490483..cc3b7d48162e3 100644 --- a/x-pack/plugins/alerting/server/routes/create.ts +++ b/x-pack/plugins/alerting/server/routes/create.ts @@ -52,7 +52,7 @@ export const createAlertRoute = (router: IRouter, licenseState: LicenseState) => }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/delete.ts b/x-pack/plugins/alerting/server/routes/delete.ts index 7f6600b1ec48e..f5a7add632edc 100644 --- a/x-pack/plugins/alerting/server/routes/delete.ts +++ b/x-pack/plugins/alerting/server/routes/delete.ts @@ -31,7 +31,7 @@ export const deleteAlertRoute = (router: IRouter, licenseState: LicenseState) => tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/disable.ts b/x-pack/plugins/alerting/server/routes/disable.ts index c7e7b1001f82d..e1eb089cf4e85 100644 --- a/x-pack/plugins/alerting/server/routes/disable.ts +++ b/x-pack/plugins/alerting/server/routes/disable.ts @@ -31,7 +31,7 @@ export const disableAlertRoute = (router: IRouter, licenseState: LicenseState) = tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/enable.ts b/x-pack/plugins/alerting/server/routes/enable.ts index 3ed4fb0739d3d..90e8f552898d9 100644 --- a/x-pack/plugins/alerting/server/routes/enable.ts +++ b/x-pack/plugins/alerting/server/routes/enable.ts @@ -33,7 +33,7 @@ export const enableAlertRoute = (router: IRouter, licenseState: LicenseState) => }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/find.ts b/x-pack/plugins/alerting/server/routes/find.ts index c723419a965c5..3de95c9580cd4 100644 --- a/x-pack/plugins/alerting/server/routes/find.ts +++ b/x-pack/plugins/alerting/server/routes/find.ts @@ -53,7 +53,7 @@ export const findAlertRoute = (router: IRouter, licenseState: LicenseState) => { tags: ['access:alerting-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/get.ts b/x-pack/plugins/alerting/server/routes/get.ts index 6d652d1304f65..cd78e7fbacddb 100644 --- a/x-pack/plugins/alerting/server/routes/get.ts +++ b/x-pack/plugins/alerting/server/routes/get.ts @@ -31,7 +31,7 @@ export const getAlertRoute = (router: IRouter, licenseState: LicenseState) => { tags: ['access:alerting-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/get_alert_state.ts b/x-pack/plugins/alerting/server/routes/get_alert_state.ts index 552bfea22a42b..a5cb14154db67 100644 --- a/x-pack/plugins/alerting/server/routes/get_alert_state.ts +++ b/x-pack/plugins/alerting/server/routes/get_alert_state.ts @@ -31,7 +31,7 @@ export const getAlertStateRoute = (router: IRouter, licenseState: LicenseState) tags: ['access:alerting-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/health.ts b/x-pack/plugins/alerting/server/routes/health.ts index bfdbc95a7d2da..98465055e88de 100644 --- a/x-pack/plugins/alerting/server/routes/health.ts +++ b/x-pack/plugins/alerting/server/routes/health.ts @@ -37,7 +37,7 @@ export function healthRoute( path: '/api/alert/_health', validate: false, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/list_alert_types.ts b/x-pack/plugins/alerting/server/routes/list_alert_types.ts index 7ab64cf932051..f5b4e3263f341 100644 --- a/x-pack/plugins/alerting/server/routes/list_alert_types.ts +++ b/x-pack/plugins/alerting/server/routes/list_alert_types.ts @@ -24,7 +24,7 @@ export const listAlertTypesRoute = (router: IRouter, licenseState: LicenseState) tags: ['access:alerting-read'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/mute_all.ts b/x-pack/plugins/alerting/server/routes/mute_all.ts index d1b4322bd1ccb..b43a1ec30ed1f 100644 --- a/x-pack/plugins/alerting/server/routes/mute_all.ts +++ b/x-pack/plugins/alerting/server/routes/mute_all.ts @@ -31,7 +31,7 @@ export const muteAllAlertRoute = (router: IRouter, licenseState: LicenseState) = tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/mute_instance.ts b/x-pack/plugins/alerting/server/routes/mute_instance.ts index fbdda62836d74..c0c69fe9653da 100644 --- a/x-pack/plugins/alerting/server/routes/mute_instance.ts +++ b/x-pack/plugins/alerting/server/routes/mute_instance.ts @@ -32,7 +32,7 @@ export const muteAlertInstanceRoute = (router: IRouter, licenseState: LicenseSta tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/unmute_all.ts b/x-pack/plugins/alerting/server/routes/unmute_all.ts index e09f2fe6b8b93..d4b6e8b7d61b1 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_all.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_all.ts @@ -31,7 +31,7 @@ export const unmuteAllAlertRoute = (router: IRouter, licenseState: LicenseState) tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/unmute_instance.ts b/x-pack/plugins/alerting/server/routes/unmute_instance.ts index 64ba22dc3ea0b..97ccd8f0adce7 100644 --- a/x-pack/plugins/alerting/server/routes/unmute_instance.ts +++ b/x-pack/plugins/alerting/server/routes/unmute_instance.ts @@ -32,7 +32,7 @@ export const unmuteAlertInstanceRoute = (router: IRouter, licenseState: LicenseS tags: ['access:alerting-all'], }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/update.ts b/x-pack/plugins/alerting/server/routes/update.ts index 7f07749311598..23fea7dc4002f 100644 --- a/x-pack/plugins/alerting/server/routes/update.ts +++ b/x-pack/plugins/alerting/server/routes/update.ts @@ -54,7 +54,7 @@ export const updateAlertRoute = (router: IRouter, licenseState: LicenseState) => }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, TypeOf>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/routes/update_api_key.ts b/x-pack/plugins/alerting/server/routes/update_api_key.ts index 9d0c34fc1a015..9d88201d7cd43 100644 --- a/x-pack/plugins/alerting/server/routes/update_api_key.ts +++ b/x-pack/plugins/alerting/server/routes/update_api_key.ts @@ -33,7 +33,7 @@ export const updateApiKeyRoute = (router: IRouter, licenseState: LicenseState) = }, }, handleDisabledApiKeysError( - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, unknown, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts b/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts index 16fadc8b06cd5..61bbab50b1222 100644 --- a/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts +++ b/x-pack/plugins/alerting/server/task_runner/create_execution_handler.ts @@ -52,7 +52,7 @@ export function createExecutionHandler({ } const actions = alertActions .filter(({ group }) => group === actionGroup) - .map(action => { + .map((action) => { return { ...action, params: transformActionParams({ diff --git a/x-pack/plugins/alerting/server/task_runner/task_runner.ts b/x-pack/plugins/alerting/server/task_runner/task_runner.ts index a36152fa17544..0831163d1d326 100644 --- a/x-pack/plugins/alerting/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerting/server/task_runner/task_runner.ts @@ -106,8 +106,8 @@ export class TaskRunner { references: SavedObject['references'] ) { // Inject ids into actions - const actionsWithIds = actions.map(action => { - const actionReference = references.find(obj => obj.name === action.actionRef); + const actionsWithIds = actions.map((action) => { + const actionReference = references.find((obj) => obj.name === action.actionRef); if (!actionReference) { throw new Error(`Action reference "${action.actionRef}" not found in alert id: ${alertId}`); } @@ -166,7 +166,7 @@ export class TaskRunner { const alertInstances = mapValues( alertRawInstances, - rawAlertInstance => new AlertInstance(rawAlertInstance) + (rawAlertInstance) => new AlertInstance(rawAlertInstance) ); const originalAlertInstanceIds = Object.keys(alertInstances); @@ -259,7 +259,7 @@ export class TaskRunner { alertTypeState: updatedAlertTypeState || undefined, alertInstances: mapValues( instancesWithScheduledActions, - alertInstance => alertInstance.toRaw() + (alertInstance) => alertInstance.toRaw() ), }; } @@ -354,7 +354,7 @@ export class TaskRunner { }; } ), - runAt: resolveErr(runAt, err => { + runAt: resolveErr(runAt, (err) => { return isAlertSavedObjectNotFoundError(err, alertId) ? undefined : getNextRunAt( diff --git a/x-pack/plugins/alerting/server/test_utils/index.ts b/x-pack/plugins/alerting/server/test_utils/index.ts index e8089984a786a..de52e0c8b7264 100644 --- a/x-pack/plugins/alerting/server/test_utils/index.ts +++ b/x-pack/plugins/alerting/server/test_utils/index.ts @@ -14,7 +14,7 @@ interface Resolvable { */ export function resolvable(): Promise & Resolvable { let resolve: (arg: T) => void; - return Object.assign(new Promise(r => (resolve = r)), { + return Object.assign(new Promise((r) => (resolve = r)), { resolve(arg: T) { return setTimeout(() => resolve(arg), 0); }, diff --git a/x-pack/plugins/alerting/server/usage/task.ts b/x-pack/plugins/alerting/server/usage/task.ts index ab62d81d44f8a..395f0c107c984 100644 --- a/x-pack/plugins/alerting/server/usage/task.ts +++ b/x-pack/plugins/alerting/server/usage/task.ts @@ -89,7 +89,7 @@ export function telemetryTaskRunner(logger: Logger, core: CoreSetup, kibanaIndex runAt: getNextMidnight(), }; }) - .catch(errMsg => { + .catch((errMsg) => { logger.warn(`Error executing alerting telemetry task: ${errMsg}`); return { state: {}, @@ -102,8 +102,5 @@ export function telemetryTaskRunner(logger: Logger, core: CoreSetup, kibanaIndex } function getNextMidnight() { - return moment() - .add(1, 'd') - .startOf('d') - .toDate(); + return moment().add(1, 'd').startOf('d').toDate(); } diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts index eff5ef2567784..32a5845a7e65b 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/lib/date_range_info.test.ts @@ -13,7 +13,7 @@ const BaseDate = Date.parse('2000-01-01T00:00:00Z'); const Dates: string[] = []; // array of date strings, starting at 2000-01-01T00:00:00Z, decreasing by 1 minute -times(10, index => Dates.push(new Date(BaseDate - index * 1000 * 60).toISOString())); +times(10, (index) => Dates.push(new Date(BaseDate - index * 1000 * 60).toISOString())); const DEFAULT_WINDOW_MINUTES = 5; @@ -215,7 +215,7 @@ function asReadableDateRangeInfo(info: DateRangeInfo) { return { dateStart: info.dateStart, dateStop_: info.dateEnd, - ranges: info.dateRanges.map(dateRange => { + ranges: info.dateRanges.map((dateRange) => { return { f: new Date(dateRange.from).toISOString(), t: new Date(dateRange.to).toISOString(), diff --git a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/routes/indices.ts b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/routes/indices.ts index ebcf6b4f0e45a..297009b5a69e8 100644 --- a/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/routes/indices.ts +++ b/x-pack/plugins/alerting_builtins/server/alert_types/index_threshold/routes/indices.ts @@ -110,7 +110,7 @@ async function getIndicesFromPattern( return []; } - return (response.aggregations as IndiciesAggregation).indices.buckets.map(bucket => bucket.key); + return (response.aggregations as IndiciesAggregation).indices.buckets.map((bucket) => bucket.key); } async function getAliasesFromPattern( diff --git a/x-pack/plugins/apm/common/agent_configuration/all_option.ts b/x-pack/plugins/apm/common/agent_configuration/all_option.ts index 7b1c7bdda97a7..0ae267154797a 100644 --- a/x-pack/plugins/apm/common/agent_configuration/all_option.ts +++ b/x-pack/plugins/apm/common/agent_configuration/all_option.ts @@ -13,7 +13,7 @@ export const ALL_OPTION_VALUE = 'ALL_OPTION_VALUE'; export function getOptionLabel(value: string | undefined) { if (value === undefined || value === ALL_OPTION_VALUE) { return i18n.translate('xpack.apm.agentConfig.allOptionLabel', { - defaultMessage: 'All' + defaultMessage: 'All', }); } diff --git a/x-pack/plugins/apm/common/agent_configuration/amount_and_unit.ts b/x-pack/plugins/apm/common/agent_configuration/amount_and_unit.ts index cd64b3025a65b..49a3ce6704116 100644 --- a/x-pack/plugins/apm/common/agent_configuration/amount_and_unit.ts +++ b/x-pack/plugins/apm/common/agent_configuration/amount_and_unit.ts @@ -17,7 +17,7 @@ export function amountAndUnitToObject(value: string): AmountAndUnit { export function amountAndUnitToString({ amount, - unit + unit, }: Omit & { amount: string | number }) { return `${amount}${unit}`; } diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.test.ts index c2a3be784f661..4e16625899785 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.test.ts @@ -12,8 +12,8 @@ describe('agentConfigurationIntakeRt', () => { const config = { service: { name: 'my-service', environment: 'my-environment' }, settings: { - transaction_sample_rate: '0.5' - } + transaction_sample_rate: '0.5', + }, }; expect(isConfigValid(config)).toBe(true); @@ -23,8 +23,8 @@ describe('agentConfigurationIntakeRt', () => { const config = { service: {}, settings: { - transaction_sample_rate: 0.5 - } + transaction_sample_rate: 0.5, + }, }; expect(isConfigValid(config)).toBe(false); @@ -34,8 +34,8 @@ describe('agentConfigurationIntakeRt', () => { const config = { service: { name: 'my-service', environment: 'my-environment' }, settings: { - my_unknown_setting: '0.5' - } + my_unknown_setting: '0.5', + }, }; expect(isConfigValid(config)).toBe(true); @@ -45,8 +45,8 @@ describe('agentConfigurationIntakeRt', () => { const config = { service: { name: 'my-service', environment: 'my-environment' }, settings: { - my_unknown_setting: false - } + my_unknown_setting: false, + }, }; expect(isConfigValid(config)).toBe(false); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.ts index e903a56486b6e..a2a22ae8cf1d7 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/agent_configuration_intake_rt.ts @@ -18,18 +18,18 @@ const knownSettings = settingDefinitions.reduce< export const serviceRt = t.partial({ name: t.string, - environment: t.string + environment: t.string, }); export const settingsRt = t.intersection([ t.record(t.string, t.string), - t.partial(knownSettings) + t.partial(knownSettings), ]); export const agentConfigurationIntakeRt = t.intersection([ t.partial({ agent_name: t.string }), t.type({ service: serviceRt, - settings: settingsRt - }) + settings: settingsRt, + }), ]); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/boolean_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/boolean_rt.test.ts index d4dfbec2344fe..c430ee571287f 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/boolean_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/boolean_rt.test.ts @@ -9,7 +9,7 @@ import { isRight } from 'fp-ts/lib/Either'; describe('booleanRt', () => { describe('it should not accept', () => { - [undefined, null, '', 0, 'foo', true, false].map(input => { + [undefined, null, '', 0, 'foo', true, false].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(booleanRt.decode(input))).toBe(false); }); @@ -17,7 +17,7 @@ describe('booleanRt', () => { }); describe('it should accept', () => { - ['true', 'false'].map(input => { + ['true', 'false'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(booleanRt.decode(input))).toBe(true); }); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.test.ts index 4d786605b00c7..468f4b3842cde 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.test.ts @@ -12,7 +12,7 @@ describe('bytesRt', () => { describe('must accept any amount and unit', () => { const bytesRt = getBytesRt({}); describe('it should not accept', () => { - ['mb', 1, '1', '5gb', '6tb'].map(input => { + ['mb', 1, '1', '5gb', '6tb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(false); }); @@ -20,7 +20,7 @@ describe('bytesRt', () => { }); describe('it should accept', () => { - ['-1b', '0mb', '1b', '2kb', '3mb', '1000mb'].map(input => { + ['-1b', '0mb', '1b', '2kb', '3mb', '1000mb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(true); }); @@ -29,11 +29,11 @@ describe('bytesRt', () => { }); describe('must be at least 0b', () => { const bytesRt = getBytesRt({ - min: '0b' + min: '0b', }); describe('it should not accept', () => { - ['mb', '-1kb', '5gb', '6tb'].map(input => { + ['mb', '-1kb', '5gb', '6tb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(false); }); @@ -41,7 +41,7 @@ describe('bytesRt', () => { }); describe('it should return correct error message', () => { - ['-1kb', '5gb', '6tb'].map(input => { + ['-1kb', '5gb', '6tb'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = bytesRt.decode(input); const message = PathReporter.report(result)[0]; @@ -52,7 +52,7 @@ describe('bytesRt', () => { }); describe('it should accept', () => { - ['1b', '2kb', '3mb'].map(input => { + ['1b', '2kb', '3mb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(true); }); @@ -62,17 +62,17 @@ describe('bytesRt', () => { describe('must be between 500b and 1kb', () => { const bytesRt = getBytesRt({ min: '500b', - max: '1kb' + max: '1kb', }); describe('it should not accept', () => { - ['mb', '-1b', '1b', '499b', '1025b', '2kb', '1mb'].map(input => { + ['mb', '-1b', '1b', '499b', '1025b', '2kb', '1mb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(false); }); }); }); describe('it should return correct error message', () => { - ['-1b', '1b', '499b', '1025b', '2kb', '1mb'].map(input => { + ['-1b', '1b', '499b', '1025b', '2kb', '1mb'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = bytesRt.decode(input); const message = PathReporter.report(result)[0]; @@ -82,7 +82,7 @@ describe('bytesRt', () => { }); }); describe('it should accept', () => { - ['500b', '1024b', '1kb'].map(input => { + ['500b', '1024b', '1kb'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(bytesRt.decode(input))).toBe(true); }); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.ts index 9f49527438b49..202afecac270f 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/bytes_rt.ts @@ -38,18 +38,21 @@ export function getBytesRt({ min, max }: { min?: string; max?: string }) { 'bytesRt', t.string.is, (input, context) => { - return either.chain(t.string.validate(input, context), inputAsString => { - const inputAsBytes = amountAndUnitToBytes(inputAsString); + return either.chain( + t.string.validate(input, context), + (inputAsString) => { + const inputAsBytes = amountAndUnitToBytes(inputAsString); - const isValidAmount = - inputAsBytes !== undefined && - inputAsBytes >= minAsBytes && - inputAsBytes <= maxAsBytes; + const isValidAmount = + inputAsBytes !== undefined && + inputAsBytes >= minAsBytes && + inputAsBytes <= maxAsBytes; - return isValidAmount - ? t.success(inputAsString) - : t.failure(input, context, message); - }); + return isValidAmount + ? t.success(inputAsString) + : t.failure(input, context, message); + } + ); }, t.identity ); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.test.ts index ba522e6b8ea68..fdcda18677d82 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.test.ts @@ -9,7 +9,7 @@ import { isRight } from 'fp-ts/lib/Either'; describe('captureBodyRt', () => { describe('it should not accept', () => { - [undefined, null, '', 0, 'foo', true, false].map(input => { + [undefined, null, '', 0, 'foo', true, false].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(captureBodyRt.decode(input))).toBe(false); }); @@ -17,7 +17,7 @@ describe('captureBodyRt', () => { }); describe('it should accept', () => { - ['off', 'errors', 'transactions', 'all'].map(input => { + ['off', 'errors', 'transactions', 'all'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(captureBodyRt.decode(input))).toBe(true); }); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.ts index 8f38a8976beb0..5138cfe87c818 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/capture_body_rt.ts @@ -10,5 +10,5 @@ export const captureBodyRt = t.union([ t.literal('off'), t.literal('errors'), t.literal('transactions'), - t.literal('all') + t.literal('all'), ]); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.test.ts index ebfd9d9a72704..cc4ad132699ab 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.test.ts @@ -23,15 +23,15 @@ describe('getDurationRt', () => { '0m', '-1m', '1ms', - '1s' - ].map(input => { + '1s', + ].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeFalsy(); }); }); }); describe('it should return correct error message', () => { - ['0m', '-1m', '1ms', '1s'].map(input => { + ['0m', '-1m', '1ms', '1s'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = customDurationRt.decode(input); const message = PathReporter.report(result)[0]; @@ -41,7 +41,7 @@ describe('getDurationRt', () => { }); }); describe('it should accept', () => { - ['1m', '2m', '1000m'].map(input => { + ['1m', '2m', '1000m'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeTruthy(); }); @@ -68,15 +68,15 @@ describe('getDurationRt', () => { '0ms', '-1ms', '0m', - '1m' - ].map(input => { + '1m', + ].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeFalsy(); }); }); }); describe('it should return correct error message', () => { - ['-1s', '0s', '2s', '1001ms', '0ms', '-1ms', '0m', '1m'].map(input => { + ['-1s', '0s', '2s', '1001ms', '0ms', '-1ms', '0m', '1m'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = customDurationRt.decode(input); const message = PathReporter.report(result)[0]; @@ -86,7 +86,7 @@ describe('getDurationRt', () => { }); }); describe('it should accept', () => { - ['1s', '1ms', '50ms', '1000ms'].map(input => { + ['1s', '1ms', '50ms', '1000ms'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeTruthy(); }); @@ -98,7 +98,7 @@ describe('getDurationRt', () => { describe('it should not accept', () => { [undefined, null, '', 0, 'foo', true, false, '2m', '61s', '60001ms'].map( - input => { + (input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeFalsy(); }); @@ -106,7 +106,7 @@ describe('getDurationRt', () => { ); }); describe('it should return correct error message', () => { - ['2m', '61s', '60001ms'].map(input => { + ['2m', '61s', '60001ms'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = customDurationRt.decode(input); const message = PathReporter.report(result)[0]; @@ -116,7 +116,7 @@ describe('getDurationRt', () => { }); }); describe('it should accept', () => { - ['1m', '0m', '-1m', '60s', '6000ms', '1ms', '1s'].map(input => { + ['1m', '0m', '-1m', '60s', '6000ms', '1ms', '1s'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(customDurationRt.decode(input))).toBeTruthy(); }); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.ts index cede5ed262558..a8c521be3d9af 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/duration_rt.ts @@ -32,18 +32,23 @@ export function getDurationRt({ min, max }: { min?: string; max?: string }) { 'durationRt', t.string.is, (input, context) => { - return either.chain(t.string.validate(input, context), inputAsString => { - const inputAsMilliseconds = amountAndUnitToMilliseconds(inputAsString); + return either.chain( + t.string.validate(input, context), + (inputAsString) => { + const inputAsMilliseconds = amountAndUnitToMilliseconds( + inputAsString + ); - const isValidAmount = - inputAsMilliseconds !== undefined && - inputAsMilliseconds >= minAsMilliseconds && - inputAsMilliseconds <= maxAsMilliseconds; + const isValidAmount = + inputAsMilliseconds !== undefined && + inputAsMilliseconds >= minAsMilliseconds && + inputAsMilliseconds <= maxAsMilliseconds; - return isValidAmount - ? t.success(inputAsString) - : t.failure(input, context, message); - }); + return isValidAmount + ? t.success(inputAsString) + : t.failure(input, context, message); + } + ); }, t.identity ); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/float_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/float_rt.ts index 4aa166f84bfe9..9c71325639674 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/float_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/float_rt.ts @@ -11,7 +11,7 @@ export const floatRt = new t.Type( 'floatRt', t.string.is, (input, context) => { - return either.chain(t.string.validate(input, context), inputAsString => { + return either.chain(t.string.validate(input, context), (inputAsString) => { const inputAsFloat = parseFloat(inputAsString); const maxThreeDecimals = parseFloat(inputAsFloat.toFixed(3)) === inputAsFloat; diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/get_range_type_message.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/get_range_type_message.ts index 5bd0fcb80c4dd..388ffa3b51d72 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/get_range_type_message.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/get_range_type_message.ts @@ -35,7 +35,7 @@ export function getRangeTypeMessage( rangeType: getRangeType( typeof min === 'string' ? amountAndUnitToObject(min).amount : min, typeof max === 'string' ? amountAndUnitToObject(max).amount : max - ) - } + ), + }, }); } diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.test.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.test.ts index a0395a4a140d9..0ea17bd40f3cc 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.test.ts @@ -12,12 +12,12 @@ describe('getIntegerRt', () => { describe('with range', () => { const integerRt = getIntegerRt({ min: 0, - max: 32000 + max: 32000, }); describe('it should not accept', () => { [NaN, undefined, null, '', 'foo', 0, 55, '-1', '-55', '33000'].map( - input => { + (input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(integerRt.decode(input))).toBe(false); }); @@ -26,7 +26,7 @@ describe('getIntegerRt', () => { }); describe('it should return correct error message', () => { - ['-1', '-55', '33000'].map(input => { + ['-1', '-55', '33000'].map((input) => { it(`${JSON.stringify(input)}`, () => { const result = integerRt.decode(input); const message = PathReporter.report(result)[0]; @@ -37,7 +37,7 @@ describe('getIntegerRt', () => { }); describe('it should accept number between 0 and 32000', () => { - ['0', '1000', '32000'].map(input => { + ['0', '1000', '32000'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(integerRt.decode(input))).toBe(true); }); @@ -49,7 +49,7 @@ describe('getIntegerRt', () => { const integerRt = getIntegerRt(); describe('it should not accept', () => { - [NaN, undefined, null, '', 'foo', 0, 55].map(input => { + [NaN, undefined, null, '', 'foo', 0, 55].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(integerRt.decode(input))).toBe(false); }); @@ -57,7 +57,7 @@ describe('getIntegerRt', () => { }); describe('it should accept any number', () => { - ['-100', '-1', '0', '1000', '32000', '100000'].map(input => { + ['-100', '-1', '0', '1000', '32000', '100000'].map((input) => { it(`${JSON.stringify(input)}`, () => { expect(isRight(integerRt.decode(input))).toBe(true); }); diff --git a/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.ts b/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.ts index adb91992f756a..2443c43ae484d 100644 --- a/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.ts +++ b/x-pack/plugins/apm/common/agent_configuration/runtime_types/integer_rt.ts @@ -10,7 +10,7 @@ import { getRangeTypeMessage } from './get_range_type_message'; export function getIntegerRt({ min = -Infinity, - max = Infinity + max = Infinity, }: { min?: number; max?: number; @@ -21,13 +21,16 @@ export function getIntegerRt({ 'integerRt', t.string.is, (input, context) => { - return either.chain(t.string.validate(input, context), inputAsString => { - const inputAsInt = parseInt(inputAsString, 10); - const isValid = inputAsInt >= min && inputAsInt <= max; - return isValid - ? t.success(inputAsString) - : t.failure(input, context, message); - }); + return either.chain( + t.string.validate(input, context), + (inputAsString) => { + const inputAsInt = parseInt(inputAsString, 10); + const isValid = inputAsInt >= min && inputAsInt <= max; + return isValid + ? t.success(inputAsString) + : t.failure(input, context, message); + } + ); }, t.identity ); diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts index 4ade59d489040..95892f435e8f9 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/general_settings.ts @@ -15,16 +15,16 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'bytes', defaultValue: '768kb', label: i18n.translate('xpack.apm.agentConfig.apiRequestSize.label', { - defaultMessage: 'API Request Size' + defaultMessage: 'API Request Size', }), description: i18n.translate( 'xpack.apm.agentConfig.apiRequestSize.description', { defaultMessage: - 'The maximum total compressed size of the request body which is sent to the APM Server intake api via a chunked encoding (HTTP streaming).\nNote that a small overshoot is possible.\n\nAllowed byte units are `b`, `kb` and `mb`. `1kb` is equal to `1024b`.' + 'The maximum total compressed size of the request body which is sent to the APM Server intake api via a chunked encoding (HTTP streaming).\nNote that a small overshoot is possible.\n\nAllowed byte units are `b`, `kb` and `mb`. `1kb` is equal to `1024b`.', } ), - excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'] + excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'], }, // API Request Time @@ -33,16 +33,16 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'duration', defaultValue: '10s', label: i18n.translate('xpack.apm.agentConfig.apiRequestTime.label', { - defaultMessage: 'API Request Time' + defaultMessage: 'API Request Time', }), description: i18n.translate( 'xpack.apm.agentConfig.apiRequestTime.description', { defaultMessage: - "Maximum time to keep an HTTP request to the APM Server open for.\n\nNOTE: This value has to be lower than the APM Server's `read_timeout` setting." + "Maximum time to keep an HTTP request to the APM Server open for.\n\nNOTE: This value has to be lower than the APM Server's `read_timeout` setting.", } ), - excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'] + excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'], }, // Capture body @@ -52,22 +52,22 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'select', defaultValue: 'off', label: i18n.translate('xpack.apm.agentConfig.captureBody.label', { - defaultMessage: 'Capture body' + defaultMessage: 'Capture body', }), description: i18n.translate( 'xpack.apm.agentConfig.captureBody.description', { defaultMessage: - 'For transactions that are HTTP requests, the agent can optionally capture the request body (e.g. POST variables).\nFor transactions that are initiated by receiving a message from a message broker, the agent can capture the textual message body.' + 'For transactions that are HTTP requests, the agent can optionally capture the request body (e.g. POST variables).\nFor transactions that are initiated by receiving a message from a message broker, the agent can capture the textual message body.', } ), options: [ { text: 'off', value: 'off' }, { text: 'errors', value: 'errors' }, { text: 'transactions', value: 'transactions' }, - { text: 'all', value: 'all' } + { text: 'all', value: 'all' }, ], - excludeAgents: ['js-base', 'rum-js'] + excludeAgents: ['js-base', 'rum-js'], }, // Capture headers @@ -76,16 +76,16 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'boolean', defaultValue: 'true', label: i18n.translate('xpack.apm.agentConfig.captureHeaders.label', { - defaultMessage: 'Capture Headers' + defaultMessage: 'Capture Headers', }), description: i18n.translate( 'xpack.apm.agentConfig.captureHeaders.description', { defaultMessage: - 'If set to `true`, the agent will capture HTTP request and response headers (including cookies), as well as message headers/properties when using messaging frameworks (like Kafka).\n\nNOTE: Setting this to `false` reduces network bandwidth, disk space and object allocations.' + 'If set to `true`, the agent will capture HTTP request and response headers (including cookies), as well as message headers/properties when using messaging frameworks (like Kafka).\n\nNOTE: Setting this to `false` reduces network bandwidth, disk space and object allocations.', } ), - excludeAgents: ['js-base', 'rum-js', 'nodejs'] + excludeAgents: ['js-base', 'rum-js', 'nodejs'], }, // LOG_LEVEL @@ -94,12 +94,12 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'text', defaultValue: 'info', label: i18n.translate('xpack.apm.agentConfig.logLevel.label', { - defaultMessage: 'Log level' + defaultMessage: 'Log level', }), description: i18n.translate('xpack.apm.agentConfig.logLevel.description', { - defaultMessage: 'Sets the logging level for the agent' + defaultMessage: 'Sets the logging level for the agent', }), - includeAgents: ['dotnet', 'ruby'] + includeAgents: ['dotnet', 'ruby'], }, // Recording @@ -108,13 +108,13 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'boolean', defaultValue: 'true', label: i18n.translate('xpack.apm.agentConfig.recording.label', { - defaultMessage: 'Recording' + defaultMessage: 'Recording', }), description: i18n.translate('xpack.apm.agentConfig.recording.description', { defaultMessage: - 'When recording, the agent instruments incoming HTTP requests, tracks errors, and collects and sends metrics. When set to non-recording, the agent works as a noop, not collecting data and not communicating with the APM Server except for polling for updated configuration. As this is a reversible switch, agent threads are not being killed when set to non-recording, but they will be mostly idle in this state, so the overhead should be negligible. You can use this setting to dynamically control whether Elastic APM is enabled or disabled.' + 'When recording, the agent instruments incoming HTTP requests, tracks errors, and collects and sends metrics. When set to non-recording, the agent works as a noop, not collecting data and not communicating with the APM Server except for polling for updated configuration. As this is a reversible switch, agent threads are not being killed when set to non-recording, but they will be mostly idle in this state, so the overhead should be negligible. You can use this setting to dynamically control whether Elastic APM is enabled or disabled.', }), - excludeAgents: ['nodejs'] + excludeAgents: ['nodejs'], }, // SERVER_TIMEOUT @@ -123,16 +123,16 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'duration', defaultValue: '5s', label: i18n.translate('xpack.apm.agentConfig.serverTimeout.label', { - defaultMessage: 'Server Timeout' + defaultMessage: 'Server Timeout', }), description: i18n.translate( 'xpack.apm.agentConfig.serverTimeout.description', { defaultMessage: - 'If a request to the APM Server takes longer than the configured timeout,\nthe request is cancelled and the event (exception or transaction) is discarded.\nSet to 0 to disable timeouts.\n\nWARNING: If timeouts are disabled or set to a high value, your app could experience memory issues if the APM Server times out.' + 'If a request to the APM Server takes longer than the configured timeout,\nthe request is cancelled and the event (exception or transaction) is discarded.\nSet to 0 to disable timeouts.\n\nWARNING: If timeouts are disabled or set to a high value, your app could experience memory issues if the APM Server times out.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, // SPAN_FRAMES_MIN_DURATION @@ -142,16 +142,16 @@ export const generalSettings: RawSettingDefinition[] = [ min: '-1ms', defaultValue: '5ms', label: i18n.translate('xpack.apm.agentConfig.spanFramesMinDuration.label', { - defaultMessage: 'Span frames minimum duration' + defaultMessage: 'Span frames minimum duration', }), description: i18n.translate( 'xpack.apm.agentConfig.spanFramesMinDuration.description', { defaultMessage: - 'In its default settings, the APM agent will collect a stack trace with every recorded span.\nWhile this is very helpful to find the exact place in your code that causes the span, collecting this stack trace does have some overhead. \nWhen setting this option to a negative value, like `-1ms`, stack traces will be collected for all spans. Setting it to a positive value, e.g. `5ms`, will limit stack trace collection to spans with durations equal to or longer than the given value, e.g. 5 milliseconds.\n\nTo disable stack trace collection for spans completely, set the value to `0ms`.' + 'In its default settings, the APM agent will collect a stack trace with every recorded span.\nWhile this is very helpful to find the exact place in your code that causes the span, collecting this stack trace does have some overhead. \nWhen setting this option to a negative value, like `-1ms`, stack traces will be collected for all spans. Setting it to a positive value, e.g. `5ms`, will limit stack trace collection to spans with durations equal to or longer than the given value, e.g. 5 milliseconds.\n\nTo disable stack trace collection for spans completely, set the value to `0ms`.', } ), - excludeAgents: ['js-base', 'rum-js', 'nodejs'] + excludeAgents: ['js-base', 'rum-js', 'nodejs'], }, // STACK_TRACE_LIMIT @@ -160,16 +160,16 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'integer', defaultValue: '50', label: i18n.translate('xpack.apm.agentConfig.stackTraceLimit.label', { - defaultMessage: 'Stack trace limit' + defaultMessage: 'Stack trace limit', }), description: i18n.translate( 'xpack.apm.agentConfig.stackTraceLimit.description', { defaultMessage: - 'Setting it to 0 will disable stack trace collection. Any positive integer value will be used as the maximum number of frames to collect. Setting it -1 means that all frames will be collected.' + 'Setting it to 0 will disable stack trace collection. Any positive integer value will be used as the maximum number of frames to collect. Setting it -1 means that all frames will be collected.', } ), - includeAgents: ['java', 'dotnet', 'go'] + includeAgents: ['java', 'dotnet', 'go'], }, // Transaction max spans @@ -180,16 +180,16 @@ export const generalSettings: RawSettingDefinition[] = [ max: 32000, defaultValue: '500', label: i18n.translate('xpack.apm.agentConfig.transactionMaxSpans.label', { - defaultMessage: 'Transaction max spans' + defaultMessage: 'Transaction max spans', }), description: i18n.translate( 'xpack.apm.agentConfig.transactionMaxSpans.description', { defaultMessage: - 'Limits the amount of spans that are recorded per transaction.' + 'Limits the amount of spans that are recorded per transaction.', } ), - excludeAgents: ['js-base', 'rum-js'] + excludeAgents: ['js-base', 'rum-js'], }, // Transaction sample rate @@ -198,14 +198,14 @@ export const generalSettings: RawSettingDefinition[] = [ type: 'float', defaultValue: '1.0', label: i18n.translate('xpack.apm.agentConfig.transactionSampleRate.label', { - defaultMessage: 'Transaction sample rate' + defaultMessage: 'Transaction sample rate', }), description: i18n.translate( 'xpack.apm.agentConfig.transactionSampleRate.description', { defaultMessage: - 'By default, the agent will sample every transaction (e.g. request to your service). To reduce overhead and storage requirements, you can set the sample rate to a value between 0.0 and 1.0. We still record overall time and the result for unsampled transactions, but not context information, labels, or spans.' + 'By default, the agent will sample every transaction (e.g. request to your service). To reduce overhead and storage requirements, you can set the sample rate to a value between 0.0 and 1.0. We still record overall time and the result for unsampled transactions, but not context information, labels, or spans.', } - ) - } + ), + }, ]; diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts index 7fa44b8c85f41..1f247813104ec 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.test.ts @@ -13,7 +13,7 @@ describe('filterByAgent', () => { describe('when `excludeAgents` is dotnet and nodejs', () => { const setting = { key: 'my-setting', - excludeAgents: ['dotnet', 'nodejs'] + excludeAgents: ['dotnet', 'nodejs'], } as SettingDefinition; it('should not include dotnet', () => { @@ -28,7 +28,7 @@ describe('filterByAgent', () => { describe('when `includeAgents` is dotnet and nodejs', () => { const setting = { key: 'my-setting', - includeAgents: ['dotnet', 'nodejs'] + includeAgents: ['dotnet', 'nodejs'], } as SettingDefinition; it('should not include go', () => { @@ -49,7 +49,7 @@ describe('filterByAgent', () => { 'span_frames_min_duration', 'stack_trace_limit', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -76,21 +76,21 @@ describe('filterByAgent', () => { 'stress_monitor_system_cpu_relief_threshold', 'stress_monitor_system_cpu_stress_threshold', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); it('js-base', () => { expect(getSettingKeysForAgent('js-base')).toEqual([ 'recording', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); it('rum-js', () => { expect(getSettingKeysForAgent('rum-js')).toEqual([ 'recording', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -98,7 +98,7 @@ describe('filterByAgent', () => { expect(getSettingKeysForAgent('nodejs')).toEqual([ 'capture_body', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -111,7 +111,7 @@ describe('filterByAgent', () => { 'recording', 'span_frames_min_duration', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -124,7 +124,7 @@ describe('filterByAgent', () => { 'span_frames_min_duration', 'stack_trace_limit', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -138,7 +138,7 @@ describe('filterByAgent', () => { 'recording', 'span_frames_min_duration', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); @@ -146,7 +146,7 @@ describe('filterByAgent', () => { expect(getSettingKeysForAgent(undefined)).toEqual([ 'capture_body', 'transaction_max_spans', - 'transaction_sample_rate' + 'transaction_sample_rate', ]); }); }); @@ -155,7 +155,7 @@ describe('filterByAgent', () => { describe('settingDefinitions', () => { it('should have correct default values', () => { expect( - settingDefinitions.map(def => { + settingDefinitions.map((def) => { return { ...omit(def, [ 'category', @@ -164,9 +164,9 @@ describe('settingDefinitions', () => { 'excludeAgents', 'includeAgents', 'label', - 'validation' + 'validation', ]), - validationName: def.validation.name + validationName: def.validation.name, }; }) ).toMatchSnapshot(); @@ -175,5 +175,5 @@ describe('settingDefinitions', () => { function getSettingKeysForAgent(agentName: AgentName | undefined) { const definitions = settingDefinitions.filter(filterByAgent(agentName)); - return definitions.map(def => def.key); + return definitions.map((def) => def.key); } diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.ts index 7869cd7d79e17..a60fb84d273b2 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/index.ts @@ -37,14 +37,14 @@ function getSettingDefaults(setting: RawSettingDefinition): SettingDefinition { validation: getIntegerRt({ min, max }), min, max, - ...setting + ...setting, }; } case 'float': { return { validation: floatRt, - ...setting + ...setting, }; } @@ -57,7 +57,7 @@ function getSettingDefaults(setting: RawSettingDefinition): SettingDefinition { validation: getBytesRt({ min, max }), units, min, - ...setting + ...setting, }; } @@ -70,7 +70,7 @@ function getSettingDefaults(setting: RawSettingDefinition): SettingDefinition { validation: getDurationRt({ min, max }), units, min, - ...setting + ...setting, }; } diff --git a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/java_settings.ts b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/java_settings.ts index 49cb0ae9cfa81..f355d2eb18b26 100644 --- a/x-pack/plugins/apm/common/agent_configuration/setting_definitions/java_settings.ts +++ b/x-pack/plugins/apm/common/agent_configuration/setting_definitions/java_settings.ts @@ -14,16 +14,16 @@ export const javaSettings: RawSettingDefinition[] = [ type: 'boolean', defaultValue: 'false', label: i18n.translate('xpack.apm.agentConfig.enableLogCorrelation.label', { - defaultMessage: 'Enable log correlation' + defaultMessage: 'Enable log correlation', }), description: i18n.translate( 'xpack.apm.agentConfig.enableLogCorrelation.description', { defaultMessage: - "A boolean specifying if the agent should integrate into SLF4J's MDC to enable trace-log correlation. If set to `true`, the agent will set the `trace.id` and `transaction.id` for the currently active spans and transactions to the MDC. Since Java agent version 1.16.0, the agent also adds `error.id` of captured error to the MDC just before the error message is logged. NOTE: While it's allowed to enable this setting at runtime, you can't disable it without a restart." + "A boolean specifying if the agent should integrate into SLF4J's MDC to enable trace-log correlation. If set to `true`, the agent will set the `trace.id` and `transaction.id` for the currently active spans and transactions to the MDC. Since Java agent version 1.16.0, the agent also adds `error.id` of captured error to the MDC just before the error message is logged. NOTE: While it's allowed to enable this setting at runtime, you can't disable it without a restart.", } ), - includeAgents: ['java'] + includeAgents: ['java'], }, /* @@ -32,7 +32,7 @@ export const javaSettings: RawSettingDefinition[] = [ { key: 'circuit_breaker_enabled', label: i18n.translate('xpack.apm.agentConfig.circuitBreakerEnabled.label', { - defaultMessage: 'Cirtcuit breaker enabled' + defaultMessage: 'Cirtcuit breaker enabled', }), type: 'boolean', category: 'Circuit-Breaker', @@ -41,10 +41,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.circuitBreakerEnabled.description', { defaultMessage: - 'A boolean specifying whether the circuit breaker should be enabled or not. When enabled, the agent periodically polls stress monitors to detect system/process/JVM stress state. If ANY of the monitors detects a stress indication, the agent will pause, as if the `recording` configuration option has been set to `false`, thus reducing resource consumption to a minimum. When paused, the agent continues polling the same monitors in order to detect whether the stress state has been relieved. If ALL monitors approve that the system/process/JVM is not under stress anymore, the agent will resume and become fully functional.' + 'A boolean specifying whether the circuit breaker should be enabled or not. When enabled, the agent periodically polls stress monitors to detect system/process/JVM stress state. If ANY of the monitors detects a stress indication, the agent will pause, as if the `recording` configuration option has been set to `false`, thus reducing resource consumption to a minimum. When paused, the agent continues polling the same monitors in order to detect whether the stress state has been relieved. If ALL monitors approve that the system/process/JVM is not under stress anymore, the agent will resume and become fully functional.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'stress_monitor_gc_stress_threshold', @@ -59,10 +59,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.stressMonitorGcStressThreshold.description', { defaultMessage: - 'The threshold used by the GC monitor to rely on for identifying heap stress. The same threshold will be used for all heap pools, so that if ANY has a usage percentage that crosses it, the agent will consider it as a heap stress. The GC monitor relies only on memory consumption measured after a recent GC.' + 'The threshold used by the GC monitor to rely on for identifying heap stress. The same threshold will be used for all heap pools, so that if ANY has a usage percentage that crosses it, the agent will consider it as a heap stress. The GC monitor relies only on memory consumption measured after a recent GC.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'stress_monitor_gc_relief_threshold', @@ -78,10 +78,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.stressMonitorGcReliefThreshold.description', { defaultMessage: - 'The threshold used by the GC monitor to rely on for identifying when the heap is not under stress. If `stress_monitor_gc_stress_threshold` has been crossed, the agent will consider it a heap-stress state. In order to determine that the stress state is over, percentage of occupied memory in ALL heap pools should be lower than this threshold. The GC monitor relies only on memory consumption measured after a recent GC.' + 'The threshold used by the GC monitor to rely on for identifying when the heap is not under stress. If `stress_monitor_gc_stress_threshold` has been crossed, the agent will consider it a heap-stress state. In order to determine that the stress state is over, percentage of occupied memory in ALL heap pools should be lower than this threshold. The GC monitor relies only on memory consumption measured after a recent GC.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'stress_monitor_cpu_duration_threshold', @@ -96,11 +96,11 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.stressMonitorCpuDurationThreshold.description', { defaultMessage: - 'The minimal time required in order to determine whether the system is either currently under stress, or that the stress detected previously has been relieved. All measurements during this time must be consistent in comparison to the relevant threshold in order to detect a change of stress state. Must be at least `1m`.' + 'The minimal time required in order to determine whether the system is either currently under stress, or that the stress detected previously has been relieved. All measurements during this time must be consistent in comparison to the relevant threshold in order to detect a change of stress state. Must be at least `1m`.', } ), includeAgents: ['java'], - min: '1m' + min: '1m', }, { key: 'stress_monitor_system_cpu_stress_threshold', @@ -115,10 +115,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.stressMonitorSystemCpuStressThreshold.description', { defaultMessage: - 'The threshold used by the system CPU monitor to detect system CPU stress. If the system CPU crosses this threshold for a duration of at least `stress_monitor_cpu_duration_threshold`, the monitor considers this as a stress state.' + 'The threshold used by the system CPU monitor to detect system CPU stress. If the system CPU crosses this threshold for a duration of at least `stress_monitor_cpu_duration_threshold`, the monitor considers this as a stress state.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'stress_monitor_system_cpu_relief_threshold', @@ -133,10 +133,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.stressMonitorSystemCpuReliefThreshold.description', { defaultMessage: - 'The threshold used by the system CPU monitor to determine that the system is not under CPU stress. If the monitor detected a CPU stress, the measured system CPU needs to be below this threshold for a duration of at least `stress_monitor_cpu_duration_threshold` in order for the monitor to decide that the CPU stress has been relieved.' + 'The threshold used by the system CPU monitor to determine that the system is not under CPU stress. If the monitor detected a CPU stress, the measured system CPU needs to be below this threshold for a duration of at least `stress_monitor_cpu_duration_threshold` in order for the monitor to decide that the CPU stress has been relieved.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, /* @@ -156,10 +156,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.profilingInferredSpansEnabled.description', { defaultMessage: - 'Set to `true` to make the agent create spans for method executions based on async-profiler, a sampling aka statistical profiler. Due to the nature of how sampling profilers work, the duration of the inferred spans are not exact, but only estimations. The `profiling_inferred_spans_sampling_interval` lets you fine tune the trade-off between accuracy and overhead. The inferred spans are created after a profiling session has ended. This means there is a delay between the regular and the inferred spans being visible in the UI. NOTE: This feature is not available on Windows.' + 'Set to `true` to make the agent create spans for method executions based on async-profiler, a sampling aka statistical profiler. Due to the nature of how sampling profilers work, the duration of the inferred spans are not exact, but only estimations. The `profiling_inferred_spans_sampling_interval` lets you fine tune the trade-off between accuracy and overhead. The inferred spans are created after a profiling session has ended. This means there is a delay between the regular and the inferred spans being visible in the UI. NOTE: This feature is not available on Windows.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'profiling_inferred_spans_sampling_interval', @@ -174,12 +174,12 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.profilingInferredSpansSamplingInterval.description', { defaultMessage: - 'The frequency at which stack traces are gathered within a profiling session. The lower you set it, the more accurate the durations will be. This comes at the expense of higher overhead and more spans for potentially irrelevant operations. The minimal duration of a profiling-inferred span is the same as the value of this setting.' + 'The frequency at which stack traces are gathered within a profiling session. The lower you set it, the more accurate the durations will be. This comes at the expense of higher overhead and more spans for potentially irrelevant operations. The minimal duration of a profiling-inferred span is the same as the value of this setting.', } ), includeAgents: ['java'], min: '1ms', - max: '1s' + max: '1s', }, { key: 'profiling_inferred_spans_min_duration', @@ -194,11 +194,11 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.profilingInferredSpansMinDuration.description', { defaultMessage: - 'The minimum duration of an inferred span. Note that the min duration is also implicitly set by the sampling interval. However, increasing the sampling interval also decreases the accuracy of the duration of inferred spans.' + 'The minimum duration of an inferred span. Note that the min duration is also implicitly set by the sampling interval. However, increasing the sampling interval also decreases the accuracy of the duration of inferred spans.', } ), includeAgents: ['java'], - min: '0ms' + min: '0ms', }, { key: 'profiling_inferred_spans_included_classes', @@ -213,10 +213,10 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.profilingInferredSpansIncludedClasses.description', { defaultMessage: - 'If set, the agent will only create inferred spans for methods which match this list. Setting a value may slightly reduce overhead and can reduce clutter by only creating spans for the classes you are interested in. This option supports the wildcard `*`, which matches zero or more characters. Example: `org.example.myapp.*`. Matching is case insensitive by default. Prepending an element with `(?-i)` makes the matching case sensitive.' + 'If set, the agent will only create inferred spans for methods which match this list. Setting a value may slightly reduce overhead and can reduce clutter by only creating spans for the classes you are interested in. This option supports the wildcard `*`, which matches zero or more characters. Example: `org.example.myapp.*`. Matching is case insensitive by default. Prepending an element with `(?-i)` makes the matching case sensitive.', } ), - includeAgents: ['java'] + includeAgents: ['java'], }, { key: 'profiling_inferred_spans_excluded_classes', @@ -232,9 +232,9 @@ export const javaSettings: RawSettingDefinition[] = [ 'xpack.apm.agentConfig.profilingInferredSpansExcludedClasses.description', { defaultMessage: - 'Excludes classes for which no profiler-inferred spans should be created. This option supports the wildcard `*`, which matches zero or more characters. Matching is case insensitive by default. Prepending an element with `(?-i)` makes the matching case sensitive.' + 'Excludes classes for which no profiler-inferred spans should be created. This option supports the wildcard `*`, which matches zero or more characters. Matching is case insensitive by default. Prepending an element with `(?-i)` makes the matching case sensitive.', } ), - includeAgents: ['java'] - } + includeAgents: ['java'], + }, ]; diff --git a/x-pack/plugins/apm/common/agent_name.ts b/x-pack/plugins/apm/common/agent_name.ts index dac29a4f50682..630f5739806af 100644 --- a/x-pack/plugins/apm/common/agent_name.ts +++ b/x-pack/plugins/apm/common/agent_name.ts @@ -23,7 +23,7 @@ export const AGENT_NAMES: AgentName[] = [ 'java', 'nodejs', 'python', - 'ruby' + 'ruby', ]; export function isAgentName(agentName: string): agentName is AgentName { diff --git a/x-pack/plugins/apm/common/alert_types.ts b/x-pack/plugins/apm/common/alert_types.ts index 6638c2dd8baf9..ad826a446d823 100644 --- a/x-pack/plugins/apm/common/alert_types.ts +++ b/x-pack/plugins/apm/common/alert_types.ts @@ -8,28 +8,28 @@ import { i18n } from '@kbn/i18n'; export enum AlertType { ErrorRate = 'apm.error_rate', - TransactionDuration = 'apm.transaction_duration' + TransactionDuration = 'apm.transaction_duration', } export const ALERT_TYPES_CONFIG = { [AlertType.ErrorRate]: { name: i18n.translate('xpack.apm.errorRateAlert.name', { - defaultMessage: 'Error rate' + defaultMessage: 'Error rate', }), actionGroups: [ { id: 'threshold_met', name: i18n.translate('xpack.apm.errorRateAlert.thresholdMet', { - defaultMessage: 'Threshold met' - }) - } + defaultMessage: 'Threshold met', + }), + }, ], defaultActionGroupId: 'threshold_met', - producer: 'apm' + producer: 'apm', }, [AlertType.TransactionDuration]: { name: i18n.translate('xpack.apm.transactionDurationAlert.name', { - defaultMessage: 'Transaction duration' + defaultMessage: 'Transaction duration', }), actionGroups: [ { @@ -37,33 +37,33 @@ export const ALERT_TYPES_CONFIG = { name: i18n.translate( 'xpack.apm.transactionDurationAlert.thresholdMet', { - defaultMessage: 'Threshold met' + defaultMessage: 'Threshold met', } - ) - } + ), + }, ], defaultActionGroupId: 'threshold_met', - producer: 'apm' - } + producer: 'apm', + }, }; export const TRANSACTION_ALERT_AGGREGATION_TYPES = { avg: i18n.translate( 'xpack.apm.transactionDurationAlert.aggregationType.avg', { - defaultMessage: 'Average' + defaultMessage: 'Average', } ), '95th': i18n.translate( 'xpack.apm.transactionDurationAlert.aggregationType.95th', { - defaultMessage: '95th percentile' + defaultMessage: '95th percentile', } ), '99th': i18n.translate( 'xpack.apm.transactionDurationAlert.aggregationType.99th', { - defaultMessage: '99th percentile' + defaultMessage: '99th percentile', } - ) + ), }; diff --git a/x-pack/plugins/apm/common/annotations.ts b/x-pack/plugins/apm/common/annotations.ts index 264236e22b0c1..95f27f5e42a3a 100644 --- a/x-pack/plugins/apm/common/annotations.ts +++ b/x-pack/plugins/apm/common/annotations.ts @@ -5,7 +5,7 @@ */ export enum AnnotationType { - VERSION = 'version' + VERSION = 'version', } export interface Annotation { diff --git a/x-pack/plugins/apm/common/custom_link/custom_link_filter_options.ts b/x-pack/plugins/apm/common/custom_link/custom_link_filter_options.ts index 65d2877dabe9a..12ed449e21bef 100644 --- a/x-pack/plugins/apm/common/custom_link/custom_link_filter_options.ts +++ b/x-pack/plugins/apm/common/custom_link/custom_link_filter_options.ts @@ -7,12 +7,12 @@ import { SERVICE_NAME, SERVICE_ENVIRONMENT, TRANSACTION_NAME, - TRANSACTION_TYPE + TRANSACTION_TYPE, } from '../elasticsearch_fieldnames'; export const FILTER_OPTIONS = [ SERVICE_NAME, SERVICE_ENVIRONMENT, TRANSACTION_TYPE, - TRANSACTION_NAME + TRANSACTION_NAME, ] as const; diff --git a/x-pack/plugins/apm/common/custom_link/custom_link_types.d.ts b/x-pack/plugins/apm/common/custom_link/custom_link_types.d.ts index ca5e475554951..61dfaf322a87d 100644 --- a/x-pack/plugins/apm/common/custom_link/custom_link_types.d.ts +++ b/x-pack/plugins/apm/common/custom_link/custom_link_types.d.ts @@ -8,7 +8,7 @@ import { SERVICE_NAME, SERVICE_ENVIRONMENT, TRANSACTION_NAME, - TRANSACTION_TYPE + TRANSACTION_TYPE, } from '../elasticsearch_fieldnames'; import { FILTER_OPTIONS } from './custom_link_filter_options'; diff --git a/x-pack/plugins/apm/common/elasticsearch_fieldnames.test.ts b/x-pack/plugins/apm/common/elasticsearch_fieldnames.test.ts index 63fa749cd9f2c..e081f27e28b7b 100644 --- a/x-pack/plugins/apm/common/elasticsearch_fieldnames.test.ts +++ b/x-pack/plugins/apm/common/elasticsearch_fieldnames.test.ts @@ -17,20 +17,20 @@ describe('Transaction', () => { '@metadata': 'whatever', observer: { version: 'whatever', - version_major: 8 + version_major: 8, }, agent: { name: 'java', - version: 'agent version' + version: 'agent version', }, http: { request: { method: 'GET' }, - response: { status_code: 200 } + response: { status_code: 200 }, }, url: { full: 'http://www.elastic.co', domain: 'www.elastic.co' }, service: { name: 'service name', - language: { name: 'nodejs', version: 'v1337' } + language: { name: 'nodejs', version: 'v1337' }, }, host: { hostname: 'my hostname' }, processor: { name: 'transaction', event: 'transaction' }, @@ -39,7 +39,7 @@ describe('Transaction', () => { user: { id: '1337' }, user_agent: { name: 'Other', original: 'test original' }, parent: { - id: 'parentId' + id: 'parentId', }, transaction: { duration: { us: 1337 }, @@ -47,16 +47,16 @@ describe('Transaction', () => { name: 'transaction name', result: 'transaction result', sampled: true, - type: 'transaction type' + type: 'transaction type', }, kubernetes: { pod: { - uid: 'pod1234567890abcdef' - } + uid: 'pod1234567890abcdef', + }, }, container: { - id: 'container1234567890abcdef' - } + id: 'container1234567890abcdef', + }, }; matchSnapshot(transaction); @@ -68,27 +68,27 @@ describe('Span', () => { '@metadata': 'whatever', observer: { version: 'whatever', - version_major: 8 + version_major: 8, }, agent: { name: 'java', - version: 'agent version' + version: 'agent version', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, timestamp: { - us: 1337 + us: 1337, }, trace: { - id: 'trace id' + id: 'trace id', }, service: { - name: 'service name' + name: 'service name', }, parent: { - id: 'parentId' + id: 'parentId', }, span: { action: 'my action', @@ -99,12 +99,12 @@ describe('Span', () => { sync: false, type: 'span type', db: { - statement: 'db statement' - } + statement: 'db statement', + }, }, transaction: { - id: 'transaction id' - } + id: 'transaction id', + }, }; matchSnapshot(span); @@ -115,11 +115,11 @@ describe('Error', () => { '@metadata': 'whatever', observer: { version: 'whatever', - version_major: 8 + version_major: 8, }, agent: { name: 'java', - version: 'agent version' + version: 'agent version', }, error: { exception: [ @@ -127,41 +127,41 @@ describe('Error', () => { module: 'errors', handled: false, message: 'sonic boom', - type: 'errorString' - } + type: 'errorString', + }, ], culprit: 'handleOopsie', id: 'error id', - grouping_key: 'grouping key' + grouping_key: 'grouping key', }, '@timestamp': new Date().toString(), host: { - hostname: 'my hostname' + hostname: 'my hostname', }, processor: { name: 'error', - event: 'error' + event: 'error', }, timestamp: { - us: 1337 + us: 1337, }, trace: { - id: 'trace id' + id: 'trace id', }, service: { name: 'service name', language: { name: 'nodejs', - version: 'v1337' - } + version: 'v1337', + }, }, parent: { - id: 'parentId' + id: 'parentId', }, transaction: { id: 'transaction id', - type: 'request' - } + type: 'request', + }, }; matchSnapshot(errorDoc); diff --git a/x-pack/plugins/apm/common/i18n.ts b/x-pack/plugins/apm/common/i18n.ts index 1e27baa7c28de..ceac828714247 100644 --- a/x-pack/plugins/apm/common/i18n.ts +++ b/x-pack/plugins/apm/common/i18n.ts @@ -9,13 +9,13 @@ import { i18n } from '@kbn/i18n'; export const NOT_AVAILABLE_LABEL = i18n.translate( 'xpack.apm.notAvailableLabel', { - defaultMessage: 'N/A' + defaultMessage: 'N/A', } ); export const UNIDENTIFIED_SERVICE_NODES_LABEL = i18n.translate( 'xpack.apm.serviceNodeNameMissing', { - defaultMessage: '(Empty)' + defaultMessage: '(Empty)', } ); diff --git a/x-pack/plugins/apm/common/ml_job_constants.test.ts b/x-pack/plugins/apm/common/ml_job_constants.test.ts index 4941925939afb..020eb993eac89 100644 --- a/x-pack/plugins/apm/common/ml_job_constants.test.ts +++ b/x-pack/plugins/apm/common/ml_job_constants.test.ts @@ -10,7 +10,7 @@ import { getMlPrefix, getMlJobServiceName, getSeverity, - severity + severity, } from './ml_job_constants'; describe('ml_job_constants', () => { diff --git a/x-pack/plugins/apm/common/ml_job_constants.ts b/x-pack/plugins/apm/common/ml_job_constants.ts index afe0550721716..6df0d324981a1 100644 --- a/x-pack/plugins/apm/common/ml_job_constants.ts +++ b/x-pack/plugins/apm/common/ml_job_constants.ts @@ -8,7 +8,7 @@ export enum severity { critical = 'critical', major = 'major', minor = 'minor', - warning = 'warning' + warning = 'warning', } export function getMlPrefix(serviceName: string, transactionType?: string) { @@ -21,10 +21,7 @@ export function getMlJobId(serviceName: string, transactionType?: string) { } export function getMlJobServiceName(jobId: string) { - return jobId - .split('-') - .slice(0, -2) - .join('-'); + return jobId.split('-').slice(0, -2).join('-'); } export function getMlIndex(serviceName: string, transactionType?: string) { diff --git a/x-pack/plugins/apm/common/processor_event.ts b/x-pack/plugins/apm/common/processor_event.ts index 83dadfc21da90..3e8b0ba0e8b5e 100644 --- a/x-pack/plugins/apm/common/processor_event.ts +++ b/x-pack/plugins/apm/common/processor_event.ts @@ -7,5 +7,5 @@ export enum ProcessorEvent { transaction = 'transaction', error = 'error', - metric = 'metric' + metric = 'metric', } diff --git a/x-pack/plugins/apm/common/projections/errors.ts b/x-pack/plugins/apm/common/projections/errors.ts index b8de049f3bce9..bd397afae2243 100644 --- a/x-pack/plugins/apm/common/projections/errors.ts +++ b/x-pack/plugins/apm/common/projections/errors.ts @@ -7,20 +7,20 @@ import { Setup, SetupTimeRange, - SetupUIFilters + SetupUIFilters, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { PROCESSOR_EVENT, SERVICE_NAME, - ERROR_GROUP_ID + ERROR_GROUP_ID, } from '../elasticsearch_fieldnames'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { rangeFilter } from '../../server/lib/helpers/range_filter'; export function getErrorGroupsProjection({ setup, - serviceName + serviceName, }: { setup: Setup & SetupTimeRange & SetupUIFilters; serviceName: string; @@ -36,17 +36,17 @@ export function getErrorGroupsProjection({ { term: { [SERVICE_NAME]: serviceName } }, { term: { [PROCESSOR_EVENT]: 'error' } }, { range: rangeFilter(start, end) }, - ...uiFiltersES - ] - } + ...uiFiltersES, + ], + }, }, aggs: { error_groups: { terms: { - field: ERROR_GROUP_ID - } - } - } - } + field: ERROR_GROUP_ID, + }, + }, + }, + }, }; } diff --git a/x-pack/plugins/apm/common/projections/metrics.ts b/x-pack/plugins/apm/common/projections/metrics.ts index 799c84ae3c1c9..b05ec5f2ba876 100644 --- a/x-pack/plugins/apm/common/projections/metrics.ts +++ b/x-pack/plugins/apm/common/projections/metrics.ts @@ -7,13 +7,13 @@ import { Setup, SetupTimeRange, - SetupUIFilters + SetupUIFilters, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, PROCESSOR_EVENT, - SERVICE_NODE_NAME + SERVICE_NODE_NAME, } from '../elasticsearch_fieldnames'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { rangeFilter } from '../../server/lib/helpers/range_filter'; @@ -34,7 +34,7 @@ function getServiceNodeNameFilters(serviceNodeName?: string) { export function getMetricsProjection({ setup, serviceName, - serviceNodeName + serviceNodeName, }: { setup: Setup & SetupTimeRange & SetupUIFilters; serviceName: string; @@ -47,7 +47,7 @@ export function getMetricsProjection({ { term: { [PROCESSOR_EVENT]: 'metric' } }, { range: rangeFilter(start, end) }, ...getServiceNodeNameFilters(serviceNodeName), - ...uiFiltersES + ...uiFiltersES, ]; return { @@ -55,9 +55,9 @@ export function getMetricsProjection({ body: { query: { bool: { - filter - } - } - } + filter, + }, + }, + }, }; } diff --git a/x-pack/plugins/apm/common/projections/service_nodes.ts b/x-pack/plugins/apm/common/projections/service_nodes.ts index c65d29e8ea00d..1bc68f51a26ed 100644 --- a/x-pack/plugins/apm/common/projections/service_nodes.ts +++ b/x-pack/plugins/apm/common/projections/service_nodes.ts @@ -7,7 +7,7 @@ import { Setup, SetupTimeRange, - SetupUIFilters + SetupUIFilters, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { SERVICE_NODE_NAME } from '../elasticsearch_fieldnames'; @@ -17,7 +17,7 @@ import { getMetricsProjection } from './metrics'; export function getServiceNodesProjection({ setup, serviceName, - serviceNodeName + serviceNodeName, }: { setup: Setup & SetupTimeRange & SetupUIFilters; serviceName: string; @@ -27,18 +27,18 @@ export function getServiceNodesProjection({ getMetricsProjection({ setup, serviceName, - serviceNodeName + serviceNodeName, }), { body: { aggs: { nodes: { terms: { - field: SERVICE_NODE_NAME - } - } - } - } + field: SERVICE_NODE_NAME, + }, + }, + }, + }, } ); } diff --git a/x-pack/plugins/apm/common/projections/services.ts b/x-pack/plugins/apm/common/projections/services.ts index bdb0c4ef97895..bcfc27d720ba9 100644 --- a/x-pack/plugins/apm/common/projections/services.ts +++ b/x-pack/plugins/apm/common/projections/services.ts @@ -7,7 +7,7 @@ import { Setup, SetupUIFilters, - SetupTimeRange + SetupTimeRange, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, PROCESSOR_EVENT } from '../elasticsearch_fieldnames'; @@ -15,7 +15,7 @@ import { SERVICE_NAME, PROCESSOR_EVENT } from '../elasticsearch_fieldnames'; import { rangeFilter } from '../../server/lib/helpers/range_filter'; export function getServicesProjection({ - setup + setup, }: { setup: Setup & SetupTimeRange & SetupUIFilters; }) { @@ -25,7 +25,7 @@ export function getServicesProjection({ index: [ indices['apm_oss.metricsIndices'], indices['apm_oss.errorIndices'], - indices['apm_oss.transactionIndices'] + indices['apm_oss.transactionIndices'], ], body: { size: 0, @@ -33,20 +33,20 @@ export function getServicesProjection({ bool: { filter: [ { - terms: { [PROCESSOR_EVENT]: ['transaction', 'error', 'metric'] } + terms: { [PROCESSOR_EVENT]: ['transaction', 'error', 'metric'] }, }, { range: rangeFilter(start, end) }, - ...uiFiltersES - ] - } + ...uiFiltersES, + ], + }, }, aggs: { services: { terms: { - field: SERVICE_NAME - } - } - } - } + field: SERVICE_NAME, + }, + }, + }, + }, }; } diff --git a/x-pack/plugins/apm/common/projections/transaction_groups.ts b/x-pack/plugins/apm/common/projections/transaction_groups.ts index c19a5d002c015..1708d89aad4ec 100644 --- a/x-pack/plugins/apm/common/projections/transaction_groups.ts +++ b/x-pack/plugins/apm/common/projections/transaction_groups.ts @@ -7,7 +7,7 @@ import { omit } from 'lodash'; import { Setup, SetupTimeRange, - SetupUIFilters + SetupUIFilters, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { TRANSACTION_NAME, PARENT_ID } from '../elasticsearch_fieldnames'; @@ -18,35 +18,35 @@ import { mergeProjection } from './util/merge_projection'; export function getTransactionGroupsProjection({ setup, - options + options, }: { setup: Setup & SetupTimeRange & SetupUIFilters; options: Options; }) { const transactionsProjection = getTransactionsProjection({ setup, - ...(omit(options, 'type') as Omit) + ...(omit(options, 'type') as Omit), }); const bool = options.type === 'top_traces' ? { - must_not: [{ exists: { field: PARENT_ID } }] + must_not: [{ exists: { field: PARENT_ID } }], } : {}; return mergeProjection(transactionsProjection, { body: { query: { - bool + bool, }, aggs: { transactions: { terms: { - field: TRANSACTION_NAME - } - } - } - } + field: TRANSACTION_NAME, + }, + }, + }, + }, }); } diff --git a/x-pack/plugins/apm/common/projections/transactions.ts b/x-pack/plugins/apm/common/projections/transactions.ts index 34de5e8d2833a..99d5a04c1e722 100644 --- a/x-pack/plugins/apm/common/projections/transactions.ts +++ b/x-pack/plugins/apm/common/projections/transactions.ts @@ -7,14 +7,14 @@ import { Setup, SetupTimeRange, - SetupUIFilters + SetupUIFilters, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, TRANSACTION_TYPE, PROCESSOR_EVENT, - TRANSACTION_NAME + TRANSACTION_NAME, } from '../elasticsearch_fieldnames'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { rangeFilter } from '../../server/lib/helpers/range_filter'; @@ -23,7 +23,7 @@ export function getTransactionsProjection({ setup, serviceName, transactionName, - transactionType + transactionType, }: { setup: Setup & SetupTimeRange & SetupUIFilters; serviceName?: string; @@ -49,16 +49,16 @@ export function getTransactionsProjection({ ...transactionNameFilter, ...transactionTypeFilter, ...serviceNameFilter, - ...uiFiltersES - ] + ...uiFiltersES, + ], }; return { index: indices['apm_oss.transactionIndices'], body: { query: { - bool - } - } + bool, + }, + }, }; } diff --git a/x-pack/plugins/apm/common/projections/typings.ts b/x-pack/plugins/apm/common/projections/typings.ts index 2b55395b70c6b..3361770336dde 100644 --- a/x-pack/plugins/apm/common/projections/typings.ts +++ b/x-pack/plugins/apm/common/projections/typings.ts @@ -7,7 +7,7 @@ import { ESSearchRequest, ESSearchBody } from '../../typings/elasticsearch'; import { AggregationOptionsByType, - AggregationInputMap + AggregationInputMap, } from '../../typings/elasticsearch/aggregations'; export type Projection = Omit & { @@ -28,5 +28,5 @@ export enum PROJECTION { TRANSACTIONS = 'transactions', METRICS = 'metrics', ERROR_GROUPS = 'errorGroups', - SERVICE_NODES = 'serviceNodes' + SERVICE_NODES = 'serviceNodes', } diff --git a/x-pack/plugins/apm/common/projections/util/merge_projection/index.test.ts b/x-pack/plugins/apm/common/projections/util/merge_projection/index.test.ts index aa72b5fd71365..33727fcb9c735 100644 --- a/x-pack/plugins/apm/common/projections/util/merge_projection/index.test.ts +++ b/x-pack/plugins/apm/common/projections/util/merge_projection/index.test.ts @@ -19,12 +19,12 @@ describe('mergeProjection', () => { bool: { must: [ { - term: 'b' - } - ] - } - } - } + term: 'b', + }, + ], + }, + }, + }, }); }); @@ -36,9 +36,9 @@ describe('mergeProjection', () => { { body: { aggs: { - foo: { ...termsAgg, aggs: { bar: { terms: { field: 'baz' } } } } - } - } + foo: { ...termsAgg, aggs: { bar: { terms: { field: 'baz' } } } }, + }, + }, } ) ).toEqual({ @@ -47,18 +47,18 @@ describe('mergeProjection', () => { aggs: { foo: { terms: { - field: 'bar' + field: 'bar', }, aggs: { bar: { terms: { - field: 'baz' - } - } - } - } - } - } + field: 'baz', + }, + }, + }, + }, + }, + }, }); }); }); diff --git a/x-pack/plugins/apm/common/projections/util/merge_projection/index.ts b/x-pack/plugins/apm/common/projections/util/merge_projection/index.ts index 6a5089733bb33..f3ae0752b908e 100644 --- a/x-pack/plugins/apm/common/projections/util/merge_projection/index.ts +++ b/x-pack/plugins/apm/common/projections/util/merge_projection/index.ts @@ -8,7 +8,7 @@ import { DeepPartial } from 'utility-types'; import { AggregationInputMap } from '../../../../typings/elasticsearch/aggregations'; import { ESSearchRequest, - ESSearchBody + ESSearchBody, } from '../../../../typings/elasticsearch'; import { Projection } from '../../typings'; diff --git a/x-pack/plugins/apm/common/runtime_types/date_as_string_rt/index.ts b/x-pack/plugins/apm/common/runtime_types/date_as_string_rt/index.ts index 8320854e0c2a9..735af469c0f74 100644 --- a/x-pack/plugins/apm/common/runtime_types/date_as_string_rt/index.ts +++ b/x-pack/plugins/apm/common/runtime_types/date_as_string_rt/index.ts @@ -13,7 +13,7 @@ export const dateAsStringRt = new t.Type( 'DateAsString', t.string.is, (input, context) => - either.chain(t.string.validate(input, context), str => { + either.chain(t.string.validate(input, context), (str) => { const date = new Date(str); return isNaN(date.getTime()) ? t.failure(input, context) : t.success(str); }), diff --git a/x-pack/plugins/apm/common/runtime_types/json_rt/index.ts b/x-pack/plugins/apm/common/runtime_types/json_rt/index.ts index 51c825ce68a60..fcc73547a686b 100644 --- a/x-pack/plugins/apm/common/runtime_types/json_rt/index.ts +++ b/x-pack/plugins/apm/common/runtime_types/json_rt/index.ts @@ -10,12 +10,12 @@ export const jsonRt = new t.Type( 'JSON', t.any.is, (input, context) => - either.chain(t.string.validate(input, context), str => { + either.chain(t.string.validate(input, context), (str) => { try { return t.success(JSON.parse(str)); } catch (e) { return t.failure(input, context); } }), - a => JSON.stringify(a) + (a) => JSON.stringify(a) ); diff --git a/x-pack/plugins/apm/common/service_map.test.ts b/x-pack/plugins/apm/common/service_map.test.ts index 40b220ffe68f1..346403efc46ae 100644 --- a/x-pack/plugins/apm/common/service_map.test.ts +++ b/x-pack/plugins/apm/common/service_map.test.ts @@ -17,9 +17,9 @@ describe('service map helpers', () => { expiryDateInMillis: 0, mode: 'platinum', type: 'platinum', - status: 'expired' + status: 'expired', }, - signature: 'test signature' + signature: 'test signature', }); expect(serviceMap.isValidPlatinumLicense(license)).toEqual(false); @@ -34,9 +34,9 @@ describe('service map helpers', () => { expiryDateInMillis: 0, mode: 'basic', type: 'basic', - status: 'active' + status: 'active', }, - signature: 'test signature' + signature: 'test signature', }); expect(serviceMap.isValidPlatinumLicense(license)).toEqual(false); @@ -51,9 +51,9 @@ describe('service map helpers', () => { expiryDateInMillis: 0, mode: 'platinum', type: 'platinum', - status: 'active' + status: 'active', }, - signature: 'test signature' + signature: 'test signature', }); expect(serviceMap.isValidPlatinumLicense(license)).toEqual(true); @@ -68,9 +68,9 @@ describe('service map helpers', () => { expiryDateInMillis: 0, mode: 'enterprise', type: 'enterprise', - status: 'active' + status: 'active', }, - signature: 'test signature' + signature: 'test signature', }); expect(serviceMap.isValidPlatinumLicense(license)).toEqual(true); @@ -85,9 +85,9 @@ describe('service map helpers', () => { expiryDateInMillis: 0, mode: 'trial', type: 'trial', - status: 'active' + status: 'active', }, - signature: 'test signature' + signature: 'test signature', }); expect(serviceMap.isValidPlatinumLicense(license)).toEqual(true); diff --git a/x-pack/plugins/apm/common/service_map.ts b/x-pack/plugins/apm/common/service_map.ts index 87db0005fb656..9f20005c2b189 100644 --- a/x-pack/plugins/apm/common/service_map.ts +++ b/x-pack/plugins/apm/common/service_map.ts @@ -13,7 +13,7 @@ import { SERVICE_NAME, SPAN_DESTINATION_SERVICE_RESOURCE, SPAN_SUBTYPE, - SPAN_TYPE + SPAN_TYPE, } from './elasticsearch_fieldnames'; export interface ServiceConnectionNode extends cytoscape.NodeDataDefinition { @@ -50,6 +50,6 @@ export const invalidLicenseMessage = i18n.translate( 'xpack.apm.serviceMap.invalidLicenseMessage', { defaultMessage: - "In order to access Service Maps, you must be subscribed to an Elastic Platinum license. With it, you'll have the ability to visualize your entire application stack along with your APM data." + "In order to access Service Maps, you must be subscribed to an Elastic Platinum license. With it, you'll have the ability to visualize your entire application stack along with your APM data.", } ); diff --git a/x-pack/plugins/apm/common/viz_colors.ts b/x-pack/plugins/apm/common/viz_colors.ts index cc070005409b6..fcc1460576825 100644 --- a/x-pack/plugins/apm/common/viz_colors.ts +++ b/x-pack/plugins/apm/common/viz_colors.ts @@ -17,7 +17,7 @@ function getVizColorsForTheme(theme = lightTheme) { theme.euiColorVis6, theme.euiColorVis7, theme.euiColorVis8, - theme.euiColorVis9 + theme.euiColorVis9, ]; } diff --git a/x-pack/plugins/apm/e2e/cypress/plugins/index.js b/x-pack/plugins/apm/e2e/cypress/plugins/index.js index 15e469f187651..540b887d55df5 100644 --- a/x-pack/plugins/apm/e2e/cypress/plugins/index.js +++ b/x-pack/plugins/apm/e2e/cypress/plugins/index.js @@ -21,9 +21,9 @@ const wp = require('@cypress/webpack-preprocessor'); const fs = require('fs'); -module.exports = on => { +module.exports = (on) => { const options = { - webpackOptions: require('../webpack.config.js') + webpackOptions: require('../webpack.config.js'), }; on('file:preprocessor', wp(options)); @@ -35,6 +35,6 @@ module.exports = on => { } return null; - } + }, }); }; diff --git a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/apm.ts b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/apm.ts index 7160d5524759d..1e3228fdb0319 100644 --- a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/apm.ts +++ b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/apm.ts @@ -14,9 +14,7 @@ Given(`a user browses the APM UI application`, () => { When(`the user inspects the opbeans-node service`, () => { // click opbeans-node service - cy.get(':contains(opbeans-node)') - .last() - .click({ force: true }); + cy.get(':contains(opbeans-node)').last().click({ force: true }); }); Then(`should redirect to correct path with correct params`, () => { @@ -31,18 +29,9 @@ Then(`should have correct y-axis ticks`, () => { // wait for all loading to finish cy.get('kbnLoadingIndicator').should('not.be.visible'); - cy.get(yAxisTick) - .eq(2) - .invoke('text') - .snapshot(); + cy.get(yAxisTick).eq(2).invoke('text').snapshot(); - cy.get(yAxisTick) - .eq(1) - .invoke('text') - .snapshot(); + cy.get(yAxisTick).eq(1).invoke('text').snapshot(); - cy.get(yAxisTick) - .eq(0) - .invoke('text') - .snapshot(); + cy.get(yAxisTick).eq(0).invoke('text').snapshot(); }); diff --git a/x-pack/plugins/apm/e2e/cypress/webpack.config.js b/x-pack/plugins/apm/e2e/cypress/webpack.config.js index 8db6a1ef83520..86729ac14346e 100644 --- a/x-pack/plugins/apm/e2e/cypress/webpack.config.js +++ b/x-pack/plugins/apm/e2e/cypress/webpack.config.js @@ -6,7 +6,7 @@ module.exports = { resolve: { - extensions: ['.ts', '.js'] + extensions: ['.ts', '.js'], }, node: { fs: 'empty', child_process: 'empty', readline: 'empty' }, module: { @@ -17,26 +17,26 @@ module.exports = { include: [/e2e\/cypress/], use: [ { - loader: 'ts-loader' - } - ] + loader: 'ts-loader', + }, + ], }, { test: /\.feature$/, use: [ { - loader: 'cypress-cucumber-preprocessor/loader' - } - ] + loader: 'cypress-cucumber-preprocessor/loader', + }, + ], }, { test: /\.features$/, use: [ { - loader: 'cypress-cucumber-preprocessor/lib/featuresLoader' - } - ] - } - ] - } + loader: 'cypress-cucumber-preprocessor/lib/featuresLoader', + }, + ], + }, + ], + }, }; diff --git a/x-pack/plugins/apm/e2e/ingest-data/replay.js b/x-pack/plugins/apm/e2e/ingest-data/replay.js index 5301eafece06d..ae3f62894afc0 100644 --- a/x-pack/plugins/apm/e2e/ingest-data/replay.js +++ b/x-pack/plugins/apm/e2e/ingest-data/replay.js @@ -53,7 +53,7 @@ if (!EVENTS_PATH) { const requestProgress = { succeeded: 0, failed: 0, - total: 0 + total: 0, }; const spinner = ora({ text: 'Warming up...', stream: process.stdout }); @@ -71,7 +71,7 @@ async function insertItem(item) { try { const url = `${APM_SERVER_URL}${item.url}`; const headers = { - 'content-type': 'application/x-ndjson' + 'content-type': 'application/x-ndjson', }; if (SECRET_TOKEN) { @@ -82,7 +82,7 @@ async function insertItem(item) { method: item.method, url, headers, - data: item.body + data: item.body, }); } catch (e) { console.error( @@ -97,16 +97,16 @@ async function init() { const items = content .toString() .split('\n') - .filter(item => item) - .map(item => JSON.parse(item)) - .filter(item => item.url === '/intake/v2/events'); + .filter((item) => item) + .map((item) => JSON.parse(item)) + .filter((item) => item.url === '/intake/v2/events'); spinner.start(); requestProgress.total = items.length; const limit = pLimit(20); // number of concurrent requests await Promise.all( - items.map(async item => { + items.map(async (item) => { try { // retry 5 times with exponential backoff await pRetry(() => limit(() => insertItem(item)), { retries: 5 }); @@ -132,7 +132,7 @@ init() process.exit(1); } }) - .catch(e => { + .catch((e) => { console.log('An error occurred:', e); process.exit(1); }); diff --git a/x-pack/plugins/apm/public/application/index.tsx b/x-pack/plugins/apm/public/application/index.tsx index 6c1c3d3262a0e..cb8600ed2c214 100644 --- a/x-pack/plugins/apm/public/application/index.tsx +++ b/x-pack/plugins/apm/public/application/index.tsx @@ -54,7 +54,7 @@ const ApmAppRoot = ({ core, deps, routerHistory, - config + config, }: { core: CoreStart; deps: ApmPluginSetupDeps; @@ -66,7 +66,7 @@ const ApmAppRoot = ({ const apmPluginContextValue = { config, core, - plugins + plugins, }; return ( @@ -77,7 +77,7 @@ const ApmAppRoot = ({ capabilities: core.application.capabilities, toastNotifications: core.notifications.toasts, actionTypeRegistry: plugins.triggers_actions_ui.actionTypeRegistry, - alertTypeRegistry: plugins.triggers_actions_ui.alertTypeRegistry + alertTypeRegistry: plugins.triggers_actions_ui.alertTypeRegistry, }} > diff --git a/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.test.tsx b/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.test.tsx index b3f90fd9aee34..f42ae4596c3a9 100644 --- a/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.test.tsx @@ -11,21 +11,21 @@ import { APMIndicesPermission } from './'; import * as hooks from '../../../hooks/useFetcher'; import { expectTextsInDocument, - expectTextsNotInDocument + expectTextsNotInDocument, } from '../../../utils/testHelpers'; import { MockApmPluginContextWrapper } from '../../../context/ApmPluginContext/MockApmPluginContext'; describe('APMIndicesPermission', () => { it('returns empty component when api status is loading', () => { spyOn(hooks, 'useFetcher').and.returnValue({ - status: hooks.FETCH_STATUS.LOADING + status: hooks.FETCH_STATUS.LOADING, }); const component = shallow(); expect(component.isEmptyRender()).toBeTruthy(); }); it('returns empty component when api status is pending', () => { spyOn(hooks, 'useFetcher').and.returnValue({ - status: hooks.FETCH_STATUS.PENDING + status: hooks.FETCH_STATUS.PENDING, }); const component = shallow(); expect(component.isEmptyRender()).toBeTruthy(); @@ -36,9 +36,9 @@ describe('APMIndicesPermission', () => { data: { has_all_requested: false, index: { - 'apm-*': { read: false } - } - } + 'apm-*': { read: false }, + }, + }, }); const component = render( @@ -48,7 +48,7 @@ describe('APMIndicesPermission', () => { expectTextsInDocument(component, [ 'Missing permissions to access APM', 'Dismiss', - 'apm-*' + 'apm-*', ]); }); @@ -57,8 +57,8 @@ describe('APMIndicesPermission', () => { status: hooks.FETCH_STATUS.SUCCESS, data: { has_all_requested: false, - index: {} - } + index: {}, + }, }); const component = render( @@ -76,8 +76,8 @@ describe('APMIndicesPermission', () => { status: hooks.FETCH_STATUS.SUCCESS, data: { has_all_requested: true, - index: {} - } + index: {}, + }, }); const component = render( @@ -99,9 +99,9 @@ describe('APMIndicesPermission', () => { 'apm-error-*': { read: false }, 'apm-trasanction-*': { read: false }, 'apm-metrics-*': { read: true }, - 'apm-span-*': { read: true } - } - } + 'apm-span-*': { read: true }, + }, + }, }); const component = render( @@ -113,7 +113,7 @@ describe('APMIndicesPermission', () => { expectTextsInDocument(component, [ 'Dismiss', 'apm-error-*', - 'apm-trasanction-*' + 'apm-trasanction-*', ]); act(() => { fireEvent.click(component.getByText('Dismiss')); @@ -135,7 +135,7 @@ describe('APMIndicesPermission', () => { 'apm-7.5.1-error-*', 'apm-7.5.1-metric-*', 'apm-7.5.1-transaction-*', - 'apm-7.5.1-span-*' + 'apm-7.5.1-span-*', ]); expectTextsInDocument(component, ['My amazing component']); }); diff --git a/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.tsx b/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.tsx index 9074726f76e6d..f55f26fe7fc3c 100644 --- a/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.tsx +++ b/x-pack/plugins/apm/public/components/app/APMIndicesPermission/index.tsx @@ -12,7 +12,7 @@ import { EuiLink, EuiPanel, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; @@ -26,12 +26,12 @@ import { SetupInstructionsLink } from '../../shared/Links/SetupInstructionsLink' export const APMIndicesPermission: React.FC = ({ children }) => { const [ isPermissionWarningDismissed, - setIsPermissionWarningDismissed + setIsPermissionWarningDismissed, ] = useState(false); - const { data: indicesPrivileges, status } = useFetcher(callApmApi => { + const { data: indicesPrivileges, status } = useFetcher((callApmApi) => { return callApmApi({ - pathname: '/api/apm/security/indices_privileges' + pathname: '/api/apm/security/indices_privileges', }); }, []); @@ -50,7 +50,7 @@ export const APMIndicesPermission: React.FC = ({ children }) => { ) { const indicesWithoutPermission = Object.keys( indicesPrivileges.index - ).filter(index => !indicesPrivileges.index[index].read); + ).filter((index) => !indicesPrivileges.index[index].read); return ( { return (
    @@ -92,7 +92,7 @@ const PermissionWarning = ({

    {i18n.translate('xpack.apm.permission.apm', { - defaultMessage: 'APM' + defaultMessage: 'APM', })}

    @@ -110,7 +110,7 @@ const PermissionWarning = ({ title={

    {i18n.translate('xpack.apm.permission.title', { - defaultMessage: 'Missing permissions to access APM' + defaultMessage: 'Missing permissions to access APM', })}

    } @@ -119,11 +119,11 @@ const PermissionWarning = ({

    {i18n.translate('xpack.apm.permission.description', { defaultMessage: - "Your user doesn't have access to all APM indices. You can still use the APM app but some data may be missing. You must be granted access to the following indices:" + "Your user doesn't have access to all APM indices. You can still use the APM app but some data may be missing. You must be granted access to the following indices:", })}

      - {indicesWithoutPermission.map(index => ( + {indicesWithoutPermission.map((index) => (
    • {index}
    • @@ -140,7 +140,7 @@ const PermissionWarning = ({ {(href: string) => ( {i18n.translate('xpack.apm.permission.learnMore', { - defaultMessage: 'Learn more about APM permissions' + defaultMessage: 'Learn more about APM permissions', })} )} @@ -152,7 +152,7 @@ const PermissionWarning = ({ style={{ fontSize }} > {i18n.translate('xpack.apm.permission.dismissWarning', { - defaultMessage: 'Dismiss' + defaultMessage: 'Dismiss', })} diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ErrorTabs.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ErrorTabs.tsx index 5982346d97b89..922ee72729e1c 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ErrorTabs.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ErrorTabs.tsx @@ -16,8 +16,8 @@ export interface ErrorTab { export const logStacktraceTab: ErrorTab = { key: 'log_stacktrace', label: i18n.translate('xpack.apm.propertiesTable.tabs.logStacktraceLabel', { - defaultMessage: 'Log stack trace' - }) + defaultMessage: 'Log stack trace', + }), }; export const exceptionStacktraceTab: ErrorTab = { @@ -25,16 +25,16 @@ export const exceptionStacktraceTab: ErrorTab = { label: i18n.translate( 'xpack.apm.propertiesTable.tabs.exceptionStacktraceLabel', { - defaultMessage: 'Exception stack trace' + defaultMessage: 'Exception stack trace', } - ) + ), }; export const metadataTab: ErrorTab = { key: 'metadata', label: i18n.translate('xpack.apm.propertiesTable.tabs.metadataLabel', { - defaultMessage: 'Metadata' - }) + defaultMessage: 'Metadata', + }), }; export function getTabs(error: APMError) { @@ -42,6 +42,6 @@ export function getTabs(error: APMError) { return [ ...(hasLogStacktrace ? [logStacktraceTab] : []), exceptionStacktraceTab, - metadataTab + metadataTab, ]; } diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.tsx index faec93013886c..aef87e50477d8 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/ExceptionStacktrace.tsx @@ -17,7 +17,7 @@ interface ExceptionStacktraceProps { export function ExceptionStacktrace({ codeLanguage, - exceptions + exceptions, }: ExceptionStacktraceProps) { const title = exceptions[0]?.message; diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.test.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.test.tsx index 7fe1386ba6414..a602c227a8915 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.test.tsx @@ -33,15 +33,15 @@ describe('DetailView', () => { transaction: undefined, error: { timestamp: { - us: 0 + us: 0, }, http: { request: { method: 'GET' } }, url: { full: 'myUrl' }, service: { name: 'myService' }, user: { id: 'myUserId' }, error: { exception: { handled: true } }, - transaction: { id: 'myTransactionId', sampled: true } - } as any + transaction: { id: 'myTransactionId', sampled: true }, + } as any, }; const wrapper = shallow( @@ -62,10 +62,10 @@ describe('DetailView', () => { error: { error: {}, timestamp: { - us: 0 - } + us: 0, + }, } as any, - transaction: undefined + transaction: undefined, }; const wrapper = shallow( { transaction: undefined, error: { timestamp: { - us: 0 + us: 0, }, error: {}, service: {}, - user: {} - } as any + user: {}, + } as any, }; const wrapper = shallow( { transaction: undefined, error: { timestamp: { - us: 0 + us: 0, }, error: {}, - context: {} - } as any + context: {}, + } as any, }; const wrapper = shallow( { transaction: undefined, error: { timestamp: { - us: 0 + us: 0, }, http: { response: { status_code: 404 } }, url: { full: 'myUrl' }, service: { name: 'myService' }, user: { id: 'myUserId' }, error: { exception: { handled: true } }, - transaction: { id: 'myTransactionId', sampled: true } - } as any + transaction: { id: 'myTransactionId', sampled: true }, + } as any, }; expect(() => shallow( diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.tsx index 9e2fd776e67a3..7ee8dfa496b57 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.tsx @@ -12,7 +12,7 @@ import { EuiTabs, EuiTitle, EuiIcon, - EuiToolTip + EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { Location } from 'history'; @@ -33,7 +33,7 @@ import { ErrorTab, exceptionStacktraceTab, getTabs, - logStacktraceTab + logStacktraceTab, } from './ErrorTabs'; import { Summary } from '../../../shared/Summary'; import { TimestampTooltip } from '../../../shared/TimestampTooltip'; @@ -93,7 +93,7 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { {i18n.translate( 'xpack.apm.errorGroupDetails.errorOccurrenceTitle', { - defaultMessage: 'Error occurrence' + defaultMessage: 'Error occurrence', } )} @@ -105,7 +105,7 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { { defaultMessage: 'View {occurrencesCount} {occurrencesCount, plural, one {occurrence} other {occurrences}} in Discover.', - values: { occurrencesCount } + values: { occurrencesCount }, } )} @@ -130,7 +130,7 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { content={i18n.translate( 'xpack.apm.errorGroupDetails.relatedTransactionSample', { - defaultMessage: 'Related transaction sample' + defaultMessage: 'Related transaction sample', } )} > @@ -147,7 +147,7 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { - ) + ), ]} /> @@ -162,8 +162,8 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { ...location, search: fromQuery({ ...toQuery(location.search), - detailTab: key - }) + detailTab: key, + }), }); }} isSelected={currentTab.key === key} @@ -182,7 +182,7 @@ export function DetailView({ errorGroup, urlParams, location }: Props) { function TabContent({ error, - currentTab + currentTab, }: { error: APMError; currentTab: ErrorTab; diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx index c67bb491910b7..796f2992236f9 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx @@ -45,7 +45,7 @@ export function getFormattedBuckets( return { x0: key, x: key + bucketSize, - y: count + y: count, }; }); } @@ -68,17 +68,15 @@ export function ErrorDistribution({ distribution, title }: Props) { return ( ); } - const xMin = d3.min(buckets, d => d.x0); - const xMax = d3.max(buckets, d => d.x); - const tickFormat = scaleUtc() - .domain([xMin, xMax]) - .tickFormat(); + const xMin = d3.min(buckets, (d) => d.x0); + const xMax = d3.max(buckets, (d) => d.x); + const tickFormat = scaleUtc().domain([xMin, xMax]).tickFormat(); return (
      @@ -98,13 +96,13 @@ export function ErrorDistribution({ distribution, title }: Props) { formatYShort={(value: number) => i18n.translate('xpack.apm.errorGroupDetails.occurrencesShortLabel', { defaultMessage: '{occCount} occ.', - values: { occCount: value } + values: { occCount: value }, }) } formatYLong={(value: number) => i18n.translate('xpack.apm.errorGroupDetails.occurrencesLongLabel', { defaultMessage: '{occCount} occurrences', - values: { occCount: value } + values: { occCount: value }, }) } /> diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx index c40c711a590be..d8885ec11c511 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx @@ -11,7 +11,7 @@ import { EuiPanel, EuiSpacer, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import theme from '@elastic/eui/dist/eui_theme_light.json'; import { i18n } from '@kbn/i18n'; @@ -62,21 +62,21 @@ export function ErrorGroupDetails() { const { serviceName, start, end, errorGroupId } = urlParams; const { data: errorGroupData } = useFetcher( - callApmApi => { + (callApmApi) => { if (serviceName && start && end && errorGroupId) { return callApmApi({ pathname: '/api/apm/services/{serviceName}/errors/{groupId}', params: { path: { serviceName, - groupId: errorGroupId + groupId: errorGroupId, }, query: { start, end, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -84,21 +84,21 @@ export function ErrorGroupDetails() { ); const { data: errorDistributionData } = useFetcher( - callApmApi => { + (callApmApi) => { if (serviceName && start && end && errorGroupId) { return callApmApi({ pathname: '/api/apm/services/{serviceName}/errors/distribution', params: { path: { - serviceName + serviceName, }, query: { start, end, groupId: errorGroupId, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -130,8 +130,8 @@ export function ErrorGroupDetails() { {i18n.translate('xpack.apm.errorGroupDetails.errorGroupTitle', { defaultMessage: 'Error group {errorGroupId}', values: { - errorGroupId: getShortGroupId(urlParams.errorGroupId) - } + errorGroupId: getShortGroupId(urlParams.errorGroupId), + }, })} @@ -140,7 +140,7 @@ export function ErrorGroupDetails() { {i18n.translate('xpack.apm.errorGroupDetails.unhandledLabel', { - defaultMessage: 'Unhandled' + defaultMessage: 'Unhandled', })} @@ -160,7 +160,7 @@ export function ErrorGroupDetails() { {i18n.translate( 'xpack.apm.errorGroupDetails.logMessageLabel', { - defaultMessage: 'Log message' + defaultMessage: 'Log message', } )} @@ -171,14 +171,14 @@ export function ErrorGroupDetails() { {i18n.translate( 'xpack.apm.errorGroupDetails.exceptionMessageLabel', { - defaultMessage: 'Exception message' + defaultMessage: 'Exception message', } )} {excMessage || NOT_AVAILABLE_LABEL} {culprit || NOT_AVAILABLE_LABEL} @@ -191,7 +191,7 @@ export function ErrorGroupDetails() { title={i18n.translate( 'xpack.apm.errorGroupDetails.occurrencesChartLabel', { - defaultMessage: 'Occurrences' + defaultMessage: 'Occurrences', } )} /> diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx index 56c80690eb2a2..ed683b8ecd11d 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/List/index.tsx @@ -18,7 +18,7 @@ import { fontSizes, px, truncate, - unit + unit, } from '../../../../style/variables'; import { useUrlParams } from '../../../../hooks/useUrlParams'; import { ManagedTable } from '../../../shared/ManagedTable'; @@ -53,7 +53,7 @@ interface Props { items: ErrorGroupListAPIResponse; } -const ErrorGroupList: React.FC = props => { +const ErrorGroupList: React.FC = (props) => { const { items } = props; const { urlParams } = useUrlParams(); const { serviceName } = urlParams; @@ -67,20 +67,20 @@ const ErrorGroupList: React.FC = props => { name: ( <> {i18n.translate('xpack.apm.errorsTable.groupIdColumnLabel', { - defaultMessage: 'Group ID' + defaultMessage: 'Group ID', })}{' '} @@ -95,11 +95,11 @@ const ErrorGroupList: React.FC = props => { {groupId.slice(0, 5) || NOT_AVAILABLE_LABEL} ); - } + }, }, { name: i18n.translate('xpack.apm.errorsTable.typeColumnLabel', { - defaultMessage: 'Type' + defaultMessage: 'Type', }), field: 'type', sortable: false, @@ -111,20 +111,20 @@ const ErrorGroupList: React.FC = props => { query={ { ...urlParams, - kuery: `error.exception.type:${type}` + kuery: `error.exception.type:${type}`, } as APMQueryParams } > {type} ); - } + }, }, { name: i18n.translate( 'xpack.apm.errorsTable.errorMessageAndCulpritColumnLabel', { - defaultMessage: 'Error message and culprit' + defaultMessage: 'Error message and culprit', } ), field: 'message', @@ -153,7 +153,7 @@ const ErrorGroupList: React.FC = props => { ); - } + }, }, { name: '', @@ -164,20 +164,20 @@ const ErrorGroupList: React.FC = props => { isUnhandled === false && ( {i18n.translate('xpack.apm.errorsTable.unhandledLabel', { - defaultMessage: 'Unhandled' + defaultMessage: 'Unhandled', })} - ) + ), }, { name: i18n.translate('xpack.apm.errorsTable.occurrencesColumnLabel', { - defaultMessage: 'Occurrences' + defaultMessage: 'Occurrences', }), field: 'occurrenceCount', sortable: true, dataType: 'number', render: (value?: number) => - value ? numeral(value).format('0.[0]a') : NOT_AVAILABLE_LABEL + value ? numeral(value).format('0.[0]a') : NOT_AVAILABLE_LABEL, }, { field: 'latestOccurrenceAt', @@ -185,7 +185,7 @@ const ErrorGroupList: React.FC = props => { name: i18n.translate( 'xpack.apm.errorsTable.latestOccurrenceColumnLabel', { - defaultMessage: 'Latest occurrence' + defaultMessage: 'Latest occurrence', } ), align: 'right', @@ -194,8 +194,8 @@ const ErrorGroupList: React.FC = props => { ) : ( NOT_AVAILABLE_LABEL - ) - } + ), + }, ], [serviceName, urlParams] ); @@ -203,7 +203,7 @@ const ErrorGroupList: React.FC = props => { return ( { const { serviceName, start, end, sortField, sortDirection } = urlParams; const { data: errorDistributionData } = useFetcher( - callApmApi => { + (callApmApi) => { if (serviceName && start && end) { return callApmApi({ pathname: '/api/apm/services/{serviceName}/errors/distribution', params: { path: { - serviceName + serviceName, }, query: { start, end, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -48,7 +48,7 @@ const ErrorGroupOverview: React.FC = () => { ); const { data: errorGroupListData } = useFetcher( - callApmApi => { + (callApmApi) => { const normalizedSortDirection = sortDirection === 'asc' ? 'asc' : 'desc'; if (serviceName && start && end) { @@ -56,16 +56,16 @@ const ErrorGroupOverview: React.FC = () => { pathname: '/api/apm/services/{serviceName}/errors', params: { path: { - serviceName + serviceName, }, query: { start, end, sortField, sortDirection: normalizedSortDirection, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -74,7 +74,7 @@ const ErrorGroupOverview: React.FC = () => { useTrackPageview({ app: 'apm', - path: 'error_group_overview' + path: 'error_group_overview', }); useTrackPageview({ app: 'apm', path: 'error_group_overview', delay: 15000 }); @@ -82,9 +82,9 @@ const ErrorGroupOverview: React.FC = () => { const config: React.ComponentProps = { filterNames: ['host', 'containerId', 'podName', 'serviceVersion'], params: { - serviceName + serviceName, }, - projection: PROJECTION.ERROR_GROUPS + projection: PROJECTION.ERROR_GROUPS, }; return config; @@ -110,7 +110,7 @@ const ErrorGroupOverview: React.FC = () => { title={i18n.translate( 'xpack.apm.serviceDetails.metrics.errorOccurrencesChartTitle', { - defaultMessage: 'Error occurrences' + defaultMessage: 'Error occurrences', } )} /> diff --git a/x-pack/plugins/apm/public/components/app/Home/index.tsx b/x-pack/plugins/apm/public/components/app/Home/index.tsx index 07d7ce1e5b48c..74cbc00b17889 100644 --- a/x-pack/plugins/apm/public/components/app/Home/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Home/index.tsx @@ -9,7 +9,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiTabs, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; @@ -27,7 +27,7 @@ import { ServiceOverview } from '../ServiceOverview'; import { TraceOverview } from '../TraceOverview'; function getHomeTabs({ - serviceMapEnabled = true + serviceMapEnabled = true, }: { serviceMapEnabled: boolean; }) { @@ -36,24 +36,24 @@ function getHomeTabs({ link: ( {i18n.translate('xpack.apm.home.servicesTabLabel', { - defaultMessage: 'Services' + defaultMessage: 'Services', })} ), render: () => , - name: 'services' + name: 'services', }, { link: ( {i18n.translate('xpack.apm.home.tracesTabLabel', { - defaultMessage: 'Traces' + defaultMessage: 'Traces', })} ), render: () => , - name: 'traces' - } + name: 'traces', + }, ]; if (serviceMapEnabled) { @@ -61,19 +61,19 @@ function getHomeTabs({ link: ( {i18n.translate('xpack.apm.home.serviceMapTabLabel', { - defaultMessage: 'Service Map' + defaultMessage: 'Service Map', })} ), render: () => , - name: 'service-map' + name: 'service-map', }); } return homeTabs; } const SETTINGS_LINK_LABEL = i18n.translate('xpack.apm.settingsLinkLabel', { - defaultMessage: 'Settings' + defaultMessage: 'Settings', }); interface Props { @@ -84,7 +84,7 @@ export function Home({ tab }: Props) { const { config } = useApmPluginContext(); const homeTabs = getHomeTabs(config); const selectedTab = homeTabs.find( - homeTab => homeTab.name === tab + (homeTab) => homeTab.name === tab ) as $ElementType; return ( @@ -109,7 +109,7 @@ export function Home({ tab }: Props) { - {homeTabs.map(homeTab => ( + {homeTabs.map((homeTab) => ( {homeTab.link} diff --git a/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.test.tsx b/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.test.tsx index 1e3a73acfab57..c6e2c0eff8166 100644 --- a/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.test.tsx @@ -15,34 +15,34 @@ describe('getBreadcrumbs', () => { path: '/a/ignored', exact: true, breadcrumb: 'Ignored Route', - name: RouteName.METRICS + name: RouteName.METRICS, }, { path: '/a/:letter', exact: true, name: RouteName.SERVICE, - breadcrumb: ({ match }) => `Second level: ${match.params.letter}` + breadcrumb: ({ match }) => `Second level: ${match.params.letter}`, }, { path: '/a/:letter/c', exact: true, name: RouteName.ERRORS, - breadcrumb: ({ match }) => `Third level: ${match.params.letter}` - } + breadcrumb: ({ match }) => `Third level: ${match.params.letter}`, + }, ]; const getLocation = () => ({ - pathname: '/a/b/c/' + pathname: '/a/b/c/', } as Location); it('should return a set of matching breadcrumbs for a given path', () => { const breadcrumbs = getBreadcrumbs({ location: getLocation(), - routes: getTestRoutes() + routes: getTestRoutes(), }); - expect(breadcrumbs.map(b => b.value)).toMatchInlineSnapshot(` + expect(breadcrumbs.map((b) => b.value)).toMatchInlineSnapshot(` Array [ "A", "Second level: b", @@ -59,10 +59,10 @@ Array [ const breadcrumbs = getBreadcrumbs({ location, - routes + routes, }); - expect(breadcrumbs.map(b => b.value)).toMatchInlineSnapshot(` + expect(breadcrumbs.map((b) => b.value)).toMatchInlineSnapshot(` Array [ "A", "Third level: b", @@ -78,7 +78,7 @@ Array [ const breadcrumbs = getBreadcrumbs({ location, routes }); - expect(breadcrumbs.map(b => b.value)).toMatchInlineSnapshot(` + expect(breadcrumbs.map((b) => b.value)).toMatchInlineSnapshot(` Array [ "A", "Third level: b", @@ -94,10 +94,10 @@ Array [ const breadcrumbs = getBreadcrumbs({ location, - routes + routes, }); - expect(breadcrumbs.map(b => b.value)).toMatchInlineSnapshot(` + expect(breadcrumbs.map((b) => b.value)).toMatchInlineSnapshot(` Array [ "A", "Second level: b", diff --git a/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.tsx b/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.tsx index cfbe8b1edbd71..f2505b64fb1e3 100644 --- a/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/ProvideBreadcrumbs.tsx @@ -10,7 +10,7 @@ import { matchPath, RouteComponentProps, RouteProps, - withRouter + withRouter, } from 'react-router-dom'; import { RouteName } from './route_config/route_names'; @@ -59,7 +59,7 @@ const parse = (options: ParseOptions) => { export function getBreadcrumb({ location, currentPath, - routes + routes, }: { location: Location; currentPath: string; @@ -80,7 +80,7 @@ export function getBreadcrumb({ return parse({ breadcrumb, match, - location + location, }); } @@ -90,7 +90,7 @@ export function getBreadcrumb({ export function getBreadcrumbs({ routes, - location + location, }: { routes: BreadcrumbRoute[]; location: Location; @@ -108,7 +108,7 @@ export function getBreadcrumbs({ const breadcrumb = getBreadcrumb({ location, currentPath, - routes + routes, }); if (breadcrumb) { @@ -126,7 +126,7 @@ function ProvideBreadcrumbsComponent({ render, location, match, - history + history, }: ProvideBreadcrumbsProps) { const breadcrumbs = getBreadcrumbs({ routes, location }); return render({ breadcrumbs, location, match, history }); diff --git a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx index e610f3b84899b..15be023c32e90 100644 --- a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.test.tsx @@ -12,7 +12,7 @@ import { routes } from './route_config'; import { UpdateBreadcrumbs } from './UpdateBreadcrumbs'; import { MockApmPluginContextWrapper, - mockApmPluginContextValue + mockApmPluginContextValue, } from '../../../context/ApmPluginContext/MockApmPluginContext'; const setBreadcrumbs = jest.fn(); @@ -27,9 +27,9 @@ function expectBreadcrumbToMatchSnapshot(route: string, params = '') { ...mockApmPluginContextValue.core, chrome: { ...mockApmPluginContextValue.core.chrome, - setBreadcrumbs - } - } + setBreadcrumbs, + }, + }, } as unknown) as ApmPluginContextValue } > @@ -48,7 +48,7 @@ describe('UpdateBreadcrumbs', () => { beforeEach(() => { realDoc = window.document; (window.document as any) = { - title: 'Kibana' + title: 'Kibana', }; setBreadcrumbs.mockReset(); }); diff --git a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx index b4a556c497c1b..7a27eae6e89f7 100644 --- a/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/UpdateBreadcrumbs.tsx @@ -11,7 +11,7 @@ import { getAPMHref } from '../../shared/Links/apm/APMLink'; import { Breadcrumb, ProvideBreadcrumbs, - BreadcrumbRoute + BreadcrumbRoute, } from './ProvideBreadcrumbs'; import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; @@ -38,7 +38,7 @@ class UpdateBreadcrumbsComponent extends React.Component { text: value, href: isLastBreadcrumbItem ? undefined // makes the breadcrumb item not clickable - : getAPMHref(match.url, this.props.location.search) + : getAPMHref(match.url, this.props.location.search), }; } ); diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx index 6d1db8c5dc6d4..577af75e92d9e 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx @@ -25,11 +25,11 @@ import { TraceLink } from '../../TraceLink'; import { CustomizeUI } from '../../Settings/CustomizeUI'; import { EditAgentConfigurationRouteHandler, - CreateAgentConfigurationRouteHandler + CreateAgentConfigurationRouteHandler, } from './route_handlers/agent_configuration'; const metricsBreadcrumb = i18n.translate('xpack.apm.breadcrumb.metricsTitle', { - defaultMessage: 'Metrics' + defaultMessage: 'Metrics', }); interface RouteParams { @@ -41,7 +41,7 @@ const renderAsRedirectTo = (to: string) => { ); @@ -53,34 +53,34 @@ export const routes: BreadcrumbRoute[] = [ path: '/', render: renderAsRedirectTo('/services'), breadcrumb: 'APM', - name: RouteName.HOME + name: RouteName.HOME, }, { exact: true, path: '/services', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.servicesTitle', { - defaultMessage: 'Services' + defaultMessage: 'Services', }), - name: RouteName.SERVICES + name: RouteName.SERVICES, }, { exact: true, path: '/traces', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.tracesTitle', { - defaultMessage: 'Traces' + defaultMessage: 'Traces', }), - name: RouteName.TRACES + name: RouteName.TRACES, }, { exact: true, path: '/settings', render: renderAsRedirectTo('/settings/agent-configuration'), breadcrumb: i18n.translate('xpack.apm.breadcrumb.listSettingsTitle', { - defaultMessage: 'Settings' + defaultMessage: 'Settings', }), - name: RouteName.SETTINGS + name: RouteName.SETTINGS, }, { exact: true, @@ -91,9 +91,9 @@ export const routes: BreadcrumbRoute[] = [ ), breadcrumb: i18n.translate('xpack.apm.breadcrumb.settings.indicesTitle', { - defaultMessage: 'Indices' + defaultMessage: 'Indices', }), - name: RouteName.INDICES + name: RouteName.INDICES, }, { exact: true, @@ -107,7 +107,7 @@ export const routes: BreadcrumbRoute[] = [ 'xpack.apm.breadcrumb.settings.agentConfigurationTitle', { defaultMessage: 'Agent Configuration' } ), - name: RouteName.AGENT_CONFIGURATION + name: RouteName.AGENT_CONFIGURATION, }, { @@ -118,7 +118,7 @@ export const routes: BreadcrumbRoute[] = [ { defaultMessage: 'Create Agent Configuration' } ), name: RouteName.AGENT_CONFIGURATION_CREATE, - component: () => + component: () => , }, { exact: true, @@ -128,7 +128,7 @@ export const routes: BreadcrumbRoute[] = [ { defaultMessage: 'Edit Agent Configuration' } ), name: RouteName.AGENT_CONFIGURATION_EDIT, - component: () => + component: () => , }, { exact: true, @@ -138,7 +138,7 @@ export const routes: BreadcrumbRoute[] = [ renderAsRedirectTo( `/services/${props.match.params.serviceName}/transactions` )(props), - name: RouteName.SERVICE + name: RouteName.SERVICE, }, // errors { @@ -146,16 +146,16 @@ export const routes: BreadcrumbRoute[] = [ path: '/services/:serviceName/errors/:groupId', component: ErrorGroupDetails, breadcrumb: ({ match }) => match.params.groupId, - name: RouteName.ERROR + name: RouteName.ERROR, }, { exact: true, path: '/services/:serviceName/errors', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.errorsTitle', { - defaultMessage: 'Errors' + defaultMessage: 'Errors', }), - name: RouteName.ERRORS + name: RouteName.ERRORS, }, // transactions { @@ -163,9 +163,9 @@ export const routes: BreadcrumbRoute[] = [ path: '/services/:serviceName/transactions', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.transactionsTitle', { - defaultMessage: 'Transactions' + defaultMessage: 'Transactions', }), - name: RouteName.TRANSACTIONS + name: RouteName.TRANSACTIONS, }, // metrics { @@ -173,7 +173,7 @@ export const routes: BreadcrumbRoute[] = [ path: '/services/:serviceName/metrics', component: () => , breadcrumb: metricsBreadcrumb, - name: RouteName.METRICS + name: RouteName.METRICS, }, // service nodes, only enabled for java agents for now { @@ -181,9 +181,9 @@ export const routes: BreadcrumbRoute[] = [ path: '/services/:serviceName/nodes', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.nodesTitle', { - defaultMessage: 'JVMs' + defaultMessage: 'JVMs', }), - name: RouteName.SERVICE_NODES + name: RouteName.SERVICE_NODES, }, // node metrics { @@ -199,7 +199,7 @@ export const routes: BreadcrumbRoute[] = [ return serviceNodeName || ''; }, - name: RouteName.SERVICE_NODE_METRICS + name: RouteName.SERVICE_NODE_METRICS, }, { exact: true, @@ -209,14 +209,14 @@ export const routes: BreadcrumbRoute[] = [ const query = toQuery(location.search); return query.transactionName as string; }, - name: RouteName.TRANSACTION_NAME + name: RouteName.TRANSACTION_NAME, }, { exact: true, path: '/link-to/trace/:traceId', component: TraceLink, breadcrumb: null, - name: RouteName.LINK_TO_TRACE + name: RouteName.LINK_TO_TRACE, }, { @@ -224,18 +224,18 @@ export const routes: BreadcrumbRoute[] = [ path: '/service-map', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.serviceMapTitle', { - defaultMessage: 'Service Map' + defaultMessage: 'Service Map', }), - name: RouteName.SERVICE_MAP + name: RouteName.SERVICE_MAP, }, { exact: true, path: '/services/:serviceName/service-map', component: () => , breadcrumb: i18n.translate('xpack.apm.breadcrumb.serviceMapTitle', { - defaultMessage: 'Service Map' + defaultMessage: 'Service Map', }), - name: RouteName.SINGLE_SERVICE_MAP + name: RouteName.SINGLE_SERVICE_MAP, }, { exact: true, @@ -246,8 +246,8 @@ export const routes: BreadcrumbRoute[] = [ ), breadcrumb: i18n.translate('xpack.apm.breadcrumb.settings.customizeUI', { - defaultMessage: 'Customize UI' + defaultMessage: 'Customize UI', }), - name: RouteName.CUSTOMIZE_UI - } + name: RouteName.CUSTOMIZE_UI, + }, ]; diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/route_handlers/agent_configuration.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/route_handlers/agent_configuration.tsx index 58087f0d8be42..14c912d0bd519 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/route_handlers/agent_configuration.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/route_handlers/agent_configuration.tsx @@ -20,10 +20,10 @@ export function EditAgentConfigurationRouteHandler() { const { name, environment, pageStep } = toQuery(search); const res = useFetcher( - callApmApi => { + (callApmApi) => { return callApmApi({ pathname: '/api/apm/settings/agent-configuration/view', - params: { query: { name, environment } } + params: { query: { name, environment } }, }); }, [name, environment] diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx index 33a4990cb549e..167de1a37f427 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx @@ -25,5 +25,5 @@ export enum RouteName { INDICES = 'indices', SERVICE_NODES = 'nodes', LINK_TO_TRACE = 'link_to_trace', - CUSTOMIZE_UI = 'customize_ui' + CUSTOMIZE_UI = 'customize_ui', } diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/AlertIntegrations/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/AlertIntegrations/index.tsx index 9001eb6992a96..bfb9e99b4fc4c 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/AlertIntegrations/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/AlertIntegrations/index.tsx @@ -8,7 +8,7 @@ import { EuiButtonEmpty, EuiContextMenu, EuiPopover, - EuiContextMenuPanelDescriptor + EuiContextMenuPanelDescriptor, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; @@ -19,14 +19,14 @@ import { useApmPluginContext } from '../../../../hooks/useApmPluginContext'; const alertLabel = i18n.translate( 'xpack.apm.serviceDetails.alertsMenu.alerts', { - defaultMessage: 'Alerts' + defaultMessage: 'Alerts', } ); const createThresholdAlertLabel = i18n.translate( 'xpack.apm.serviceDetails.alertsMenu.createThresholdAlert', { - defaultMessage: 'Create threshold alert' + defaultMessage: 'Create threshold alert', } ); @@ -53,7 +53,7 @@ export function AlertIntegrations(props: Props) { onClick={() => setPopoverOpen(true)} > {i18n.translate('xpack.apm.serviceDetails.alertsMenu.alerts', { - defaultMessage: 'Alerts' + defaultMessage: 'Alerts', })} ); @@ -68,8 +68,8 @@ export function AlertIntegrations(props: Props) { { name: createThresholdAlertLabel, panel: CREATE_THRESHOLD_ALERT_PANEL_ID, - icon: 'bell' - } + icon: 'bell', + }, ] : []), ...(canReadAlerts @@ -78,17 +78,17 @@ export function AlertIntegrations(props: Props) { name: i18n.translate( 'xpack.apm.serviceDetails.alertsMenu.viewActiveAlerts', { - defaultMessage: 'View active alerts' + defaultMessage: 'View active alerts', } ), href: plugin.core.http.basePath.prepend( '/app/kibana#/management/insightsAndAlerting/triggersActions/alerts' ), - icon: 'tableOfContents' - } + icon: 'tableOfContents', + }, ] - : []) - ] + : []), + ], }, { id: CREATE_THRESHOLD_ALERT_PANEL_ID, @@ -98,26 +98,26 @@ export function AlertIntegrations(props: Props) { name: i18n.translate( 'xpack.apm.serviceDetails.alertsMenu.transactionDuration', { - defaultMessage: 'Transaction duration' + defaultMessage: 'Transaction duration', } ), onClick: () => { setAlertType(AlertType.TransactionDuration); - } + }, }, { name: i18n.translate( 'xpack.apm.serviceDetails.alertsMenu.errorRate', { - defaultMessage: 'Error rate' + defaultMessage: 'Error rate', } ), onClick: () => { setAlertType(AlertType.ErrorRate); - } - } - ] - } + }, + }, + ], + }, ]; return ( @@ -135,7 +135,7 @@ export function AlertIntegrations(props: Props) { { + setAddFlyoutVisibility={(visible) => { if (!visible) { setAlertType(null); } diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx index 7ab2f7bac8ae2..2f35e329720de 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx @@ -42,26 +42,26 @@ export function ServiceDetailTabs({ tab }: Props) { link: ( {i18n.translate('xpack.apm.serviceDetails.transactionsTabLabel', { - defaultMessage: 'Transactions' + defaultMessage: 'Transactions', })} ), render: () => , - name: 'transactions' + name: 'transactions', }; const errorsTab = { link: ( {i18n.translate('xpack.apm.serviceDetails.errorsTabLabel', { - defaultMessage: 'Errors' + defaultMessage: 'Errors', })} ), render: () => { return ; }, - name: 'errors' + name: 'errors', }; const tabs = [transactionsTab, errorsTab]; @@ -71,12 +71,12 @@ export function ServiceDetailTabs({ tab }: Props) { link: ( {i18n.translate('xpack.apm.serviceDetails.nodesTabLabel', { - defaultMessage: 'JVMs' + defaultMessage: 'JVMs', })} ), render: () => , - name: 'nodes' + name: 'nodes', }; tabs.push(nodesListTab); } else if (agentName && !isRumAgentName(agentName)) { @@ -84,12 +84,12 @@ export function ServiceDetailTabs({ tab }: Props) { link: ( {i18n.translate('xpack.apm.serviceDetails.metricsTabLabel', { - defaultMessage: 'Metrics' + defaultMessage: 'Metrics', })} ), render: () => , - name: 'metrics' + name: 'metrics', }; tabs.push(metricsTab); } @@ -98,24 +98,24 @@ export function ServiceDetailTabs({ tab }: Props) { link: ( {i18n.translate('xpack.apm.home.serviceMapTabLabel', { - defaultMessage: 'Service Map' + defaultMessage: 'Service Map', })} ), render: () => , - name: 'service-map' + name: 'service-map', }; if (serviceMapEnabled) { tabs.push(serviceMapTab); } - const selectedTab = tabs.find(serviceTab => serviceTab.name === tab); + const selectedTab = tabs.find((serviceTab) => serviceTab.name === tab); return ( <> - {tabs.map(serviceTab => ( + {tabs.map((serviceTab) => ( { + options={transactionTypes.map((transactionType) => { return { value: transactionType, inputDisplay: transactionType, @@ -47,7 +47,7 @@ export function TransactionSelect({ {transactionType} - ) + ), }; })} /> diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/index.tsx index 0561a7d999a91..91778b2940c6b 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/index.tsx @@ -27,11 +27,11 @@ export class MachineLearningFlyout extends Component { static contextType = ApmPluginContext; public state: State = { - isCreatingJob: false + isCreatingJob: false, }; public onClickCreate = async ({ - transactionType + transactionType, }: { transactionType: string; }) => { @@ -75,7 +75,7 @@ export class MachineLearningFlyout extends Component { title: i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.jobCreationFailedNotificationTitle', { - defaultMessage: 'Job creation failed' + defaultMessage: 'Job creation failed', } ), text: toMountPoint( @@ -86,17 +86,17 @@ export class MachineLearningFlyout extends Component { 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.jobCreationFailedNotificationText', { defaultMessage: - 'Your current license may not allow for creating machine learning jobs, or this job may already exist.' + 'Your current license may not allow for creating machine learning jobs, or this job may already exist.', } )}

      - ) + ), }); }; public addSuccessToast = ({ - transactionType + transactionType, }: { transactionType: string; }) => { @@ -112,7 +112,7 @@ export class MachineLearningFlyout extends Component { title: i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.jobCreatedNotificationTitle', { - defaultMessage: 'Job successfully created' + defaultMessage: 'Job successfully created', } ), text: toMountPoint( @@ -124,8 +124,8 @@ export class MachineLearningFlyout extends Component { 'The analysis is now running for {serviceName} ({transactionType}). It might take a while before results are added to the response times graph.', values: { serviceName, - transactionType - } + transactionType, + }, } )}{' '} @@ -136,13 +136,13 @@ export class MachineLearningFlyout extends Component { {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.jobCreatedNotificationText.viewJobLinkText', { - defaultMessage: 'View job' + defaultMessage: 'View job', } )}

      - ) + ), }); }; diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/view.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/view.tsx index 77edf40fa89a8..72e8193ba2de2 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/view.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/MachineLearningFlyout/view.tsx @@ -16,7 +16,7 @@ import { EuiFormRow, EuiSpacer, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -42,7 +42,7 @@ export function MachineLearningFlyoutView({ isCreatingJob, onClickCreate, onClose, - urlParams + urlParams, }: Props) { const { serviceName } = urlParams; const transactionTypes = useServiceTransactionTypes(urlParams); @@ -59,7 +59,7 @@ export function MachineLearningFlyoutView({ return getHasMLJob({ serviceName, transactionType: selectedTransactionType, - http + http, }); } }, @@ -87,7 +87,7 @@ export function MachineLearningFlyoutView({ {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.enableAnomalyDetectionTitle', { - defaultMessage: 'Enable anomaly detection' + defaultMessage: 'Enable anomaly detection', } )} @@ -101,7 +101,7 @@ export function MachineLearningFlyoutView({ title={i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.callout.mlNotAvailable', { - defaultMessage: 'Machine learning not available' + defaultMessage: 'Machine learning not available', } )} color="warning" @@ -112,7 +112,7 @@ export function MachineLearningFlyoutView({ 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.callout.mlNotAvailableDescription', { defaultMessage: - 'Unable to connect to Machine learning. Make sure it is enabled in Kibana to use anomaly detection.' + 'Unable to connect to Machine learning. Make sure it is enabled in Kibana to use anomaly detection.', } )}

      @@ -126,7 +126,7 @@ export function MachineLearningFlyoutView({ title={i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.callout.jobExistsTitle', { - defaultMessage: 'Job already exists' + defaultMessage: 'Job already exists', } )} color="success" @@ -140,8 +140,8 @@ export function MachineLearningFlyoutView({ 'There is currently a job running for {serviceName} ({transactionType}).', values: { serviceName, - transactionType: selectedTransactionType - } + transactionType: selectedTransactionType, + }, } )}{' '} @@ -176,7 +176,7 @@ export function MachineLearningFlyoutView({ {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.createMLJobDescription.transactionDurationGraphText', { - defaultMessage: 'transaction duration' + defaultMessage: 'transaction duration', } )} @@ -186,11 +186,11 @@ export function MachineLearningFlyoutView({ {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.createMLJobDescription.serviceMapAnnotationText', { - defaultMessage: 'service maps' + defaultMessage: 'service maps', } )} - ) + ), }} />

      @@ -205,11 +205,11 @@ export function MachineLearningFlyoutView({ {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.manageMLJobDescription.mlJobsPageLinkText', { - defaultMessage: 'Machine Learning Job Management page' + defaultMessage: 'Machine Learning Job Management page', } )} - ) + ), }} />{' '} @@ -217,7 +217,7 @@ export function MachineLearningFlyoutView({ 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.manageMLJobDescription.noteText', { defaultMessage: - 'Note: It might take a few minutes for the job to begin calculating results.' + 'Note: It might take a few minutes for the job to begin calculating results.', } )} @@ -251,7 +251,7 @@ export function MachineLearningFlyoutView({ {i18n.translate( 'xpack.apm.serviceDetails.enableAnomalyDetectionPanel.createNewJobButtonLabel', { - defaultMessage: 'Create job' + defaultMessage: 'Create job', } )} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx index c0c93bb4cb298..8a3e2b1a02dac 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx @@ -22,7 +22,7 @@ import { EuiSpacer, EuiSwitch, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -84,15 +84,15 @@ export class WatcherFlyout extends Component< threshold: 10, actions: { slack: false, - email: false + email: false, }, interval: { value: 10, - unit: 'm' + unit: 'm', }, daily: '08:00', emails: '', - slackUrl: '' + slackUrl: '', }; public onChangeSchedule = (schedule: ScheduleKey) => { @@ -101,13 +101,13 @@ export class WatcherFlyout extends Component< public onChangeThreshold = (event: React.ChangeEvent) => { this.setState({ - threshold: parseInt(event.target.value, 10) + threshold: parseInt(event.target.value, 10), }); }; public onChangeDailyUnit = (event: React.ChangeEvent) => { this.setState({ - daily: event.target.value + daily: event.target.value, }); }; @@ -117,8 +117,8 @@ export class WatcherFlyout extends Component< this.setState({ interval: { value: parseInt(event.target.value, 10), - unit: this.state.interval.unit - } + unit: this.state.interval.unit, + }, }); }; @@ -128,8 +128,8 @@ export class WatcherFlyout extends Component< this.setState({ interval: { value: this.state.interval.value, - unit: event.target.value as IntervalUnit - } + unit: event.target.value as IntervalUnit, + }, }); }; @@ -137,8 +137,8 @@ export class WatcherFlyout extends Component< this.setState({ actions: { ...this.state.actions, - [actionName]: !this.state.actions[actionName] - } + [actionName]: !this.state.actions[actionName], + }, }); }; @@ -161,8 +161,8 @@ export class WatcherFlyout extends Component< const emails = this.state.actions.email ? this.state.emails .split(',') - .map(email => email.trim()) - .filter(email => !!email) + .map((email) => email.trim()) + .filter((email) => !!email) : []; const slackUrl = this.state.actions.slack ? this.state.slackUrl : ''; @@ -170,25 +170,25 @@ export class WatcherFlyout extends Component< const schedule = this.state.schedule === 'interval' ? { - interval: `${this.state.interval.value}${this.state.interval.unit}` + interval: `${this.state.interval.value}${this.state.interval.unit}`, } : { - daily: { at: `${this.state.daily}` } + daily: { at: `${this.state.daily}` }, }; const timeRange = this.state.schedule === 'interval' ? { value: this.state.interval.value, - unit: this.state.interval.unit + unit: this.state.interval.unit, } : { value: 24, - unit: 'h' + unit: 'h', }; return getApmIndexPatternTitle() - .then(indexPatternTitle => { + .then((indexPatternTitle) => { return createErrorGroupWatch({ http: core.http, emails, @@ -197,13 +197,13 @@ export class WatcherFlyout extends Component< slackUrl, threshold: this.state.threshold, timeRange, - apmIndexPatternTitle: indexPatternTitle + apmIndexPatternTitle: indexPatternTitle, }).then((id: string) => { this.props.onClose(); this.addSuccessToast(id); }); }) - .catch(e => { + .catch((e) => { // eslint-disable-next-line console.error(e); this.addErrorToast(); @@ -217,7 +217,7 @@ export class WatcherFlyout extends Component< title: i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreationFailedNotificationTitle', { - defaultMessage: 'Watch creation failed' + defaultMessage: 'Watch creation failed', } ), text: toMountPoint( @@ -226,11 +226,11 @@ export class WatcherFlyout extends Component< 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreationFailedNotificationText', { defaultMessage: - 'Make sure your user has permission to create watches.' + 'Make sure your user has permission to create watches.', } )}

      - ) + ), }); }; @@ -241,7 +241,7 @@ export class WatcherFlyout extends Component< title: i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreatedNotificationTitle', { - defaultMessage: 'New watch created!' + defaultMessage: 'New watch created!', } ), text: toMountPoint( @@ -252,8 +252,8 @@ export class WatcherFlyout extends Component< defaultMessage: 'The watch is now ready and will send error reports for {serviceName}.', values: { - serviceName: this.props.urlParams.serviceName - } + serviceName: this.props.urlParams.serviceName, + }, } )}{' '} @@ -263,13 +263,13 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreatedNotificationText.viewWatchLinkText', { - defaultMessage: 'View watch' + defaultMessage: 'View watch', } )}

      - ) + ), }); }; @@ -287,7 +287,7 @@ export class WatcherFlyout extends Component< ); // Format as 12h w. tz // Generate UTC hours for Daily Report select field - const intervalHours = range(24).map(i => { + const intervalHours = range(24).map((i) => { const hour = padLeft(i.toString(), 2, '0'); return { value: `${hour}:00`, text: `${hour}:00 UTC` }; }); @@ -309,11 +309,11 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.formDescription.documentationLinkText', { - defaultMessage: 'documentation' + defaultMessage: 'documentation', } )} - ) + ), }} />

      @@ -323,7 +323,7 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.conditionTitle', { - defaultMessage: 'Condition' + defaultMessage: 'Condition', } )} @@ -331,14 +331,14 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.occurrencesThresholdLabel', { - defaultMessage: 'Occurrences threshold per error group' + defaultMessage: 'Occurrences threshold per error group', } )} helpText={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.occurrencesThresholdHelpText', { defaultMessage: - 'Threshold to be met for error group to be included in report.' + 'Threshold to be met for error group to be included in report.', } )} compressed @@ -355,7 +355,7 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerScheduleTitle', { - defaultMessage: 'Trigger schedule' + defaultMessage: 'Trigger schedule', } )} @@ -364,7 +364,7 @@ export class WatcherFlyout extends Component< 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerScheduleDescription', { defaultMessage: - 'Choose the time interval for the report, when the threshold is exceeded.' + 'Choose the time interval for the report, when the threshold is exceeded.', } )} @@ -374,7 +374,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.dailyReportRadioButtonLabel', { - defaultMessage: 'Daily report' + defaultMessage: 'Daily report', } )} onChange={() => this.onChangeSchedule('daily')} @@ -387,7 +387,7 @@ export class WatcherFlyout extends Component< { defaultMessage: 'The daily report will be sent at {dailyTimeFormatted} / {dailyTime12HourFormatted}.', - values: { dailyTimeFormatted, dailyTime12HourFormatted } + values: { dailyTimeFormatted, dailyTime12HourFormatted }, } )} compressed @@ -405,7 +405,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.intervalRadioButtonLabel', { - defaultMessage: 'Interval' + defaultMessage: 'Interval', } )} onChange={() => this.onChangeSchedule('interval')} @@ -419,7 +419,7 @@ export class WatcherFlyout extends Component< helpText={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.intervalHelpText', { - defaultMessage: 'Time interval between reports.' + defaultMessage: 'Time interval between reports.', } )} compressed @@ -447,19 +447,19 @@ export class WatcherFlyout extends Component< text: i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.intervalUnit.minsLabel', { - defaultMessage: 'mins' + defaultMessage: 'mins', } - ) + ), }, { value: 'h', text: i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.intervalUnit.hrsLabel', { - defaultMessage: 'hrs' + defaultMessage: 'hrs', } - ) - } + ), + }, ]} disabled={this.state.schedule !== 'interval'} /> @@ -470,7 +470,7 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.actionsTitle', { - defaultMessage: 'Actions' + defaultMessage: 'Actions', } )} @@ -479,7 +479,7 @@ export class WatcherFlyout extends Component< 'xpack.apm.serviceDetails.enableErrorReportsPanel.actionsDescription', { defaultMessage: - 'Reports can be sent by email or posted to a Slack channel. Each report will include the top 10 errors sorted by occurrence.' + 'Reports can be sent by email or posted to a Slack channel. Each report will include the top 10 errors sorted by occurrence.', } )} @@ -488,7 +488,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.sendEmailLabel', { - defaultMessage: 'Send email' + defaultMessage: 'Send email', } )} checked={this.state.actions.email} @@ -500,7 +500,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.recipientsLabel', { - defaultMessage: 'Recipients (separated with comma)' + defaultMessage: 'Recipients (separated with comma)', } )} compressed @@ -519,11 +519,11 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.recipientsHelpText.documentationLinkText', { - defaultMessage: 'documentation' + defaultMessage: 'documentation', } )} - ) + ), }} /> @@ -542,7 +542,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.sendSlackNotificationLabel', { - defaultMessage: 'Send Slack notification' + defaultMessage: 'Send Slack notification', } )} checked={this.state.actions.slack} @@ -554,7 +554,7 @@ export class WatcherFlyout extends Component< label={i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.slackWebhookURLLabel', { - defaultMessage: 'Slack Webhook URL' + defaultMessage: 'Slack Webhook URL', } )} compressed @@ -572,11 +572,11 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.slackWebhookURLHelpText.documentationLinkText', { - defaultMessage: 'documentation' + defaultMessage: 'documentation', } )} - ) + ), }} /> @@ -602,7 +602,7 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.enableErrorReportsTitle', { - defaultMessage: 'Enable error reports' + defaultMessage: 'Enable error reports', } )} @@ -622,7 +622,7 @@ export class WatcherFlyout extends Component< {i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.createWatchButtonLabel', { - defaultMessage: 'Create watch' + defaultMessage: 'Create watch', } )} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts index f83daa4ea1a8a..f0bc313ab4644 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts @@ -13,10 +13,10 @@ import { esResponse } from './esResponse'; import { HttpSetup } from 'kibana/public'; // disable html escaping since this is also disabled in watcher\s mustache implementation -mustache.escape = value => value; +mustache.escape = (value) => value; jest.mock('../../../../../services/rest/callApi', () => ({ - callApi: () => Promise.resolve(null) + callApi: () => Promise.resolve(null), })); describe('createErrorGroupWatch', () => { @@ -34,20 +34,20 @@ describe('createErrorGroupWatch', () => { emails: ['my@email.dk', 'mySecond@email.dk'], schedule: { daily: { - at: '08:00' - } + at: '08:00', + }, }, serviceName: 'opbeans-node', slackUrl: 'https://hooks.slack.com/services/slackid1/slackid2/slackid3', threshold: 10, timeRange: { value: 24, unit: 'h' }, - apmIndexPatternTitle: 'myIndexPattern' + apmIndexPatternTitle: 'myIndexPattern', }); const watchBody = createWatchSpy.mock.calls[0][0].watch; const templateCtx = { payload: esResponse, - metadata: watchBody.metadata + metadata: watchBody.metadata, }; tmpl = renderMustache(createWatchSpy.mock.calls[0][0].watch, templateCtx); @@ -100,12 +100,12 @@ function renderMustache( if (isString(input)) { return mustache.render(input, { ctx, - join: () => (text: string, render: any) => render(`{{${text}}}`, { ctx }) + join: () => (text: string, render: any) => render(`{{${text}}}`, { ctx }), }); } if (isArray(input)) { - return input.map(itemValue => renderMustache(itemValue, ctx)); + return input.map((itemValue) => renderMustache(itemValue, ctx)); } if (isObject(input)) { diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts index 1a15be1f65dec..e17cb54b52b5c 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts @@ -11,12 +11,12 @@ export const esResponse = { total: 10, successful: 10, skipped: 0, - failed: 0 + failed: 0, }, hits: { total: 23287, max_score: 0, - hits: [] + hits: [], }, aggregations: { error_groups: { @@ -39,16 +39,16 @@ export const esResponse = { '@timestamp': '2018-04-25T17:03:02.296Z', error: { log: { - message: 'this is a string' + message: 'this is a string', }, - grouping_key: '63925d00b445cdf4b532dd09d185f5c6' - } + grouping_key: '63925d00b445cdf4b532dd09d185f5c6', + }, }, - sort: [1524675782296] - } - ] - } - } + sort: [1524675782296], + }, + ], + }, + }, }, { key: '89bb1a1f644c7f4bbe8d1781b5cb5fd5', @@ -68,18 +68,18 @@ export const esResponse = { exception: [ { handled: true, - message: 'foo' - } + message: 'foo', + }, ], culprit: ' (server/coffee.js)', - grouping_key: '89bb1a1f644c7f4bbe8d1781b5cb5fd5' - } + grouping_key: '89bb1a1f644c7f4bbe8d1781b5cb5fd5', + }, }, - sort: [1524675843504] - } - ] - } - } + sort: [1524675843504], + }, + ], + }, + }, }, { key: '7a17ea60604e3531bd8de58645b8631f', @@ -99,18 +99,18 @@ export const esResponse = { exception: [ { handled: false, - message: 'socket hang up' - } + message: 'socket hang up', + }, ], culprit: 'createHangUpError (_http_client.js)', - grouping_key: '7a17ea60604e3531bd8de58645b8631f' - } + grouping_key: '7a17ea60604e3531bd8de58645b8631f', + }, }, - sort: [1524675854575] - } - ] - } - } + sort: [1524675854575], + }, + ], + }, + }, }, { key: 'b9e1027f29c221763f864f6fa2ad9f5e', @@ -130,20 +130,20 @@ export const esResponse = { exception: [ { handled: false, - message: 'this will not get captured by express' - } + message: 'this will not get captured by express', + }, ], culprit: ' (server/coffee.js)', - grouping_key: 'b9e1027f29c221763f864f6fa2ad9f5e' - } + grouping_key: 'b9e1027f29c221763f864f6fa2ad9f5e', + }, }, - sort: [1524675854533] - } - ] - } - } - } - ] - } - } + sort: [1524675854533], + }, + ], + }, + }, + }, + ], + }, + }, }; diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts index d45453e24f1c9..151c4abb9fce3 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts @@ -16,7 +16,7 @@ import { ERROR_GROUP_ID, ERROR_LOG_MESSAGE, PROCESSOR_EVENT, - SERVICE_NAME + SERVICE_NAME, } from '../../../../../common/elasticsearch_fieldnames'; import { createWatch } from '../../../../services/rest/watcher'; @@ -62,7 +62,7 @@ export async function createErrorGroupWatch({ slackUrl, threshold, timeRange, - apmIndexPatternTitle + apmIndexPatternTitle, }: Arguments) { const id = `apm-${uuid.v4()}`; @@ -93,8 +93,8 @@ export async function createErrorGroupWatch({ docCountParam: '{{doc_count}}', slashErrorGroupsBucket: '{{/ctx.payload.aggregations.error_groups.buckets}}', - br: '
      ' - } + br: '
      ', + }, } ); @@ -121,13 +121,13 @@ export async function createErrorGroupWatch({ slashErrorCulprit: '{{/sample.hits.hits.0._source.error.culprit}}', docCountParam: '>{{doc_count}}', slashErrorGroupsBucket: - '{{/ctx.payload.aggregations.error_groups.buckets}}' - } + '{{/ctx.payload.aggregations.error_groups.buckets}}', + }, } ); const actions: Actions = { - log_error: { logging: { text: emailTemplate } } + log_error: { logging: { text: emailTemplate } }, }; const body = { @@ -136,17 +136,17 @@ export async function createErrorGroupWatch({ trigger: i18n.translate( 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerText', { - defaultMessage: 'This value must be changed in trigger section' + defaultMessage: 'This value must be changed in trigger section', } ), serviceName, threshold, timeRangeValue: timeRange.value, timeRangeUnit: timeRange.unit, - slackUrlPath + slackUrlPath, }, trigger: { - schedule + schedule, }, input: { search: { @@ -163,12 +163,12 @@ export async function createErrorGroupWatch({ range: { '@timestamp': { gte: - 'now-{{ctx.metadata.timeRangeValue}}{{ctx.metadata.timeRangeUnit}}' - } - } - } - ] - } + 'now-{{ctx.metadata.timeRangeValue}}{{ctx.metadata.timeRangeUnit}}', + }, + }, + }, + ], + }, }, aggs: { error_groups: { @@ -177,8 +177,8 @@ export async function createErrorGroupWatch({ field: ERROR_GROUP_ID, size: 10, order: { - _count: 'desc' - } + _count: 'desc', + }, }, aggs: { sample: { @@ -189,30 +189,30 @@ export async function createErrorGroupWatch({ ERROR_EXC_HANDLED, ERROR_CULPRIT, ERROR_GROUP_ID, - '@timestamp' + '@timestamp', ], sort: [ { - '@timestamp': 'desc' - } + '@timestamp': 'desc', + }, ], - size: 1 - } - } - } - } - } - } - } - } + size: 1, + }, + }, + }, + }, + }, + }, + }, + }, }, condition: { script: { source: - 'return ctx.payload.aggregations.error_groups.buckets.length > 0' - } + 'return ctx.payload.aggregations.error_groups.buckets.length > 0', + }, }, - actions + actions, }; if (slackUrlPath) { @@ -224,12 +224,12 @@ export async function createErrorGroupWatch({ method: 'POST', path: '{{ctx.metadata.slackUrlPath}}', headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }, body: `__json__::${JSON.stringify({ - text: slackTemplate - })}` - } + text: slackTemplate, + })}`, + }, }; } @@ -242,20 +242,20 @@ export async function createErrorGroupWatch({ { defaultMessage: '{serviceName} has error groups which exceeds the threshold', - values: { serviceName: '"{{ctx.metadata.serviceName}}"' } + values: { serviceName: '"{{ctx.metadata.serviceName}}"' }, } ), body: { - html: emailTemplate - } - } + html: emailTemplate, + }, + }, }; } await createWatch({ http, id, - watch: body + watch: body, }); return id; } diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx index e1f58b7b35210..bcc31a30b154d 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx @@ -8,7 +8,7 @@ import { EuiButtonEmpty, EuiContextMenu, EuiContextMenuPanelItemDescriptor, - EuiPopover + EuiPopover, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { memoize } from 'lodash'; @@ -48,21 +48,21 @@ export class ServiceIntegrations extends React.Component { name: i18n.translate( 'xpack.apm.serviceDetails.integrationsMenu.enableMLAnomalyDetectionButtonLabel', { - defaultMessage: 'Enable ML anomaly detection' + defaultMessage: 'Enable ML anomaly detection', } ), icon: 'machineLearningApp', toolTipContent: i18n.translate( 'xpack.apm.serviceDetails.integrationsMenu.enableMLAnomalyDetectionButtonTooltip', { - defaultMessage: 'Set up a machine learning job for this service' + defaultMessage: 'Set up a machine learning job for this service', } ), onClick: () => { this.closePopover(); this.openFlyout('ML'); - } - } + }, + }, ]; }; @@ -74,20 +74,20 @@ export class ServiceIntegrations extends React.Component { name: i18n.translate( 'xpack.apm.serviceDetails.integrationsMenu.enableWatcherErrorReportsButtonLabel', { - defaultMessage: 'Enable watcher error reports' + defaultMessage: 'Enable watcher error reports', } ), icon: 'watchesApp', onClick: () => { this.closePopover(); this.openFlyout('Watcher'); - } + }, }, { name: i18n.translate( 'xpack.apm.serviceDetails.integrationsMenu.viewWatchesButtonLabel', { - defaultMessage: 'View existing watches' + defaultMessage: 'View existing watches', } ), icon: 'watchesApp', @@ -95,19 +95,19 @@ export class ServiceIntegrations extends React.Component { '/app/kibana#/management/insightsAndAlerting/watcher' ), target: '_blank', - onClick: () => this.closePopover() - } + onClick: () => this.closePopover(), + }, ]; }; public openPopover = () => this.setState({ - isPopoverOpen: true + isPopoverOpen: true, }); public closePopover = () => this.setState({ - isPopoverOpen: false + isPopoverOpen: false, }); public openFlyout = (name: FlyoutName) => @@ -125,7 +125,7 @@ export class ServiceIntegrations extends React.Component { {i18n.translate( 'xpack.apm.serviceDetails.integrationsMenu.integrationsButtonLabel', { - defaultMessage: 'Integrations' + defaultMessage: 'Integrations', } )} @@ -133,7 +133,7 @@ export class ServiceIntegrations extends React.Component { return ( - {license => ( + {(license) => ( { id: 0, items: this.getPanelItems( license?.getFeature('ml').isAvailable - ) - } + ), + }, ]} /> diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/BetaBadge.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/BetaBadge.tsx index b40efce020a63..dfbdee647b50a 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/BetaBadge.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/BetaBadge.tsx @@ -22,13 +22,13 @@ export function BetaBadge() { diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Controls.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Controls.tsx index eabd967e6efe9..2199349952d8d 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Controls.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Controls.tsx @@ -50,8 +50,8 @@ function doZoom(cy: cytoscape.Core | undefined, increment: number) { duration, zoom: { level, - position: primaryCenter || graphCenter - } + position: primaryCenter || graphCenter, + }, }); } } @@ -64,7 +64,7 @@ export function Controls() { useEffect(() => { if (cy) { - cy.on('zoom', event => { + cy.on('zoom', (event) => { setZoom(event.cy.zoom()); }); } @@ -76,7 +76,7 @@ export function Controls() { cy.animate({ ...animationOptions, center: { eles }, - fit: { eles, padding: nodeHeight } + fit: { eles, padding: nodeHeight }, }); } } @@ -100,16 +100,16 @@ export function Controls() { const increment = (maxZoom - minZoom) / steps; const centerLabel = i18n.translate('xpack.apm.serviceMap.center', { - defaultMessage: 'Center' + defaultMessage: 'Center', }); const viewFullMapLabel = i18n.translate('xpack.apm.serviceMap.viewFullMap', { - defaultMessage: 'View full service map' + defaultMessage: 'View full service map', }); const zoomInLabel = i18n.translate('xpack.apm.serviceMap.zoomIn', { - defaultMessage: 'Zoom in' + defaultMessage: 'Zoom in', }); const zoomOutLabel = i18n.translate('xpack.apm.serviceMap.zoomOut', { - defaultMessage: 'Zoom out' + defaultMessage: 'Zoom out', }); const showViewFullMapButton = cy.nodes('.primary').length > 0; diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.stories.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.stories.tsx index 2d1e99096a44f..1c62d3cc03db0 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.stories.tsx @@ -22,31 +22,31 @@ storiesOf('app/ServiceMap/Cytoscape', module).add( data: { id: 'opbeans-python', 'service.name': 'opbeans-python', - 'agent.name': 'python' - } + 'agent.name': 'python', + }, }, { data: { id: 'opbeans-node', 'service.name': 'opbeans-node', - 'agent.name': 'nodejs' - } + 'agent.name': 'nodejs', + }, }, { data: { id: 'opbeans-ruby', 'service.name': 'opbeans-ruby', - 'agent.name': 'ruby' - } + 'agent.name': 'ruby', + }, }, { data: { source: 'opbeans-python', target: 'opbeans-node' } }, { data: { bidirectional: true, source: 'opbeans-python', - target: 'opbeans-ruby' - } - } + target: 'opbeans-ruby', + }, + }, ]; const height = 300; const width = 1340; @@ -63,8 +63,8 @@ storiesOf('app/ServiceMap/Cytoscape', module).add( { info: { propTables: false, - source: false - } + source: false, + }, } ); @@ -79,8 +79,8 @@ storiesOf('app/ServiceMap/Cytoscape', module) data: { id: 'aws', 'span.type': 'aws', - 'span.subtype': 'servicename' - } + 'span.subtype': 'servicename', + }, }, { data: { id: 'cache', 'span.type': 'cache' } }, { data: { id: 'database', 'span.type': 'db' } }, @@ -88,43 +88,43 @@ storiesOf('app/ServiceMap/Cytoscape', module) data: { id: 'cassandra', 'span.type': 'db', - 'span.subtype': 'cassandra' - } + 'span.subtype': 'cassandra', + }, }, { data: { id: 'elasticsearch', 'span.type': 'db', - 'span.subtype': 'elasticsearch' - } + 'span.subtype': 'elasticsearch', + }, }, { data: { id: 'mongodb', 'span.type': 'db', - 'span.subtype': 'mongodb' - } + 'span.subtype': 'mongodb', + }, }, { data: { id: 'mysql', 'span.type': 'db', - 'span.subtype': 'mysql' - } + 'span.subtype': 'mysql', + }, }, { data: { id: 'postgresql', 'span.type': 'db', - 'span.subtype': 'postgresql' - } + 'span.subtype': 'postgresql', + }, }, { data: { id: 'redis', 'span.type': 'db', - 'span.subtype': 'redis' - } + 'span.subtype': 'redis', + }, }, { data: { id: 'external', 'span.type': 'external' } }, { data: { id: 'ext', 'span.type': 'ext' } }, @@ -132,129 +132,129 @@ storiesOf('app/ServiceMap/Cytoscape', module) data: { id: 'graphql', 'span.type': 'external', - 'span.subtype': 'graphql' - } + 'span.subtype': 'graphql', + }, }, { data: { id: 'grpc', 'span.type': 'external', - 'span.subtype': 'grpc' - } + 'span.subtype': 'grpc', + }, }, { data: { id: 'websocket', 'span.type': 'external', - 'span.subtype': 'websocket' - } + 'span.subtype': 'websocket', + }, }, { data: { id: 'messaging', 'span.type': 'messaging' } }, { data: { id: 'jms', 'span.type': 'messaging', - 'span.subtype': 'jms' - } + 'span.subtype': 'jms', + }, }, { data: { id: 'kafka', 'span.type': 'messaging', - 'span.subtype': 'kafka' - } + 'span.subtype': 'kafka', + }, }, { data: { id: 'template', 'span.type': 'template' } }, { data: { id: 'handlebars', 'span.type': 'template', - 'span.subtype': 'handlebars' - } + 'span.subtype': 'handlebars', + }, }, { data: { id: 'dark', 'service.name': 'dark service', - 'agent.name': 'dark' - } + 'agent.name': 'dark', + }, }, { data: { id: 'dotnet', 'service.name': 'dotnet service', - 'agent.name': 'dotnet' - } + 'agent.name': 'dotnet', + }, }, { data: { id: 'dotNet', 'service.name': 'dotNet service', - 'agent.name': 'dotNet' - } + 'agent.name': 'dotNet', + }, }, { data: { id: 'go', 'service.name': 'go service', - 'agent.name': 'go' - } + 'agent.name': 'go', + }, }, { data: { id: 'java', 'service.name': 'java service', - 'agent.name': 'java' - } + 'agent.name': 'java', + }, }, { data: { id: 'RUM (js-base)', 'service.name': 'RUM service', - 'agent.name': 'js-base' - } + 'agent.name': 'js-base', + }, }, { data: { id: 'RUM (rum-js)', 'service.name': 'RUM service', - 'agent.name': 'rum-js' - } + 'agent.name': 'rum-js', + }, }, { data: { id: 'nodejs', 'service.name': 'nodejs service', - 'agent.name': 'nodejs' - } + 'agent.name': 'nodejs', + }, }, { data: { id: 'php', 'service.name': 'php service', - 'agent.name': 'php' - } + 'agent.name': 'php', + }, }, { data: { id: 'python', 'service.name': 'python service', - 'agent.name': 'python' - } + 'agent.name': 'python', + }, }, { data: { id: 'ruby', 'service.name': 'ruby service', - 'agent.name': 'ruby' - } - } + 'agent.name': 'ruby', + }, + }, ]; cy.add(elements); return ( - {cy.nodes().map(node => ( + {cy.nodes().map((node) => ( ; }, { - info: { propTables: false, source: false } + info: { propTables: false, source: false }, } ); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx index 441f4f6bf46b4..cb908785d64d8 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx @@ -11,13 +11,13 @@ import React, { ReactNode, useEffect, useRef, - useState + useState, } from 'react'; import { debounce } from 'lodash'; import { animationOptions, cytoscapeOptions, - nodeHeight + nodeHeight, } from './cytoscapeOptions'; import { useUiTracker } from '../../../../../observability/public'; @@ -66,7 +66,7 @@ function rotatePoint( const sinθ = Math.sin(θ); return { x: x * cosθ - y * sinθ, - y: x * sinθ + y * cosθ + y: x * sinθ + y * cosθ, }; } @@ -86,20 +86,20 @@ function getLayoutOptions( // The extra 5° achieves the effect of separating overlapping taxi-styled edges. transform: (node: any, pos: cytoscape.Position) => rotatePoint(pos, -95), // swap width/height of boundingBox to compensate for the rotation - boundingBox: { x1: 0, y1: 0, w: height, h: width } + boundingBox: { x1: 0, y1: 0, w: height, h: width }, }; } function selectRoots(cy: cytoscape.Core): string[] { const bfs = cy.elements().bfs({ - roots: cy.elements().leaves() + roots: cy.elements().leaves(), }); const furthestNodeFromLeaves = bfs.path.last(); return cy .elements() .roots() .union(furthestNodeFromLeaves) - .map(el => el.id()); + .map((el) => el.id()); } export function Cytoscape({ @@ -108,11 +108,11 @@ export function Cytoscape({ height, width, serviceName, - style + style, }: CytoscapeProps) { const [ref, cy] = useCytoscape({ ...cytoscapeOptions, - elements + elements, }); // Add the height to the div style. The height is a separate prop because it @@ -142,7 +142,7 @@ export function Cytoscape({ } }; - const dataHandler: cytoscape.EventHandler = event => { + const dataHandler: cytoscape.EventHandler = (event) => { if (cy && cy.elements().length > 0) { if (serviceName) { resetConnectedEdgeStyle(cy.getElementById(serviceName)); @@ -164,7 +164,7 @@ export function Cytoscape({ } }; let layoutstopDelayTimeout: NodeJS.Timeout; - const layoutstopHandler: cytoscape.EventHandler = event => { + const layoutstopHandler: cytoscape.EventHandler = (event) => { // This 0ms timer is necessary to prevent a race condition // between the layout finishing rendering and viewport centering layoutstopDelayTimeout = setTimeout(() => { @@ -173,11 +173,11 @@ export function Cytoscape({ ...animationOptions, fit: { eles: event.cy.elements(), - padding: nodeHeight + padding: nodeHeight, }, center: { - eles: event.cy.getElementById(serviceName) - } + eles: event.cy.getElementById(serviceName), + }, }); } else { event.cy.fit(undefined, nodeHeight); @@ -189,25 +189,25 @@ export function Cytoscape({ () => trackApmEvent({ metric: 'service_map_node_or_edge_hover' }), 1000 ); - const mouseoverHandler: cytoscape.EventHandler = event => { + const mouseoverHandler: cytoscape.EventHandler = (event) => { trackNodeEdgeHover(); event.target.addClass('hover'); event.target.connectedEdges().addClass('nodeHover'); }; - const mouseoutHandler: cytoscape.EventHandler = event => { + const mouseoutHandler: cytoscape.EventHandler = (event) => { event.target.removeClass('hover'); event.target.connectedEdges().removeClass('nodeHover'); }; - const selectHandler: cytoscape.EventHandler = event => { + const selectHandler: cytoscape.EventHandler = (event) => { trackApmEvent({ metric: 'service_map_node_select' }); resetConnectedEdgeStyle(event.target); }; - const unselectHandler: cytoscape.EventHandler = event => { + const unselectHandler: cytoscape.EventHandler = (event) => { resetConnectedEdgeStyle( serviceName ? event.cy.getElementById(serviceName) : undefined ); }; - const debugHandler: cytoscape.EventHandler = event => { + const debugHandler: cytoscape.EventHandler = (event) => { const debugEnabled = sessionStorage.getItem('apm_debug') === 'true'; if (debugEnabled) { // eslint-disable-next-line no-console diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx index f05ff0246b9e4..d497711cd0c24 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.test.tsx @@ -30,7 +30,7 @@ describe('EmptyBanner', () => { ); const component = render(, { - wrapper: noCytoscapeWrapper + wrapper: noCytoscapeWrapper, }); expect(component.container.children).toHaveLength(0); @@ -40,7 +40,7 @@ describe('EmptyBanner', () => { describe('with no nodes', () => { it('renders null', () => { const component = render(, { - wrapper + wrapper, }); expect(component.container.children).toHaveLength(0); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.tsx index 422b2052b0396..86582d57b3d7e 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/EmptyBanner.tsx @@ -28,7 +28,7 @@ export function EmptyBanner() { const [nodeCount, setNodeCount] = useState(0); useEffect(() => { - const handler: cytoscape.EventHandler = event => + const handler: cytoscape.EventHandler = (event) => setNodeCount(event.cy.nodes().length); if (cy) { @@ -58,19 +58,19 @@ export function EmptyBanner() { {i18n.translate('xpack.apm.serviceMap.emptyBanner.message', { defaultMessage: - "We will map out connected services and external requests if we can detect them. Please make sure you're running the latest version of the APM agent." + "We will map out connected services and external requests if we can detect them. Please make sure you're running the latest version of the APM agent.", })}{' '} {i18n.translate('xpack.apm.serviceMap.emptyBanner.docsLink', { - defaultMessage: 'Learn more in the docs' + defaultMessage: 'Learn more in the docs', })} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx index c08d3acbf1861..23fd568648bad 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/LoadingOverlay.tsx @@ -51,7 +51,7 @@ export const LoadingOverlay = ({ isLoading, percentageLoaded }: Props) => ( {i18n.translate('xpack.apm.loadingServiceMap', { defaultMessage: - 'Loading service map... This might take a short while.' + 'Loading service map... This might take a short while.', })} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx index 8041554756adc..d67447e04ef81 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Buttons.tsx @@ -20,7 +20,7 @@ interface ButtonsProps { export function Buttons({ onFocusClick = () => {}, - selectedNodeServiceName + selectedNodeServiceName, }: ButtonsProps) { const urlParams = useUrlParams().urlParams as APMQueryParams; const detailsUrl = getAPMHref( @@ -39,14 +39,14 @@ export function Buttons({ {i18n.translate('xpack.apm.serviceMap.serviceDetailsButtonText', { - defaultMessage: 'Service Details' + defaultMessage: 'Service Details', })} {i18n.translate('xpack.apm.serviceMap.focusMapButtonText', { - defaultMessage: 'Focus map' + defaultMessage: 'Focus map', })} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx index e58d9a0ff761a..d9254b487d037 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx @@ -10,7 +10,7 @@ import { EuiHorizontalRule, EuiTitle, EuiIconTip, - EuiHealth + EuiHealth, } from '@elastic/eui'; import theme from '@elastic/eui/dist/eui_theme_light.json'; import { i18n } from '@kbn/i18n'; @@ -94,7 +94,7 @@ const ANOMALY_DETECTION_TOOLTIP = i18n.translate( 'xpack.apm.serviceMap.anomalyDetectionPopoverTooltip', { defaultMessage: - 'Service health indicators are powered by the anomaly detection feature in machine learning' + 'Service health indicators are powered by the anomaly detection feature in machine learning', } ); @@ -112,7 +112,7 @@ const ANOMALY_DETECTION_DISABLED_TEXT = i18n.translate( 'xpack.apm.serviceMap.anomalyDetectionPopoverDisabled', { defaultMessage: - 'Display service health indicators by enabling anomaly detection from the Integrations menu in the Service details view.' + 'Display service health indicators by enabling anomaly detection from the Integrations menu in the Service details view.', } ); @@ -121,7 +121,7 @@ export function Contents({ isService, label, onFocusClick, - selectedNodeServiceName + selectedNodeServiceName, }: ContentsProps) { // Anomaly Detection const severity = selectedNodeData.severity; @@ -134,8 +134,8 @@ export function Contents({ maxScore, actualValue, typicalValue, - jobId - ].every(value => value !== undefined); + jobId, + ].every((value) => value !== undefined); const anomalyDescription = hasAnomalyDetection ? getMetricChangeDescription(actualValue, typicalValue).message : null; diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx index 541f4f6a1e775..992e6ffdc46ba 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx @@ -11,7 +11,7 @@ import React from 'react'; import styled from 'styled-components'; import { SPAN_SUBTYPE, - SPAN_TYPE + SPAN_TYPE, } from '../../../../../common/elasticsearch_fieldnames'; const ItemRow = styled.div` @@ -40,16 +40,16 @@ export function Info(data: InfoProps) { const listItems = [ { title: i18n.translate('xpack.apm.serviceMap.typePopoverMetric', { - defaultMessage: 'Type' + defaultMessage: 'Type', }), - description: type + description: type, }, { title: i18n.translate('xpack.apm.serviceMap.subtypePopoverMetric', { - defaultMessage: 'Subtype' + defaultMessage: 'Subtype', }), - description: subtype - } + description: subtype, + }, ]; return ( diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx index 6f67f7a4bed7a..718e43984d7f3 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx @@ -15,24 +15,24 @@ interface ServiceMetricFetcherProps { } export function ServiceMetricFetcher({ - serviceName + serviceName, }: ServiceMetricFetcherProps) { const { - urlParams: { start, end, environment } + urlParams: { start, end, environment }, } = useUrlParams(); const { data = {} as ServiceNodeMetrics, status } = useFetcher( - callApmApi => { + (callApmApi) => { if (serviceName && start && end) { return callApmApi({ pathname: '/api/apm/service-map/service/{serviceName}', - params: { path: { serviceName }, query: { start, end, environment } } + params: { path: { serviceName }, query: { start, end, environment } }, }); } }, [serviceName, start, end, environment], { - preservePreviousData: false + preservePreviousData: false, } ); const isLoading = status === 'loading'; diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx index 39d54dc5801d2..4e6f077a80ae7 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx @@ -48,57 +48,57 @@ export function ServiceMetricList({ avgErrorsPerMinute, avgCpuUsage, avgMemoryUsage, - isLoading + isLoading, }: ServiceMetricListProps) { const listItems = [ { title: i18n.translate( 'xpack.apm.serviceMap.avgTransDurationPopoverMetric', { - defaultMessage: 'Trans. duration (avg.)' + defaultMessage: 'Trans. duration (avg.)', } ), description: isNumber(avgTransactionDuration) ? asDuration(avgTransactionDuration) - : null + : null, }, { title: i18n.translate( 'xpack.apm.serviceMap.avgReqPerMinutePopoverMetric', { - defaultMessage: 'Req. per minute (avg.)' + defaultMessage: 'Req. per minute (avg.)', } ), description: isNumber(avgRequestsPerMinute) ? `${avgRequestsPerMinute.toFixed(2)} ${tpmUnit('request')}` - : null + : null, }, { title: i18n.translate( 'xpack.apm.serviceMap.avgErrorsPerMinutePopoverMetric', { - defaultMessage: 'Errors per minute (avg.)' + defaultMessage: 'Errors per minute (avg.)', } ), - description: avgErrorsPerMinute?.toFixed(2) + description: avgErrorsPerMinute?.toFixed(2), }, { title: i18n.translate('xpack.apm.serviceMap.avgCpuUsagePopoverMetric', { - defaultMessage: 'CPU usage (avg.)' + defaultMessage: 'CPU usage (avg.)', }), - description: isNumber(avgCpuUsage) ? asPercent(avgCpuUsage, 1) : null + description: isNumber(avgCpuUsage) ? asPercent(avgCpuUsage, 1) : null, }, { title: i18n.translate( 'xpack.apm.serviceMap.avgMemoryUsagePopoverMetric', { - defaultMessage: 'Memory usage (avg.)' + defaultMessage: 'Memory usage (avg.)', } ), description: isNumber(avgMemoryUsage) ? asPercent(avgMemoryUsage, 1) - : null - } + : null, + }, ]; return isLoading ? ( diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/index.tsx index 86ef0b880c4da..96e8ef78967b5 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/index.tsx @@ -13,7 +13,7 @@ import React, { useContext, useEffect, useRef, - useState + useState, } from 'react'; import { SERVICE_NAME } from '../../../../../common/elasticsearch_fieldnames'; import { CytoscapeContext } from '../Cytoscape'; @@ -44,7 +44,7 @@ export function Popover({ focusedServiceName }: PopoverProps) { background: 'transparent', height: renderedHeight, position: 'absolute', - width: renderedWidth + width: renderedWidth, }; const trigger =
      ; const zoom = cy?.zoom() ?? 1; @@ -52,7 +52,7 @@ export function Popover({ focusedServiceName }: PopoverProps) { const translateY = y - ((zoom + 1) * height) / 4; const popoverStyle: CSSProperties = { position: 'absolute', - transform: `translate(${x}px, ${translateY}px)` + transform: `translate(${x}px, ${translateY}px)`, }; const selectedNodeData = selectedNode?.data() ?? {}; const selectedNodeServiceName = selectedNodeData.id; @@ -61,7 +61,7 @@ export function Popover({ focusedServiceName }: PopoverProps) { // Set up Cytoscape event handlers useEffect(() => { - const selectHandler: cytoscape.EventHandler = event => { + const selectHandler: cytoscape.EventHandler = (event) => { setSelectedNode(event.target); }; @@ -94,7 +94,7 @@ export function Popover({ focusedServiceName }: PopoverProps) { if (cy) { cy.animate({ ...animationOptions, - center: { eles: cy.getElementById(selectedNodeServiceName) } + center: { eles: cy.getElementById(selectedNodeServiceName) }, }); } }, @@ -116,7 +116,7 @@ export function Popover({ focusedServiceName }: PopoverProps) { isService={isService} label={label} onFocusClick={ - isAlreadyFocused ? centerSelectedNode : _event => deselect() + isAlreadyFocused ? centerSelectedNode : (_event) => deselect() } selectedNodeData={selectedNodeData} selectedNodeServiceName={selectedNodeServiceName} diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/cytoscapeOptions.ts b/x-pack/plugins/apm/public/components/app/ServiceMap/cytoscapeOptions.ts index 67cd688b6d188..0e4666b7bff17 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/cytoscapeOptions.ts +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/cytoscapeOptions.ts @@ -8,7 +8,7 @@ import cytoscape from 'cytoscape'; import { CSSProperties } from 'react'; import { SERVICE_NAME, - SPAN_DESTINATION_SERVICE_RESOURCE + SPAN_DESTINATION_SERVICE_RESOURCE, } from '../../../../common/elasticsearch_fieldnames'; import { severity } from '../../../../common/ml_job_constants'; import { defaultIcon, iconForNode } from './icons'; @@ -78,7 +78,7 @@ const isIE11 = !!window.MSInputMethodContext && !!document.documentMode; export const animationOptions: cytoscape.AnimationOptions = { duration: parseInt(theme.euiAnimSpeedNormal, 10), // @ts-ignore The cubic-bezier options here are not recognized by the cytoscape types - easing: theme.euiAnimSlightBounce + easing: theme.euiAnimSlightBounce, }; const lineColor = '#C5CCD7'; const zIndexNode = 200; @@ -141,8 +141,8 @@ const style: cytoscape.Stylesheet[] = [ 'text-valign': 'bottom', 'text-wrap': 'ellipsis', width: theme.avatarSizing.l.size, - 'z-index': zIndexNode - } + 'z-index': zIndexNode, + }, }, { selector: 'edge', @@ -161,8 +161,8 @@ const style: cytoscape.Stylesheet[] = [ 'target-distance-from-node': isIE11 ? undefined : theme.paddingSizes.xs, width: 1, 'source-arrow-shape': 'none', - 'z-index': zIndexEdge - } + 'z-index': zIndexEdge, + }, }, { selector: 'edge[bidirectional]', @@ -176,14 +176,14 @@ const style: cytoscape.Stylesheet[] = [ : parseInt(theme.paddingSizes.xs, 10), 'target-distance-from-node': isIE11 ? undefined - : parseInt(theme.paddingSizes.xs, 10) - } + : parseInt(theme.paddingSizes.xs, 10), + }, }, // @ts-ignore DefinitelyTyped says visibility is "none" but it's // actually "hidden" { selector: 'edge[isInverseEdge]', - style: { visibility: 'hidden' } + style: { visibility: 'hidden' }, }, { selector: 'edge.nodeHover', @@ -193,14 +193,14 @@ const style: cytoscape.Stylesheet[] = [ 'z-index': zIndexEdgeHover, 'line-color': theme.euiColorDarkShade, 'source-arrow-color': theme.euiColorDarkShade, - 'target-arrow-color': theme.euiColorDarkShade - } + 'target-arrow-color': theme.euiColorDarkShade, + }, }, { selector: 'node.hover', style: { - 'border-width': getBorderWidth - } + 'border-width': getBorderWidth, + }, }, { selector: 'edge.highlight', @@ -210,9 +210,9 @@ const style: cytoscape.Stylesheet[] = [ 'source-arrow-color': theme.euiColorPrimary, 'target-arrow-color': theme.euiColorPrimary, // @ts-ignore - 'z-index': zIndexEdgeHighlight - } - } + 'z-index': zIndexEdgeHighlight, + }, + }, ]; // The CSS styles for the div containing the cytoscape element. Makes a @@ -234,7 +234,7 @@ center, ${theme.euiColorLightShade}`, backgroundSize: `${theme.euiSizeL} ${theme.euiSizeL}`, margin: `-${theme.gutterTypes.gutterLarge}`, - marginTop: 0 + marginTop: 0, }; export const cytoscapeOptions: cytoscape.CytoscapeOptions = { @@ -242,5 +242,5 @@ export const cytoscapeOptions: cytoscape.CytoscapeOptions = { boxSelectionEnabled: false, maxZoom: 3, minZoom: 0.2, - style + style, }; diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/icons.ts b/x-pack/plugins/apm/public/components/app/ServiceMap/icons.ts index 1b4bf1b77791c..c211ef3abab1d 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/icons.ts +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/icons.ts @@ -9,7 +9,7 @@ import { getNormalizedAgentName } from '../../../../common/agent_name'; import { AGENT_NAME, SPAN_SUBTYPE, - SPAN_TYPE + SPAN_TYPE, } from '../../../../common/elasticsearch_fieldnames'; import awsIcon from './icons/aws.svg'; import cassandraIcon from './icons/cassandra.svg'; @@ -45,12 +45,12 @@ const defaultTypeIcons: { [key: string]: string } = { ext: globeIcon, external: globeIcon, messaging: documentsIcon, - resource: globeIcon + resource: globeIcon, }; const typeIcons: { [key: string]: { [key: string]: string } } = { aws: { - servicename: awsIcon + servicename: awsIcon, }, db: { cassandra: cassandraIcon, @@ -58,20 +58,20 @@ const typeIcons: { [key: string]: { [key: string]: string } } = { mongodb: mongodbIcon, mysql: mysqlIcon, postgresql: postgresqlIcon, - redis: redisIcon + redis: redisIcon, }, external: { graphql: graphqlIcon, grpc: grpcIcon, - websocket: websocketIcon + websocket: websocketIcon, }, messaging: { jms: javaIcon, - kafka: kafkaIcon + kafka: kafkaIcon, }, template: { - handlebars: handlebarsIcon - } + handlebars: handlebarsIcon, + }, }; const agentIcons: { [key: string]: string } = { @@ -83,7 +83,7 @@ const agentIcons: { [key: string]: string } = { nodejs: nodeJsIcon, php: phpIcon, python: pythonIcon, - ruby: rubyIcon + ruby: rubyIcon, }; function getAgentIcon(agentName?: string) { diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx index c7e25269511bf..f36b94f2971cd 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/index.test.tsx @@ -18,8 +18,8 @@ const expiredLicense = new License({ mode: 'platinum', status: 'expired', type: 'platinum', - uid: '1' - } + uid: '1', + }, }); const Wrapper: FunctionComponent = ({ children }) => { @@ -36,7 +36,7 @@ describe('ServiceMap', () => { expect( ( await render(, { - wrapper: Wrapper + wrapper: Wrapper, }).findAllByText(/Platinum/) ).length ).toBeGreaterThan(0); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx index b57f0b047c613..2decf7325a8f3 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/index.tsx @@ -9,7 +9,7 @@ import theme from '@elastic/eui/dist/eui_theme_light.json'; import React from 'react'; import { invalidLicenseMessage, - isValidPlatinumLicense + isValidPlatinumLicense, } from '../../../../common/service_map'; import { useFetcher } from '../../../hooks/useFetcher'; import { useLicense } from '../../../hooks/useLicense'; @@ -49,9 +49,9 @@ export function ServiceMap({ serviceName }: ServiceMapProps) { start, end, environment, - serviceName - } - } + serviceName, + }, + }, }); } }, [license, serviceName, urlParams]); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMetrics/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceMetrics/index.tsx index 0fb8c00a2b162..9af6a8d988c11 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMetrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMetrics/index.tsx @@ -9,7 +9,7 @@ import { EuiFlexItem, EuiPanel, EuiSpacer, - EuiFlexGroup + EuiFlexGroup, } from '@elastic/eui'; import React, { useMemo } from 'react'; import { useServiceMetricCharts } from '../../../hooks/useServiceMetricCharts'; @@ -34,10 +34,10 @@ export function ServiceMetrics({ agentName }: ServiceMetricsProps) { filterNames: ['host', 'containerId', 'podName', 'serviceVersion'], params: { serviceName, - serviceNodeName + serviceNodeName, }, projection: PROJECTION.METRICS, - showCount: false + showCount: false, }), [serviceName, serviceNodeName] ); @@ -52,7 +52,7 @@ export function ServiceMetrics({ agentName }: ServiceMetricsProps) { - {data.charts.map(chart => ( + {data.charts.map((chart) => ( diff --git a/x-pack/plugins/apm/public/components/app/ServiceNodeMetrics/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceNodeMetrics/index.tsx index 3929c153ae419..e81968fb298fa 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceNodeMetrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceNodeMetrics/index.tsx @@ -14,7 +14,7 @@ import { EuiSpacer, EuiStat, EuiToolTip, - EuiCallOut + EuiCallOut, } from '@elastic/eui'; import React from 'react'; import { i18n } from '@kbn/i18n'; @@ -33,7 +33,7 @@ import { ElasticDocsLink } from '../../shared/Links/ElasticDocsLink'; const INITIAL_DATA = { host: '', - containerId: '' + containerId: '', }; const Truncate = styled.span` @@ -50,7 +50,7 @@ export function ServiceNodeMetrics() { const { start, end } = urlParams; const { data: { host, containerId } = INITIAL_DATA, status } = useFetcher( - callApmApi => { + (callApmApi) => { if (serviceName && serviceNodeName && start && end) { return callApmApi({ pathname: @@ -60,9 +60,9 @@ export function ServiceNodeMetrics() { query: { start, end, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -90,7 +90,7 @@ export function ServiceNodeMetrics() { title={i18n.translate( 'xpack.apm.serviceNodeMetrics.unidentifiedServiceNodesWarningTitle', { - defaultMessage: 'Could not identify JVMs' + defaultMessage: 'Could not identify JVMs', } )} iconType="help" @@ -111,7 +111,7 @@ export function ServiceNodeMetrics() { { defaultMessage: 'documentation of APM Server' } )} - ) + ), }} /> @@ -123,7 +123,7 @@ export function ServiceNodeMetrics() { description={i18n.translate( 'xpack.apm.serviceNodeMetrics.serviceName', { - defaultMessage: 'Service name' + defaultMessage: 'Service name', } )} title={ @@ -138,7 +138,7 @@ export function ServiceNodeMetrics() { titleSize="s" isLoading={isLoading} description={i18n.translate('xpack.apm.serviceNodeMetrics.host', { - defaultMessage: 'Host' + defaultMessage: 'Host', })} title={ @@ -154,7 +154,7 @@ export function ServiceNodeMetrics() { description={i18n.translate( 'xpack.apm.serviceNodeMetrics.containerId', { - defaultMessage: 'Container ID' + defaultMessage: 'Container ID', } )} title={ @@ -170,7 +170,7 @@ export function ServiceNodeMetrics() { {agentName && serviceNodeName && ( - {data.charts.map(chart => ( + {data.charts.map((chart) => ( diff --git a/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx index 4e57cb47691be..62ea3bc42860a 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceNodeOverview/index.tsx @@ -9,7 +9,7 @@ import { EuiFlexItem, EuiPanel, EuiToolTip, - EuiSpacer + EuiSpacer, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import styled from 'styled-components'; @@ -23,7 +23,7 @@ import { useFetcher } from '../../../hooks/useFetcher'; import { asDynamicBytes, asInteger, - asPercent + asPercent, } from '../../../utils/formatters'; import { ServiceNodeMetricOverviewLink } from '../../shared/Links/apm/ServiceNodeMetricOverviewLink'; import { truncate, px, unit } from '../../../style/variables'; @@ -44,15 +44,15 @@ const ServiceNodeOverview = () => { () => ({ filterNames: ['host', 'containerId', 'podName'], params: { - serviceName + serviceName, }, - projection: PROJECTION.SERVICE_NODES + projection: PROJECTION.SERVICE_NODES, }), [serviceName] ); const { data: items = [] } = useFetcher( - callApmApi => { + (callApmApi) => { if (!serviceName || !start || !end) { return undefined; } @@ -60,14 +60,14 @@ const ServiceNodeOverview = () => { pathname: '/api/apm/services/{serviceName}/serviceNodes', params: { path: { - serviceName + serviceName, }, query: { start, end, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); }, [serviceName, start, end, uiFilters] @@ -82,12 +82,12 @@ const ServiceNodeOverview = () => { name: ( <> {i18n.translate('xpack.apm.jvmsTable.nameColumnLabel', { - defaultMessage: 'Name' + defaultMessage: 'Name', })} @@ -103,9 +103,9 @@ const ServiceNodeOverview = () => { 'xpack.apm.jvmsTable.explainServiceNodeNameMissing', { defaultMessage: - 'We could not identify which JVMs these metrics belong to. This is likely caused by running a version of APM Server that is older than 7.5. Upgrading to APM Server 7.5 or higher should resolve this issue.' + 'We could not identify which JVMs these metrics belong to. This is likely caused by running a version of APM Server that is older than 7.5. Upgrading to APM Server 7.5 or higher should resolve this issue.', } - ) + ), } : { displayedName: name, tooltip: name }; @@ -119,40 +119,40 @@ const ServiceNodeOverview = () => { ); - } + }, }, { name: i18n.translate('xpack.apm.jvmsTable.cpuColumnLabel', { - defaultMessage: 'CPU avg' + defaultMessage: 'CPU avg', }), field: 'cpu', sortable: true, - render: (value: number | null) => asPercent(value || 0, 1) + render: (value: number | null) => asPercent(value || 0, 1), }, { name: i18n.translate('xpack.apm.jvmsTable.heapMemoryColumnLabel', { - defaultMessage: 'Heap memory avg' + defaultMessage: 'Heap memory avg', }), field: 'heapMemory', sortable: true, - render: asDynamicBytes + render: asDynamicBytes, }, { name: i18n.translate('xpack.apm.jvmsTable.nonHeapMemoryColumnLabel', { - defaultMessage: 'Non-heap memory avg' + defaultMessage: 'Non-heap memory avg', }), field: 'nonHeapMemory', sortable: true, - render: asDynamicBytes + render: asDynamicBytes, }, { name: i18n.translate('xpack.apm.jvmsTable.threadCountColumnLabel', { - defaultMessage: 'Thread count max' + defaultMessage: 'Thread count max', }), field: 'threadCount', sortable: true, - render: asInteger - } + render: asInteger, + }, ]; return ( @@ -168,7 +168,7 @@ const ServiceNodeOverview = () => { noItemsMessage={i18n.translate( 'xpack.apm.jvmsTable.noJvmsLabel', { - defaultMessage: 'No JVMs were found' + defaultMessage: 'No JVMs were found', } )} items={items} diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/NoServicesMessage.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/NoServicesMessage.tsx index 266e5a97ef07a..d2763c6632c65 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceOverview/NoServicesMessage.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/NoServicesMessage.tsx @@ -34,7 +34,7 @@ export function NoServicesMessage({ historicalDataFound, status }: Props) { title={
      {i18n.translate('xpack.apm.servicesTable.notFoundLabel', { - defaultMessage: 'No services found' + defaultMessage: 'No services found', })}
      } @@ -48,7 +48,7 @@ export function NoServicesMessage({ historicalDataFound, status }: Props) { title={
      {i18n.translate('xpack.apm.servicesTable.noServicesLabel', { - defaultMessage: `Looks like you don't have any APM services installed. Let's add some!` + defaultMessage: `Looks like you don't have any APM services installed. Let's add some!`, })}
      } @@ -58,18 +58,18 @@ export function NoServicesMessage({ historicalDataFound, status }: Props) {

      {i18n.translate('xpack.apm.servicesTable.7xUpgradeServerMessage', { defaultMessage: `Upgrading from a pre-7.x version? Make sure you've also upgraded - your APM Server instance(s) to at least 7.0.` + your APM Server instance(s) to at least 7.0.`, })}

      {i18n.translate('xpack.apm.servicesTable.7xOldDataMessage', { defaultMessage: - 'You may also have old data that needs to be migrated.' + 'You may also have old data that needs to be migrated.', })}{' '} {i18n.translate('xpack.apm.servicesTable.UpgradeAssistantLink', { defaultMessage: - 'Learn more by visiting the Kibana Upgrade Assistant' + 'Learn more by visiting the Kibana Upgrade Assistant', })} . diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js index 003c9d14406a9..927779b571fd8 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js +++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/__test__/List.test.js @@ -32,9 +32,9 @@ describe('ServiceOverview -> List', () => { transactionsPerMinute: 86.93333333333334, errorsPerMinute: 12.6, avgResponseTime: 91535.42944785276, - environments: ['test'] + environments: ['test'], }; - const renderedColumns = SERVICE_COLUMNS.map(c => + const renderedColumns = SERVICE_COLUMNS.map((c) => c.render(service[c.field], service) ); expect(renderedColumns[0]).toMatchSnapshot(); @@ -42,7 +42,7 @@ describe('ServiceOverview -> List', () => { 'python', '92 ms', '86.9 tpm', - '12.6 err.' + '12.6 err.', ]); }); }); diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx index 7e2d03ad35899..b9048f013cb25 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/ServiceList/index.tsx @@ -45,7 +45,7 @@ export const SERVICE_COLUMNS = [ { field: 'serviceName', name: i18n.translate('xpack.apm.servicesTable.nameColumnLabel', { - defaultMessage: 'Name' + defaultMessage: 'Name', }), width: '40%', sortable: true, @@ -53,46 +53,46 @@ export const SERVICE_COLUMNS = [ {formatString(serviceName)} - ) + ), }, { field: 'environments', name: i18n.translate('xpack.apm.servicesTable.environmentColumnLabel', { - defaultMessage: 'Environment' + defaultMessage: 'Environment', }), width: '20%', sortable: true, render: (environments: string[]) => ( - ) + ), }, { field: 'agentName', name: i18n.translate('xpack.apm.servicesTable.agentColumnLabel', { - defaultMessage: 'Agent' + defaultMessage: 'Agent', }), sortable: true, - render: (agentName: string) => formatString(agentName) + render: (agentName: string) => formatString(agentName), }, { field: 'avgResponseTime', name: i18n.translate('xpack.apm.servicesTable.avgResponseTimeColumnLabel', { - defaultMessage: 'Avg. response time' + defaultMessage: 'Avg. response time', }), sortable: true, dataType: 'number', render: (time: number) => convertTo({ unit: 'milliseconds', - microseconds: time - }).formatted + microseconds: time, + }).formatted, }, { field: 'transactionsPerMinute', name: i18n.translate( 'xpack.apm.servicesTable.transactionsPerMinuteColumnLabel', { - defaultMessage: 'Trans. per minute' + defaultMessage: 'Trans. per minute', } ), sortable: true, @@ -101,14 +101,14 @@ export const SERVICE_COLUMNS = [ `${formatNumber(value)} ${i18n.translate( 'xpack.apm.servicesTable.transactionsPerMinuteUnitLabel', { - defaultMessage: 'tpm' + defaultMessage: 'tpm', } - )}` + )}`, }, { field: 'errorsPerMinute', name: i18n.translate('xpack.apm.servicesTable.errorsPerMinuteColumnLabel', { - defaultMessage: 'Errors per minute' + defaultMessage: 'Errors per minute', }), sortable: true, dataType: 'number', @@ -116,10 +116,10 @@ export const SERVICE_COLUMNS = [ `${formatNumber(value)} ${i18n.translate( 'xpack.apm.servicesTable.errorsPerMinuteUnitLabel', { - defaultMessage: 'err.' + defaultMessage: 'err.', } - )}` - } + )}`, + }, ]; export function ServiceList({ items, noItemsMessage }: Props) { diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/__test__/NoServicesMessage.test.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/__test__/NoServicesMessage.test.tsx index fdf373bf97f94..21681f42d4b52 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceOverview/__test__/NoServicesMessage.test.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/__test__/NoServicesMessage.test.tsx @@ -10,8 +10,8 @@ import { NoServicesMessage } from '../NoServicesMessage'; import { FETCH_STATUS } from '../../../../hooks/useFetcher'; describe('NoServicesMessage', () => { - Object.values(FETCH_STATUS).forEach(status => { - [true, false].forEach(historicalDataFound => { + Object.values(FETCH_STATUS).forEach((status) => { + [true, false].forEach((historicalDataFound) => { it(`status: ${status} and historicalDataFound: ${historicalDataFound}`, () => { const wrapper = shallow( @@ -62,15 +62,15 @@ describe('Service Overview -> View', () => { spyOn(urlParamsHooks, 'useUrlParams').and.returnValue({ urlParams: { start: 'myStart', - end: 'myEnd' - } + end: 'myEnd', + }, }); jest.spyOn(useLocalUIFilters, 'useLocalUIFilters').mockReturnValue({ filters: [], setFilterValue: () => null, clearValues: () => null, - status: FETCH_STATUS.SUCCESS + status: FETCH_STATUS.SUCCESS, }); }); @@ -90,7 +90,7 @@ describe('Service Overview -> View', () => { transactionsPerMinute: 100, errorsPerMinute: 200, avgResponseTime: 300, - environments: ['test', 'dev'] + environments: ['test', 'dev'], }, { serviceName: 'My Go Service', @@ -98,9 +98,9 @@ describe('Service Overview -> View', () => { transactionsPerMinute: 400, errorsPerMinute: 500, avgResponseTime: 600, - environments: [] - } - ] + environments: [], + }, + ], }); const { container, getByText } = renderServiceOverview(); @@ -116,7 +116,7 @@ describe('Service Overview -> View', () => { httpGet.mockResolvedValueOnce({ hasLegacyData: false, hasHistoricalData: false, - items: [] + items: [], }); const { container, getByText } = renderServiceOverview(); @@ -138,7 +138,7 @@ describe('Service Overview -> View', () => { httpGet.mockResolvedValueOnce({ hasLegacyData: false, hasHistoricalData: true, - items: [] + items: [], }); const { container, getByText } = renderServiceOverview(); @@ -155,7 +155,7 @@ describe('Service Overview -> View', () => { httpGet.mockResolvedValueOnce({ hasLegacyData: true, hasHistoricalData: true, - items: [] + items: [], }); renderServiceOverview(); @@ -165,7 +165,7 @@ describe('Service Overview -> View', () => { expect(addWarning).toHaveBeenLastCalledWith( expect.objectContaining({ - title: 'Legacy data was detected within the selected time range' + title: 'Legacy data was detected within the selected time range', }) ); }); @@ -176,7 +176,7 @@ describe('Service Overview -> View', () => { httpGet.mockResolvedValueOnce({ hasLegacyData: false, hasHistoricalData: true, - items: [] + items: [], }); renderServiceOverview(); diff --git a/x-pack/plugins/apm/public/components/app/ServiceOverview/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceOverview/index.tsx index 06f56d9ec1be7..7d05ae90afb87 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceOverview/index.tsx @@ -22,7 +22,7 @@ import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; const initalData = { items: [], hasHistoricalData: true, - hasLegacyData: false + hasLegacyData: false, }; let hasDisplayedToast = false; @@ -31,16 +31,16 @@ export function ServiceOverview() { const { core } = useApmPluginContext(); const { urlParams: { start, end }, - uiFilters + uiFilters, } = useUrlParams(); const { data = initalData, status } = useFetcher( - callApmApi => { + (callApmApi) => { if (start && end) { return callApmApi({ pathname: '/api/apm/services', params: { - query: { start, end, uiFilters: JSON.stringify(uiFilters) } - } + query: { start, end, uiFilters: JSON.stringify(uiFilters) }, + }, }); } }, @@ -54,30 +54,30 @@ export function ServiceOverview() { core.notifications.toasts.addWarning({ title: i18n.translate('xpack.apm.serviceOverview.toastTitle', { defaultMessage: - 'Legacy data was detected within the selected time range' + 'Legacy data was detected within the selected time range', }), text: toMountPoint(

      {i18n.translate('xpack.apm.serviceOverview.toastText', { defaultMessage: - "You're running Elastic Stack 7.0+ and we've detected incompatible data from a previous 6.x version. If you want to view this data in APM, you should migrate it. See more in " + "You're running Elastic Stack 7.0+ and we've detected incompatible data from a previous 6.x version. If you want to view this data in APM, you should migrate it. See more in ", })} {i18n.translate( 'xpack.apm.serviceOverview.upgradeAssistantLink', { - defaultMessage: 'the upgrade assistant' + defaultMessage: 'the upgrade assistant', } )}

      - ) + ), }); } }, [data.hasLegacyData, core.http.basePath, core.notifications.toasts]); @@ -88,7 +88,7 @@ export function ServiceOverview() { const localFiltersConfig: React.ComponentProps = useMemo( () => ({ filterNames: ['host', 'agentName'], - projection: PROJECTION.SERVICES + projection: PROJECTION.SERVICES, }), [] ); diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx index 30d3f9580db48..5a17e5dc45019 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/ServicePage/FormRowSelect.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { EuiDescribedFormGroup, EuiSelectOption, - EuiFormRow + EuiFormRow, } from '@elastic/eui'; import { SelectWithPlaceholder } from '../../../../../shared/SelectWithPlaceholder'; @@ -31,7 +31,7 @@ export function FormRowSelect({ options, value, disabled, - onChange + onChange, }: Props) { return ( { + (callApmApi) => { return callApmApi({ pathname: '/api/apm/settings/agent-configuration/services', - isCachable: true + isCachable: true, }); }, [], @@ -44,13 +44,13 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { ); const { data: environments = [], status: environmentStatus } = useFetcher( - callApmApi => { + (callApmApi) => { if (newConfig.service.name) { return callApmApi({ pathname: '/api/apm/settings/agent-configuration/environments', params: { - query: { serviceName: omitAllOption(newConfig.service.name) } - } + query: { serviceName: omitAllOption(newConfig.service.name) }, + }, }); } }, @@ -59,7 +59,7 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { ); const { status: agentNameStatus } = useFetcher( - async callApmApi => { + async (callApmApi) => { const serviceName = newConfig.service.name; if (!isString(serviceName) || serviceName.length === 0) { @@ -68,10 +68,10 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { const { agentName } = await callApmApi({ pathname: '/api/apm/settings/agent-configuration/agent_name', - params: { query: { serviceName } } + params: { query: { serviceName } }, }); - setNewConfig(prev => ({ ...prev, agent_name: agentName })); + setNewConfig((prev) => ({ ...prev, agent_name: agentName })); }, [newConfig.service.name, setNewConfig] ); @@ -81,9 +81,9 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { { defaultMessage: 'already configured' } ); - const serviceNameOptions = serviceNames.map(name => ({ + const serviceNameOptions = serviceNames.map((name) => ({ text: getOptionLabel(name), - value: name + value: name, })); const environmentOptions = environments.map( ({ name, alreadyConfigured }) => ({ @@ -91,7 +91,7 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { text: `${getOptionLabel(name)} ${ alreadyConfigured ? `(${ALREADY_CONFIGURED_TRANSLATED})` : '' }`, - value: name + value: name, }) ); @@ -100,7 +100,7 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) {

      {i18n.translate('xpack.apm.agentConfig.servicePage.title', { - defaultMessage: 'Choose service' + defaultMessage: 'Choose service', })}

      @@ -125,12 +125,12 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { options={serviceNameOptions} value={newConfig.service.name} disabled={serviceNamesStatus === FETCH_STATUS.LOADING} - onChange={e => { + onChange={(e) => { e.preventDefault(); const name = e.target.value; - setNewConfig(prev => ({ + setNewConfig((prev) => ({ ...prev, - service: { name, environment: '' } + service: { name, environment: '' }, })); }} /> @@ -145,7 +145,7 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { 'xpack.apm.agentConfig.servicePage.environment.description', { defaultMessage: - 'Only a single environment per configuration is supported.' + 'Only a single environment per configuration is supported.', } )} fieldLabel={i18n.translate( @@ -158,12 +158,12 @@ export function ServicePage({ newConfig, setNewConfig, onClickNext }: Props) { disabled={ !newConfig.service.name || environmentStatus === FETCH_STATUS.LOADING } - onChange={e => { + onChange={(e) => { e.preventDefault(); const environment = e.target.value; - setNewConfig(prev => ({ + setNewConfig((prev) => ({ ...prev, - service: { name: prev.service.name, environment } + service: { name: prev.service.name, environment }, })); }} /> diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx index 6711fecc2376c..629579a6c9caf 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingFormRow.tsx @@ -14,21 +14,21 @@ import { EuiFlexItem, EuiCode, EuiSpacer, - EuiIconTip + EuiIconTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { SettingDefinition } from '../../../../../../../common/agent_configuration/setting_definitions/types'; import { validateSetting } from '../../../../../../../common/agent_configuration/setting_definitions'; import { amountAndUnitToString, - amountAndUnitToObject + amountAndUnitToObject, } from '../../../../../../../common/agent_configuration/amount_and_unit'; import { SelectWithPlaceholder } from '../../../../../shared/SelectWithPlaceholder'; function FormRow({ setting, value, - onChange + onChange, }: { setting: SettingDefinition; value?: string; @@ -41,7 +41,7 @@ function FormRow({ onChange(setting.key, e.target.value)} + onChange={(e) => onChange(setting.key, e.target.value)} /> ); } @@ -53,7 +53,7 @@ function FormRow({ value={(value as any) || ''} min={setting.min} max={setting.max} - onChange={e => onChange(setting.key, e.target.value)} + onChange={(e) => onChange(setting.key, e.target.value)} /> ); } @@ -64,7 +64,7 @@ function FormRow({ placeholder={setting.placeholder} options={setting.options} value={value} - onChange={e => onChange(setting.key, e.target.value)} + onChange={(e) => onChange(setting.key, e.target.value)} /> ); } @@ -75,10 +75,10 @@ function FormRow({ placeholder={setting.placeholder} options={[ { text: 'true', value: 'true' }, - { text: 'false', value: 'false' } + { text: 'false', value: 'false' }, ]} value={value} - onChange={e => onChange(setting.key, e.target.value)} + onChange={(e) => onChange(setting.key, e.target.value)} /> ); } @@ -93,12 +93,12 @@ function FormRow({ + onChange={(e) => onChange( setting.key, amountAndUnitToString({ amount: e.target.value, - unit + unit, }) ) } @@ -107,11 +107,11 @@ function FormRow({ ({ text, value: text }))} - onChange={e => + options={setting.units?.map((text) => ({ text, value: text }))} + onChange={(e) => onChange( setting.key, amountAndUnitToString({ amount, unit: e.target.value }) @@ -132,7 +132,7 @@ export function SettingFormRow({ isUnsaved, setting, value, - onChange + onChange, }: { isUnsaved: boolean; setting: SettingDefinition; diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx index bb3c2b3249363..3a08d4e74da94 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/SettingsPage.tsx @@ -16,7 +16,7 @@ import { EuiBottomBar, EuiText, EuiHealth, - EuiLoadingSpinner + EuiLoadingSpinner, } from '@elastic/eui'; import React, { useState, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; @@ -29,7 +29,7 @@ import { AgentConfigurationIntake } from '../../../../../../../common/agent_conf import { filterByAgent, settingDefinitions, - validateSetting + validateSetting, } from '../../../../../../../common/agent_configuration/setting_definitions'; import { saveConfig } from './saveConfig'; import { useApmPluginContext } from '../../../../../../hooks/useApmPluginContext'; @@ -50,7 +50,7 @@ export function SettingsPage({ setNewConfig, resetSettings, isEditMode, - onClickEdit + onClickEdit, }: { status?: FETCH_STATUS; unsavedChanges: Record; @@ -77,7 +77,7 @@ export function SettingsPage({ }) // every setting must be valid for the form to be valid - .every(def => { + .every((def) => { const value = newConfig.settings[def.key]; return validateSetting(def, value).isValid; }) @@ -95,7 +95,7 @@ export function SettingsPage({ // go back to overview history.push({ pathname: '/settings/agent-configuration', - search: history.location.search + search: history.location.search, }); }; @@ -125,7 +125,7 @@ export function SettingsPage({ {/* Since the submit button is placed outside the form we cannot use `onSubmit` and have to use `onKeyPress` to submit the form on enter */} {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */} { + onKeyPress={(e) => { const didClickEnter = e.which === 13; if (didClickEnter && isFormValid) { e.preventDefault(); @@ -138,7 +138,7 @@ export function SettingsPage({

      {i18n.translate('xpack.apm.agentConfig.chooseService.title', { - defaultMessage: 'Choose service' + defaultMessage: 'Choose service', })}

      @@ -192,7 +192,7 @@ export function SettingsPage({

      {i18n.translate('xpack.apm.agentConfig.settings.title', { - defaultMessage: 'Configuration options' + defaultMessage: 'Configuration options', })}

      @@ -219,7 +219,7 @@ export function SettingsPage({ grow={false} style={{ flexDirection: 'row', - alignItems: 'center' + alignItems: 'center', }} > @@ -227,7 +227,7 @@ export function SettingsPage({ {i18n.translate('xpack.apm.unsavedChanges', { defaultMessage: '{unsavedChangesCount, plural, =0{0 unsaved changes} one {1 unsaved change} other {# unsaved changes}} ', - values: { unsavedChangesCount } + values: { unsavedChangesCount }, })}
      @@ -268,7 +268,7 @@ export function SettingsPage({ function renderSettings({ newConfig, unsavedChanges, - setNewConfig + setNewConfig, }: { newConfig: AgentConfigurationIntake; unsavedChanges: Record; @@ -280,19 +280,19 @@ function renderSettings({ // filter out agent specific items that are not applicable // to the selected service .filter(filterByAgent(newConfig.agent_name as AgentName)) - .map(setting => ( + .map((setting) => ( { - setNewConfig(prev => ({ + setNewConfig((prev) => ({ ...prev, settings: { ...prev.settings, - [key]: value - } + [key]: value, + }, })); }} /> diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts index 5f7354bf6f713..4e75b24e6af95 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/SettingsPage/saveConfig.ts @@ -9,14 +9,14 @@ import { NotificationsStart } from 'kibana/public'; import { AgentConfigurationIntake } from '../../../../../../../common/agent_configuration/configuration_types'; import { getOptionLabel, - omitAllOption + omitAllOption, } from '../../../../../../../common/agent_configuration/all_option'; import { callApmApi } from '../../../../../../services/rest/createCallApmApi'; export async function saveConfig({ config, isEditMode, - toasts + toasts, }: { config: AgentConfigurationIntake; agentName?: string; @@ -33,10 +33,10 @@ export async function saveConfig({ ...config, service: { name: omitAllOption(config.service.name), - environment: omitAllOption(config.service.environment) - } - } - } + environment: omitAllOption(config.service.environment), + }, + }, + }, }); toasts.addSuccess({ @@ -47,22 +47,22 @@ export async function saveConfig({ text: i18n.translate('xpack.apm.agentConfig.saveConfig.succeeded.text', { defaultMessage: 'The configuration for "{serviceName}" was saved. It will take some time to propagate to the agents.', - values: { serviceName: getOptionLabel(config.service.name) } - }) + values: { serviceName: getOptionLabel(config.service.name) }, + }), }); } catch (error) { toasts.addDanger({ title: i18n.translate('xpack.apm.agentConfig.saveConfig.failed.title', { - defaultMessage: 'Configuration could not be saved' + defaultMessage: 'Configuration could not be saved', }), text: i18n.translate('xpack.apm.agentConfig.saveConfig.failed.text', { defaultMessage: 'Something went wrong when saving the configuration for "{serviceName}". Error: "{errorMessage}"', values: { serviceName: getOptionLabel(config.service.name), - errorMessage: error.message - } - }) + errorMessage: error.message, + }, + }), }); } } diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx index 089bc58f50a88..7c69fb28d668f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.stories.tsx @@ -19,7 +19,7 @@ import { createCallApmApi } from '../../../../../services/rest/createCallApmApi' import { AgentConfigurationCreateEdit } from './index'; import { ApmPluginContext, - ApmPluginContextValue + ApmPluginContextValue, } from '../../../../../context/ApmPluginContext'; storiesOf( @@ -35,8 +35,10 @@ storiesOf( const contextMock = { core: { - notifications: { toasts: { addWarning: () => {}, addDanger: () => {} } } - } + notifications: { + toasts: { addWarning: () => {}, addDanger: () => {} }, + }, + }, }; return ( @@ -57,7 +59,7 @@ storiesOf( }, { info: { - source: false - } + source: false, + }, } ); diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx index 79a6370b4be46..5bb678d1c08af 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/AgentConfigurationCreateEdit/index.tsx @@ -12,7 +12,7 @@ import { FetcherResult } from '../../../../../hooks/useFetcher'; import { history } from '../../../../../utils/history'; import { AgentConfigurationIntake, - AgentConfiguration + AgentConfiguration, } from '../../../../../../common/agent_configuration/configuration_types'; import { ServicePage } from './ServicePage/ServicePage'; import { SettingsPage } from './SettingsPage/SettingsPage'; @@ -26,7 +26,7 @@ function getInitialNewConfig( return { agent_name: existingConfig?.agent_name, service: existingConfig?.service || {}, - settings: existingConfig?.settings || {} + settings: existingConfig?.settings || {}, }; } @@ -35,14 +35,14 @@ function setPage(pageStep: PageStep) { ...history.location, search: fromQuery({ ...toQuery(history.location.search), - pageStep - }) + pageStep, + }), }); } function getUnsavedChanges({ newConfig, - existingConfig + existingConfig, }: { newConfig: AgentConfigurationIntake; existingConfig?: AgentConfigurationIntake; @@ -63,7 +63,7 @@ function getUnsavedChanges({ export function AgentConfigurationCreateEdit({ pageStep, - existingConfigResult + existingConfigResult, }: { pageStep: PageStep; existingConfigResult?: FetcherResult; @@ -75,9 +75,9 @@ export function AgentConfigurationCreateEdit({ ); const resetSettings = useCallback(() => { - setNewConfig(_newConfig => ({ + setNewConfig((_newConfig) => ({ ..._newConfig, - settings: existingConfig?.settings || {} + settings: existingConfig?.settings || {}, })); }, [existingConfig]); @@ -110,10 +110,10 @@ export function AgentConfigurationCreateEdit({

      {isEditMode ? i18n.translate('xpack.apm.agentConfig.editConfigTitle', { - defaultMessage: 'Edit configuration' + defaultMessage: 'Edit configuration', }) : i18n.translate('xpack.apm.agentConfig.createConfigTitle', { - defaultMessage: 'Create configuration' + defaultMessage: 'Create configuration', })}

      @@ -122,7 +122,7 @@ export function AgentConfigurationCreateEdit({ {i18n.translate('xpack.apm.agentConfig.newConfig.description', { defaultMessage: `This allows you to fine-tune your agent configuration directly in Kibana. Best of all, changes are automatically propagated to your APM - agents so there’s no need to redeploy.` + agents so there’s no need to redeploy.`, })} diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx index 6a1a472562305..aca04a3e46ad0 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/ConfirmDeleteModal.tsx @@ -30,7 +30,7 @@ export function ConfirmDeleteModal({ config, onCancel, onConfirm }: Props) { { @@ -56,8 +56,8 @@ export function ConfirmDeleteModal({ config, onCancel, onConfirm }: Props) { defaultMessage: `You are about to delete the configuration for service "{serviceName}" and environment "{environment}".`, values: { serviceName: getOptionLabel(config.service.name), - environment: getOptionLabel(config.service.environment) - } + environment: getOptionLabel(config.service.environment), + }, })}

      @@ -77,10 +77,10 @@ async function deleteConfig( body: { service: { name: config.service.name, - environment: config.service.environment - } - } - } + environment: config.service.environment, + }, + }, + }, }); toasts.addSuccess({ @@ -93,9 +93,9 @@ async function deleteConfig( { defaultMessage: 'You have successfully deleted a configuration for "{serviceName}". It will take some time to propagate to the agents.', - values: { serviceName: getOptionLabel(config.service.name) } + values: { serviceName: getOptionLabel(config.service.name) }, } - ) + ), }); } catch (error) { toasts.addDanger({ @@ -110,10 +110,10 @@ async function deleteConfig( 'Something went wrong when deleting a configuration for "{serviceName}". Error: "{errorMessage}"', values: { serviceName: getOptionLabel(config.service.name), - errorMessage: error.message - } + errorMessage: error.message, + }, } - ) + ), }); } } diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx index 9eaa7786baca0..6d850b66f2980 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/List/index.tsx @@ -12,7 +12,7 @@ import { EuiButtonEmpty, EuiHealth, EuiToolTip, - EuiButtonIcon + EuiButtonIcon, } from '@elastic/eui'; import { isEmpty } from 'lodash'; import theme from '@elastic/eui/dist/eui_theme_light.json'; @@ -26,7 +26,7 @@ import { px, units } from '../../../../../style/variables'; import { getOptionLabel } from '../../../../../../common/agent_configuration/all_option'; import { createAgentConfigurationHref, - editAgentConfigurationHref + editAgentConfigurationHref, } from '../../../../shared/Links/apm/agentConfigurationLinks'; import { ConfirmDeleteModal } from './ConfirmDeleteModal'; @@ -35,7 +35,7 @@ type Config = AgentConfigurationListAPIResponse[0]; export function AgentConfigurationList({ status, data, - refetch + refetch, }: { status: FETCH_STATUS; data: Config[]; @@ -63,7 +63,7 @@ export function AgentConfigurationList({ 'xpack.apm.agentConfig.configTable.emptyPromptText', { defaultMessage: - "Let's change that! You can fine-tune agent configuration directly from Kibana without having to redeploy. Get started by creating your first configuration." + "Let's change that! You can fine-tune agent configuration directly from Kibana without having to redeploy. Get started by creating your first configuration.", } )}

      @@ -90,7 +90,7 @@ export function AgentConfigurationList({ 'xpack.apm.agentConfig.configTable.configTable.failurePromptText', { defaultMessage: - 'The list of agent configurations could not be fetched. Your user may not have the sufficient permissions.' + 'The list of agent configurations could not be fetched. Your user may not have the sufficient permissions.', } )}

      @@ -130,7 +130,7 @@ export function AgentConfigurationList({ > - ) + ), }, { field: 'service.name', @@ -148,7 +148,7 @@ export function AgentConfigurationList({ > {getOptionLabel(config.service.name)} - ) + ), }, { field: 'service.environment', @@ -157,7 +157,7 @@ export function AgentConfigurationList({ { defaultMessage: 'Service environment' } ), sortable: true, - render: (environment: string) => getOptionLabel(environment) + render: (environment: string) => getOptionLabel(environment), }, { align: 'right', @@ -169,7 +169,7 @@ export function AgentConfigurationList({ sortable: true, render: (value: number) => ( - ) + ), }, { width: px(units.double), @@ -180,7 +180,7 @@ export function AgentConfigurationList({ iconType="pencil" href={editAgentConfigurationHref(config.service)} /> - ) + ), }, { width: px(units.double), @@ -191,8 +191,8 @@ export function AgentConfigurationList({ iconType="trash" onClick={() => setConfigToBeDeleted(config)} /> - ) - } + ), + }, ]; return ( diff --git a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/index.tsx index 4349e542449cc..1e6015a9589b0 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/AgentConfigurations/index.tsx @@ -12,7 +12,7 @@ import { EuiFlexItem, EuiPanel, EuiSpacer, - EuiButton + EuiButton, } from '@elastic/eui'; import { isEmpty } from 'lodash'; import { useFetcher } from '../../../../hooks/useFetcher'; @@ -22,7 +22,7 @@ import { createAgentConfigurationHref } from '../../../shared/Links/apm/agentCon export function AgentConfigurations() { const { refetch, data = [], status } = useFetcher( - callApmApi => + (callApmApi) => callApmApi({ pathname: '/api/apm/settings/agent-configuration' }), [], { preservePreviousData: false } @@ -67,7 +67,7 @@ function CreateConfigurationButton() { {i18n.translate('xpack.apm.agentConfig.createConfigButtonLabel', { - defaultMessage: 'Create configuration' + defaultMessage: 'Create configuration', })} diff --git a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.test.tsx index b03960861e0ad..b1c7ab3d19889 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.test.tsx @@ -14,7 +14,7 @@ describe('ApmIndices', () => { it('should not get stuck in infinite loop', () => { const spy = spyOn(hooks, 'useFetcher').and.returnValue({ data: undefined, - status: 'loading' + status: 'loading', }); const { getByText } = render( diff --git a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx index ac8908b6e425c..145fb9683cb61 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/ApmIndices/index.tsx @@ -17,7 +17,7 @@ import { EuiFormRow, EuiFieldText, EuiButton, - EuiButtonEmpty + EuiButtonEmpty, } from '@elastic/eui'; import { useFetcher } from '../../../../hooks/useFetcher'; import { callApmApi } from '../../../../services/rest/createCallApmApi'; @@ -30,44 +30,44 @@ const APM_INDEX_LABELS = [ label: i18n.translate( 'xpack.apm.settings.apmIndices.sourcemapIndicesLabel', { defaultMessage: 'Sourcemap Indices' } - ) + ), }, { configurationName: 'apm_oss.errorIndices', label: i18n.translate('xpack.apm.settings.apmIndices.errorIndicesLabel', { - defaultMessage: 'Error Indices' - }) + defaultMessage: 'Error Indices', + }), }, { configurationName: 'apm_oss.onboardingIndices', label: i18n.translate( 'xpack.apm.settings.apmIndices.onboardingIndicesLabel', { defaultMessage: 'Onboarding Indices' } - ) + ), }, { configurationName: 'apm_oss.spanIndices', label: i18n.translate('xpack.apm.settings.apmIndices.spanIndicesLabel', { - defaultMessage: 'Span Indices' - }) + defaultMessage: 'Span Indices', + }), }, { configurationName: 'apm_oss.transactionIndices', label: i18n.translate( 'xpack.apm.settings.apmIndices.transactionIndicesLabel', { defaultMessage: 'Transaction Indices' } - ) + ), }, { configurationName: 'apm_oss.metricsIndices', label: i18n.translate('xpack.apm.settings.apmIndices.metricsIndicesLabel', { - defaultMessage: 'Metrics Indices' - }) - } + defaultMessage: 'Metrics Indices', + }), + }, ]; async function saveApmIndices({ - apmIndices + apmIndices, }: { apmIndices: Record; }) { @@ -75,8 +75,8 @@ async function saveApmIndices({ method: 'POST', pathname: '/api/apm/settings/apm-indices/save', params: { - body: apmIndices - } + body: apmIndices, + }, }); clearCache(); @@ -92,9 +92,9 @@ export function ApmIndices() { const [isSaving, setIsSaving] = useState(false); const { data = INITIAL_STATE, status, refetch } = useFetcher( - _callApmApi => + (_callApmApi) => _callApmApi({ - pathname: `/api/apm/settings/apm-index-settings` + pathname: `/api/apm/settings/apm-index-settings`, }), [] ); @@ -104,7 +104,7 @@ export function ApmIndices() { data.reduce( (acc, { configurationName, savedValue }) => ({ ...acc, - [configurationName]: savedValue + [configurationName]: savedValue, }), {} ) @@ -129,9 +129,9 @@ export function ApmIndices() { 'xpack.apm.settings.apmIndices.applyChanges.succeeded.text', { defaultMessage: - 'The indices changes were successfully applied. These changes are reflected immediately in the APM UI' + 'The indices changes were successfully applied. These changes are reflected immediately in the APM UI', } - ) + ), }); } catch (error) { toasts.addDanger({ @@ -144,9 +144,9 @@ export function ApmIndices() { { defaultMessage: 'Something went wrong when applying indices. Error: {errorMessage}', - values: { errorMessage: error.message } + values: { errorMessage: error.message }, } - ) + ), }); } setIsSaving(false); @@ -158,7 +158,7 @@ export function ApmIndices() { const { name, value } = event.target; setApmIndices({ ...apmIndices, - [name]: value + [name]: value, }); }; @@ -169,7 +169,7 @@ export function ApmIndices() {

      {i18n.translate('xpack.apm.settings.apmIndices.title', { - defaultMessage: 'Indices' + defaultMessage: 'Indices', })}

      @@ -177,7 +177,7 @@ export function ApmIndices() {

      {i18n.translate('xpack.apm.settings.apmIndices.description', { - defaultMessage: `The APM UI uses index patterns to query your APM indices. If you've customized the index names that APM Server writes events to, you may need to update these patterns for the APM UI to work. Settings here take precedence over those set in kibana.yml.` + defaultMessage: `The APM UI uses index patterns to query your APM indices. If you've customized the index names that APM Server writes events to, you may need to update these patterns for the APM UI to work. Settings here take precedence over those set in kibana.yml.`, })}

      @@ -199,7 +199,7 @@ export function ApmIndices() { { defaultMessage: 'Overrides {configurationName}: {defaultValue}', - values: { configurationName, defaultValue } + values: { configurationName, defaultValue }, } )} fullWidth diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx index 415d2557c23c3..919cc4debe4d8 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CreateCustomLinkButton.tsx @@ -8,7 +8,7 @@ import { EuiButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; export const CreateCustomLinkButton = ({ - onClick + onClick, }: { onClick: () => void; }) => ( diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/DeleteButton.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/DeleteButton.tsx index 87cb171518ea4..686970c0493ee 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/DeleteButton.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/DeleteButton.tsx @@ -35,7 +35,7 @@ export function DeleteButton({ onDelete, customLinkId }: Props) { style={{ marginRight: px(unit) }} > {i18n.translate('xpack.apm.settings.customizeUI.customLink.delete', { - defaultMessage: 'Delete' + defaultMessage: 'Delete', })} ); @@ -50,15 +50,15 @@ async function deleteConfig( pathname: '/api/apm/settings/custom_links/{id}', method: 'DELETE', params: { - path: { id: customLinkId } - } + path: { id: customLinkId }, + }, }); toasts.addSuccess({ iconType: 'trash', title: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.delete.successed', { defaultMessage: 'Deleted custom link.' } - ) + ), }); } catch (error) { toasts.addDanger({ @@ -66,7 +66,7 @@ async function deleteConfig( title: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.delete.failed', { defaultMessage: 'Custom link could not be deleted' } - ) + ), }); } } diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx index 9c244e3cde411..daadc1bace9c4 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FiltersSection.tsx @@ -11,24 +11,24 @@ import { EuiSelect, EuiSpacer, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEmpty } from 'lodash'; import React from 'react'; import { Filter, - FilterKey + FilterKey, } from '../../../../../../../common/custom_link/custom_link_types'; import { DEFAULT_OPTION, FILTER_SELECT_OPTIONS, - getSelectOptions + getSelectOptions, } from './helper'; export const FiltersSection = ({ filters, - onChangeFilters + onChangeFilters, }: { filters: Filter[]; onChangeFilters: (filters: Filter[]) => void; @@ -68,7 +68,7 @@ export const FiltersSection = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.filters.title', { - defaultMessage: 'Filters' + defaultMessage: 'Filters', } )} @@ -79,7 +79,7 @@ export const FiltersSection = ({ 'xpack.apm.settings.customizeUI.customLink.flyout.filters.subtitle', { defaultMessage: - 'Use the filter options to scope them to only appear for specific services.' + 'Use the filter options to scope them to only appear for specific services.', } )}
      @@ -102,10 +102,10 @@ export const FiltersSection = ({ prepend={i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.filters.prepend', { - defaultMessage: 'Field' + defaultMessage: 'Field', } )} - onChange={e => + onChange={(e) => onChangeFilter(e.target.value as FilterKey, value, idx) } isInvalid={ @@ -122,7 +122,7 @@ export const FiltersSection = ({ 'xpack.apm.settings.customizeUI.customLink.flyOut.filters.defaultOption.value', { defaultMessage: 'Value' } )} - onChange={e => onChangeFilter(key, e.target.value, idx)} + onChange={(e) => onChangeFilter(key, e.target.value, idx)} value={value} isInvalid={!isEmpty(key) && isEmpty(value)} /> @@ -151,7 +151,7 @@ export const FiltersSection = ({ const AddFilterButton = ({ onClick, - isDisabled + isDisabled, }: { onClick: () => void; isDisabled: boolean; @@ -164,7 +164,7 @@ const AddFilterButton = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.filters.addAnotherFilter', { - defaultMessage: 'Add another filter' + defaultMessage: 'Add another filter', } )} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx index 96505d639bcdd..4fde75602990c 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/FlyoutFooter.tsx @@ -9,7 +9,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty, - EuiButton + EuiButton, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { DeleteButton } from './DeleteButton'; @@ -19,7 +19,7 @@ export const FlyoutFooter = ({ isSaving, onDelete, customLinkId, - isSaveButtonEnabled + isSaveButtonEnabled, }: { onClose: () => void; isSaving: boolean; @@ -35,7 +35,7 @@ export const FlyoutFooter = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.close', { - defaultMessage: 'Close' + defaultMessage: 'Close', } )} @@ -53,7 +53,7 @@ export const FlyoutFooter = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.save', { - defaultMessage: 'Save' + defaultMessage: 'Save', } )} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.test.tsx index a1afbd7a807cc..7b98f978f0f2f 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.test.tsx @@ -10,7 +10,7 @@ import { getNodeText, getByTestId, act, - wait + wait, } from '@testing-library/react'; import * as apmApi from '../../../../../../services/rest/createCallApmApi'; @@ -18,7 +18,7 @@ describe('LinkPreview', () => { let callApmApiSpy: jasmine.Spy; beforeAll(() => { callApmApiSpy = spyOn(apmApi, 'callApmApi').and.returnValue({ - transaction: { id: 'foo' } + transaction: { id: 'foo' }, }); }); afterAll(() => { diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx index 8fed838a48261..b229157d1b1a8 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkPreview.tsx @@ -13,7 +13,7 @@ import { EuiToolTip, EuiIcon, EuiFlexGroup, - EuiFlexItem + EuiFlexItem, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { debounce } from 'lodash'; @@ -32,7 +32,7 @@ const fetchTransaction = debounce( async (filters: Filter[], callback: (transaction: Transaction) => void) => { const transaction = await callApmApi({ pathname: '/api/apm/settings/custom_links/transaction', - params: { query: convertFiltersToQuery(filters) } + params: { query: convertFiltersToQuery(filters) }, }); callback(transaction); }, @@ -108,7 +108,7 @@ export const LinkPreview = ({ label, url, filters }: Props) => { 'xpack.apm.settings.customizeUI.customLink.linkPreview.descrition', { defaultMessage: - 'Test your link with values from an example transaction document based on the filters above.' + 'Test your link with values from an example transaction document based on the filters above.', } )} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx index 210033888d90c..6a31752d11705 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/LinkSection.tsx @@ -8,7 +8,7 @@ import { EuiFormRow, EuiSpacer, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; @@ -35,7 +35,7 @@ export const LinkSection = ({ label, onChangeLabel, url, - onChangeUrl + onChangeUrl, }: Props) => { const inputFields: InputField[] = [ { @@ -43,31 +43,31 @@ export const LinkSection = ({ label: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.link.label', { - defaultMessage: 'Label' + defaultMessage: 'Label', } ), helpText: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.link.label.helpText', { defaultMessage: - 'This is the label shown in the actions context menu. Keep it as short as possible.' + 'This is the label shown in the actions context menu. Keep it as short as possible.', } ), placeholder: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.link.label.placeholder', { - defaultMessage: 'e.g. Support tickets' + defaultMessage: 'e.g. Support tickets', } ), value: label, - onChange: onChangeLabel + onChange: onChangeLabel, }, { name: 'url', label: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.link.url', { - defaultMessage: 'URL' + defaultMessage: 'URL', } ), helpText: ( @@ -77,14 +77,14 @@ export const LinkSection = ({ { defaultMessage: 'Add field name variables to your URL to apply values e.g. {sample}.', - values: { sample: '{{trace.id}}' } + values: { sample: '{{trace.id}}' }, } )}{' '} @@ -93,12 +93,12 @@ export const LinkSection = ({ placeholder: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.link.url.placeholder', { - defaultMessage: 'e.g. https://www.elastic.co/' + defaultMessage: 'e.g. https://www.elastic.co/', } ), value: url, - onChange: onChangeUrl - } + onChange: onChangeUrl, + }, ]; return ( @@ -108,13 +108,13 @@ export const LinkSection = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.action.title', { - defaultMessage: 'Link' + defaultMessage: 'Link', } )} - {inputFields.map(field => { + {inputFields.map((field) => { return ( @@ -137,7 +137,7 @@ export const LinkSection = ({ name={field.name} fullWidth value={field.value} - onChange={e => field.onChange(e.target.value)} + onChange={(e) => field.onChange(e.target.value)} data-test-subj={field.name} /> diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.test.ts b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.test.ts index 49e381aab675d..5f8e0b9052a65 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.test.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.test.ts @@ -5,7 +5,7 @@ */ import { getSelectOptions, - replaceTemplateVariables + replaceTemplateVariables, } from '../CustomLinkFlyout/helper'; import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; @@ -18,7 +18,7 @@ describe('Custom link helper', () => { { key: '', value: '' }, { key: '', value: '' }, { key: '', value: '' }, - { key: '', value: '' } + { key: '', value: '' }, ], '' ) @@ -27,7 +27,7 @@ describe('Custom link helper', () => { { value: 'service.name', text: 'service.name' }, { value: 'service.environment', text: 'service.environment' }, { value: 'transaction.type', text: 'transaction.type' }, - { value: 'transaction.name', text: 'transaction.name' } + { value: 'transaction.name', text: 'transaction.name' }, ]); }); it('removes item added in another filter', () => { @@ -37,7 +37,7 @@ describe('Custom link helper', () => { { key: 'service.name', value: 'foo' }, { key: '', value: '' }, { key: '', value: '' }, - { key: '', value: '' } + { key: '', value: '' }, ], '' ) @@ -45,7 +45,7 @@ describe('Custom link helper', () => { { value: 'DEFAULT', text: 'Select field...' }, { value: 'service.environment', text: 'service.environment' }, { value: 'transaction.type', text: 'transaction.type' }, - { value: 'transaction.name', text: 'transaction.name' } + { value: 'transaction.name', text: 'transaction.name' }, ]); }); it('removes item added in another filter but keep the current selected', () => { @@ -55,7 +55,7 @@ describe('Custom link helper', () => { { key: 'service.name', value: 'foo' }, { key: 'transaction.name', value: 'bar' }, { key: '', value: '' }, - { key: '', value: '' } + { key: '', value: '' }, ], 'transaction.name' ) @@ -63,7 +63,7 @@ describe('Custom link helper', () => { { value: 'DEFAULT', text: 'Select field...' }, { value: 'service.environment', text: 'service.environment' }, { value: 'transaction.type', text: 'transaction.type' }, - { value: 'transaction.name', text: 'transaction.name' } + { value: 'transaction.name', text: 'transaction.name' }, ]); }); it('returns empty when all option were selected', () => { @@ -73,7 +73,7 @@ describe('Custom link helper', () => { { key: 'service.name', value: 'foo' }, { key: 'transaction.name', value: 'bar' }, { key: 'service.environment', value: 'baz' }, - { key: 'transaction.type', value: 'qux' } + { key: 'transaction.type', value: 'qux' }, ], '' ) @@ -84,7 +84,7 @@ describe('Custom link helper', () => { describe('replaceTemplateVariables', () => { const transaction = ({ service: { name: 'foo' }, - trace: { id: '123' } + trace: { id: '123' }, } as unknown) as Transaction; it('replaces template variables', () => { @@ -95,7 +95,7 @@ describe('Custom link helper', () => { ) ).toEqual({ error: undefined, - formattedUrl: 'https://elastic.co?service.name=foo&trace.id=123' + formattedUrl: 'https://elastic.co?service.name=foo&trace.id=123', }); }); @@ -103,7 +103,7 @@ describe('Custom link helper', () => { const expectedResult = { error: "We couldn't find a matching transaction document based on the defined filters.", - formattedUrl: 'https://elastic.co?service.name=&trace.id=' + formattedUrl: 'https://elastic.co?service.name=&trace.id=', }; expect( replaceTemplateVariables( @@ -127,7 +127,7 @@ describe('Custom link helper', () => { ).toEqual({ error: "We couldn't find a value match for {{service.nam}}, {{trace.i}} in the example transaction document.", - formattedUrl: 'https://elastic.co?service.name=&trace.id=' + formattedUrl: 'https://elastic.co?service.name=&trace.id=', }); }); @@ -140,7 +140,7 @@ describe('Custom link helper', () => { ).toEqual({ error: "We couldn't find an example transaction document due to invalid variable(s) defined.", - formattedUrl: 'https://elastic.co?service.name={{service.name}' + formattedUrl: 'https://elastic.co?service.name={{service.name}', }); }); }); diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.ts b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.ts index 8c35b8fe77506..489e42750a3e9 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/helper.ts @@ -9,7 +9,7 @@ import { isEmpty, get } from 'lodash'; import { FILTER_OPTIONS } from '../../../../../../../common/custom_link/custom_link_filter_options'; import { Filter, - FilterKey + FilterKey, } from '../../../../../../../common/custom_link/custom_link_types'; import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; @@ -23,15 +23,15 @@ export const DEFAULT_OPTION: FilterSelectOption = { text: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyOut.filters.defaultOption', { defaultMessage: 'Select field...' } - ) + ), }; export const FILTER_SELECT_OPTIONS: FilterSelectOption[] = [ DEFAULT_OPTION, - ...FILTER_OPTIONS.map(filter => ({ + ...FILTER_OPTIONS.map((filter) => ({ value: filter, - text: filter - })) + text: filter, + })), ]; /** @@ -57,7 +57,7 @@ const getInvalidTemplateVariables = ( return (Mustache.parse(template) as Array<[string, string]>) .filter(([type]) => type === 'name') .map(([, value]) => value) - .filter(templateVar => get(transaction, templateVar) == null); + .filter((templateVar) => get(transaction, templateVar) == null); }; const validateUrl = (url: string, transaction?: Transaction) => { @@ -66,7 +66,7 @@ const validateUrl = (url: string, transaction?: Transaction) => { 'xpack.apm.settings.customizeUI.customLink.preview.transaction.notFound', { defaultMessage: - "We couldn't find a matching transaction document based on the defined filters." + "We couldn't find a matching transaction document based on the defined filters.", } ); } @@ -80,9 +80,9 @@ const validateUrl = (url: string, transaction?: Transaction) => { "We couldn't find a value match for {variables} in the example transaction document.", values: { variables: invalidVariables - .map(variable => `{{${variable}}}`) - .join(', ') - } + .map((variable) => `{{${variable}}}`) + .join(', '), + }, } ); } @@ -91,7 +91,7 @@ const validateUrl = (url: string, transaction?: Transaction) => { 'xpack.apm.settings.customizeUI.customLink.preview.contextVariable.invalid', { defaultMessage: - "We couldn't find an example transaction document due to invalid variable(s) defined." + "We couldn't find an example transaction document due to invalid variable(s) defined.", } ); } diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx index 150147d9af405..ccd98bd005666 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/index.tsx @@ -10,7 +10,7 @@ import { EuiPortal, EuiSpacer, EuiText, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; @@ -42,7 +42,7 @@ export const CustomLinkFlyout = ({ onSave, onDelete, defaults, - customLinkId + customLinkId, }: Props) => { const { toasts } = useApmPluginContext().core.notifications; const [isSaving, setIsSaving] = useState(false); @@ -67,7 +67,7 @@ export const CustomLinkFlyout = ({ label, url, filters, - toasts + toasts, }); setIsSaving(false); onSave(); @@ -83,7 +83,7 @@ export const CustomLinkFlyout = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.flyout.title', { - defaultMessage: 'Create link' + defaultMessage: 'Create link', } )} @@ -96,14 +96,14 @@ export const CustomLinkFlyout = ({ 'xpack.apm.settings.customizeUI.customLink.flyout.label', { defaultMessage: - 'Links will be available in the context of transaction details throughout the APM app. You can create an unlimited number of links. You can refer to dynamic variables by using any of the transaction metadata to fill in your URLs. More information, including examples, are available in the' + 'Links will be available in the context of transaction details throughout the APM app. You can create an unlimited number of links. You can refer to dynamic variables by using any of the transaction metadata to fill in your URLs. More information, including examples, are available in the', } )}{' '} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/saveCustomLink.ts b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/saveCustomLink.ts index 685b3ab022950..8ccd799b7cbc6 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/saveCustomLink.ts +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkFlyout/saveCustomLink.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { NotificationsStart } from 'kibana/public'; import { Filter, - CustomLink + CustomLink, } from '../../../../../../../common/custom_link/custom_link_types'; import { callApmApi } from '../../../../../../services/rest/createCallApmApi'; @@ -17,7 +17,7 @@ export async function saveCustomLink({ label, url, filters, - toasts + toasts, }: { id?: string; label: string; @@ -29,7 +29,7 @@ export async function saveCustomLink({ const customLink: CustomLink = { label, url, - filters: filters.filter(({ key, value }) => key && value) + filters: filters.filter(({ key, value }) => key && value), }; if (id) { @@ -38,16 +38,16 @@ export async function saveCustomLink({ method: 'PUT', params: { path: { id }, - body: customLink - } + body: customLink, + }, }); } else { await callApmApi({ pathname: '/api/apm/settings/custom_links', method: 'POST', params: { - body: customLink - } + body: customLink, + }, }); } toasts.addSuccess({ @@ -55,7 +55,7 @@ export async function saveCustomLink({ title: i18n.translate( 'xpack.apm.settings.customizeUI.customLink.create.successed', { defaultMessage: 'Link saved!' } - ) + ), }); } catch (error) { toasts.addDanger({ @@ -69,10 +69,10 @@ export async function saveCustomLink({ defaultMessage: 'Something went wrong when saving the link. Error: "{errorMessage}"', values: { - errorMessage: error.message - } + errorMessage: error.message, + }, } - ) + ), }); } } diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx index d68fb757e53d1..f2aabc878bf2d 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/CustomLinkTable.tsx @@ -10,7 +10,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiText, - EuiSpacer + EuiSpacer, } from '@elastic/eui'; import { isEmpty } from 'lodash'; import { CustomLink } from '../../../../../../common/custom_link/custom_link_types'; @@ -26,7 +26,7 @@ interface Props { export const CustomLinkTable = ({ items = [], - onCustomLinkSelected + onCustomLinkSelected, }: Props) => { const [searchTerm, setSearchTerm] = useState(''); @@ -37,7 +37,7 @@ export const CustomLinkTable = ({ 'xpack.apm.settings.customizeUI.customLink.table.name', { defaultMessage: 'Name' } ), - truncateText: true + truncateText: true, }, { field: 'url', @@ -45,7 +45,7 @@ export const CustomLinkTable = ({ 'xpack.apm.settings.customizeUI.customLink.table.url', { defaultMessage: 'URL' } ), - truncateText: true + truncateText: true, }, { width: px(160), @@ -58,7 +58,7 @@ export const CustomLinkTable = ({ sortable: true, render: (value: number) => ( - ) + ), }, { width: px(units.triple), @@ -78,10 +78,10 @@ export const CustomLinkTable = ({ type: 'icon', onClick: (customLink: CustomLink) => { onCustomLinkSelected(customLink); - } - } - ] - } + }, + }, + ], + }, ]; const filteredItems = items.filter(({ label, url }) => { @@ -96,11 +96,11 @@ export const CustomLinkTable = ({ setSearchTerm(e.target.value)} + onChange={(e) => setSearchTerm(e.target.value)} placeholder={i18n.translate( 'xpack.apm.settings.customizeUI.customLink.searchInput.filter', { - defaultMessage: 'Filter links by Name and URL...' + defaultMessage: 'Filter links by Name and URL...', } )} /> @@ -131,7 +131,7 @@ const NoResultFound = ({ value }: { value: string }) => ( 'xpack.apm.settings.customizeUI.customLink.table.noResultFound', { defaultMessage: `No results for "{value}".`, - values: { value } + values: { value }, } )} diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx index e75004918f430..ee9350e320e1a 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/EmptyPrompt.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { CreateCustomLinkButton } from './CreateCustomLinkButton'; export const EmptyPrompt = ({ - onCreateCustomLinkClick + onCreateCustomLinkClick, }: { onCreateCustomLinkClick: () => void; }) => { @@ -22,7 +22,7 @@ export const EmptyPrompt = ({ {i18n.translate( 'xpack.apm.settings.customizeUI.customLink.emptyPromptTitle', { - defaultMessage: 'No links found.' + defaultMessage: 'No links found.', } )} @@ -34,7 +34,7 @@ export const EmptyPrompt = ({ 'xpack.apm.settings.customizeUI.customLink.emptyPromptText', { defaultMessage: - "Let's change that! You can add custom links to the Actions context menu by the transaction details for each service. Create a helpful link to your company's support portal or open a new bug report. Learn more about it in our docs." + "Let's change that! You can add custom links to the Actions context menu by the transaction details for each service. Create a helpful link to your company's support portal or open a new bug report. Learn more about it in our docs.", } )}

      diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx index 07af7b0c0e7db..95b8adb403981 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/Title.tsx @@ -15,7 +15,7 @@ export const Title = () => (

      {i18n.translate('xpack.apm.settings.customizeUI.customLink', { - defaultMessage: 'Custom Links' + defaultMessage: 'Custom Links', })}

      @@ -28,7 +28,7 @@ export const Title = () => ( 'xpack.apm.settings.customizeUI.customLink.info', { defaultMessage: - 'These links will be shown in the Actions context menu for transactions.' + 'These links will be shown in the Actions context menu for transactions.', } )} /> diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx index 32a08f5ffaf7c..6b27fbdaaf66b 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.test.tsx @@ -14,7 +14,7 @@ import { LicenseContext } from '../../../../../context/LicenseContext'; import { CustomLinkOverview } from '.'; import { expectTextsInDocument, - expectTextsNotInDocument + expectTextsNotInDocument, } from '../../../../../utils/testHelpers'; import * as saveCustomLink from './CustomLinkFlyout/saveCustomLink'; import { MockApmPluginContextWrapper } from '../../../../../context/ApmPluginContext/MockApmPluginContext'; @@ -24,14 +24,14 @@ const data = [ id: '1', label: 'label 1', url: 'url 1', - 'service.name': 'opbeans-java' + 'service.name': 'opbeans-java', }, { id: '2', label: 'label 2', url: 'url 2', - 'transaction.type': 'request' - } + 'transaction.type': 'request', + }, ]; describe('CustomLink', () => { @@ -49,14 +49,14 @@ describe('CustomLink', () => { mode: 'gold', status: 'active', type: 'gold', - uid: '1' - } + uid: '1', + }, }); describe('empty prompt', () => { beforeAll(() => { spyOn(hooks, 'useFetcher').and.returnValue({ data: [], - status: 'success' + status: 'success', }); }); @@ -77,7 +77,7 @@ describe('CustomLink', () => { beforeAll(() => { spyOn(hooks, 'useFetcher').and.returnValue({ data, - status: 'success' + status: 'success', }); }); @@ -97,7 +97,7 @@ describe('CustomLink', () => { 'label 1', 'url 1', 'label 2', - 'url 2' + 'url 2', ]); }); @@ -126,7 +126,7 @@ describe('CustomLink', () => { spyOn(hooks, 'useFetcher').and.returnValue({ data, status: 'success', - refetch + refetch, }); }); afterEach(() => { @@ -157,13 +157,13 @@ describe('CustomLink', () => { const labelInput = component.getByTestId('label'); act(() => { fireEvent.change(labelInput, { - target: { value: 'foo' } + target: { value: 'foo' }, }); }); const urlInput = component.getByTestId('url'); act(() => { fireEvent.change(urlInput, { - target: { value: 'bar' } + target: { value: 'bar' }, }); }); await act(async () => { @@ -225,12 +225,12 @@ describe('CustomLink', () => { } const field = component.getByTestId(fieldName) as HTMLSelectElement; const optionsAvailable = Object.values(field) - .map(option => (option as HTMLOptionElement).text) - .filter(option => option); + .map((option) => (option as HTMLOptionElement).text) + .filter((option) => option); act(() => { fireEvent.change(field, { - target: { value: selectValue } + target: { value: selectValue }, }); }); expect(field.value).toEqual(selectValue); @@ -242,25 +242,25 @@ describe('CustomLink', () => { 'service.name', 'service.environment', 'transaction.type', - 'transaction.name' + 'transaction.name', ]); addFieldAndCheck('filter-1', 'service.name', true, [ 'Select field...', 'service.name', 'service.environment', - 'transaction.type' + 'transaction.type', ]); addFieldAndCheck('filter-2', 'transaction.type', true, [ 'Select field...', 'service.environment', - 'transaction.type' + 'transaction.type', ]); addFieldAndCheck('filter-3', 'service.environment', true, [ 'Select field...', - 'service.environment' + 'service.environment', ]); }); }); @@ -270,7 +270,7 @@ describe('CustomLink', () => { beforeAll(() => { spyOn(hooks, 'useFetcher').and.returnValue({ data: [], - status: 'success' + status: 'success', }); }); it('shows license prompt when user has a basic license', () => { @@ -281,8 +281,8 @@ describe('CustomLink', () => { mode: 'basic', status: 'active', type: 'basic', - uid: '1' - } + uid: '1', + }, }); const component = render( @@ -301,8 +301,8 @@ describe('CustomLink', () => { mode: 'gold', status: 'invalid', type: 'gold', - uid: '1' - } + uid: '1', + }, }); const component = render( @@ -321,8 +321,8 @@ describe('CustomLink', () => { mode: 'trial', status: 'invalid', type: 'trial', - uid: '1' - } + uid: '1', + }, }); const component = render( @@ -341,8 +341,8 @@ describe('CustomLink', () => { mode: 'trial', status: 'active', type: 'trial', - uid: '1' - } + uid: '1', + }, }); const component = render( diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx index b94ce513bc210..b4acc783d08ed 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/CustomLink/index.tsx @@ -28,7 +28,7 @@ export const CustomLinkOverview = () => { >(); const { data: customLinks, status, refetch } = useFetcher( - callApmApi => callApmApi({ pathname: '/api/apm/settings/custom_links' }), + (callApmApi) => callApmApi({ pathname: '/api/apm/settings/custom_links' }), [] ); @@ -99,7 +99,7 @@ export const CustomLinkOverview = () => { 'xpack.apm.settings.customizeUI.customLink.license.text', { defaultMessage: - "To create custom links, you must be subscribed to an Elastic Gold license or above. With it, you'll have the ability to create custom links to improve your workflow when analyzing your services." + "To create custom links, you must be subscribed to an Elastic Gold license or above. With it, you'll have the ability to create custom links to improve your workflow when analyzing your services.", } )} /> diff --git a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx index 350f2185fb3c8..c88eba1c87b57 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/CustomizeUI/index.tsx @@ -15,7 +15,7 @@ export const CustomizeUI = () => {

      {i18n.translate('xpack.apm.settings.customizeApp', { - defaultMessage: 'Customize app' + defaultMessage: 'Customize app', })}

      diff --git a/x-pack/plugins/apm/public/components/app/Settings/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/index.tsx index 2bb85876686bf..578a7db1958d4 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/index.tsx @@ -11,20 +11,20 @@ import { EuiPage, EuiSideNav, EuiPageSideBar, - EuiPageBody + EuiPageBody, } from '@elastic/eui'; import { HomeLink } from '../../shared/Links/apm/HomeLink'; import { useLocation } from '../../../hooks/useLocation'; import { getAPMHref } from '../../shared/Links/apm/APMLink'; -export const Settings: React.FC = props => { +export const Settings: React.FC = (props) => { const { search, pathname } = useLocation(); return ( <> {i18n.translate('xpack.apm.settings.returnToOverviewLinkLabel', { - defaultMessage: 'Return to overview' + defaultMessage: 'Return to overview', })} @@ -34,38 +34,38 @@ export const Settings: React.FC = props => { items={[ { name: i18n.translate('xpack.apm.settings.pageTitle', { - defaultMessage: 'Settings' + defaultMessage: 'Settings', }), id: 0, items: [ { name: i18n.translate('xpack.apm.settings.agentConfig', { - defaultMessage: 'Agent Configuration' + defaultMessage: 'Agent Configuration', }), id: '1', href: getAPMHref('/settings/agent-configuration', search), isSelected: pathname.startsWith( '/settings/agent-configuration' - ) + ), }, { name: i18n.translate('xpack.apm.settings.indices', { - defaultMessage: 'Indices' + defaultMessage: 'Indices', }), id: '2', href: getAPMHref('/settings/apm-indices', search), - isSelected: pathname === '/settings/apm-indices' + isSelected: pathname === '/settings/apm-indices', }, { name: i18n.translate('xpack.apm.settings.customizeApp', { - defaultMessage: 'Customize app' + defaultMessage: 'Customize app', }), id: '3', href: getAPMHref('/settings/customize-ui', search), - isSelected: pathname === '/settings/customize-ui' - } - ] - } + isSelected: pathname === '/settings/customize-ui', + }, + ], + }, ]} /> diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/__test__/TraceLink.test.tsx b/x-pack/plugins/apm/public/components/app/TraceLink/__test__/TraceLink.test.tsx index b8d6d9818eb2c..0488815308aab 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/__test__/TraceLink.test.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceLink/__test__/TraceLink.test.tsx @@ -17,13 +17,13 @@ jest.mock('../../Main/route_config', () => ({ routes: [ { path: '/services/:serviceName/transactions/view', - name: 'transaction_name' + name: 'transaction_name', }, { path: '/traces', - name: 'traces' - } - ] + name: 'traces', + }, + ], })); describe('TraceLink', () => { @@ -40,12 +40,12 @@ describe('TraceLink', () => { urlParams: { traceIdLink: '123', rangeFrom: 'now-24h', - rangeTo: 'now' - } + rangeTo: 'now', + }, }); spyOn(hooks, 'useFetcher').and.returnValue({ data: { transaction: undefined }, - status: 'success' + status: 'success', }); const component = shallow(); @@ -60,8 +60,8 @@ describe('TraceLink', () => { urlParams: { traceIdLink: '123', rangeFrom: 'now-24h', - rangeTo: 'now' - } + rangeTo: 'now', + }, }); }); it('renders with date range params', () => { @@ -70,13 +70,13 @@ describe('TraceLink', () => { transaction: { id: '456', name: 'bar', - type: 'GET' + type: 'GET', }, - trace: { id: 123 } + trace: { id: 123 }, }; spyOn(hooks, 'useFetcher').and.returnValue({ data: { transaction }, - status: 'success' + status: 'success', }); const component = shallow(); expect(component.prop('to')).toEqual( diff --git a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx index 04d830f4649d4..3eb5a855ee3b4 100644 --- a/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceLink/index.tsx @@ -22,7 +22,7 @@ const CentralizedContainer = styled.div` const redirectToTransactionDetailPage = ({ transaction, rangeFrom, - rangeTo + rangeTo, }: { transaction: Transaction; rangeFrom?: string; @@ -36,14 +36,14 @@ const redirectToTransactionDetailPage = ({ transactionName: transaction.transaction.name, transactionType: transaction.transaction.type, rangeFrom, - rangeTo - } + rangeTo, + }, }); const redirectToTracePage = ({ traceId, rangeFrom, - rangeTo + rangeTo, }: { traceId: string; rangeFrom?: string; @@ -54,8 +54,8 @@ const redirectToTracePage = ({ query: { kuery: encodeURIComponent(`${TRACE_ID} : "${traceId}"`), rangeFrom, - rangeTo - } + rangeTo, + }, }); export const TraceLink = () => { @@ -63,15 +63,15 @@ export const TraceLink = () => { const { traceIdLink: traceId, rangeFrom, rangeTo } = urlParams; const { data = { transaction: null }, status } = useFetcher( - callApmApi => { + (callApmApi) => { if (traceId) { return callApmApi({ pathname: '/api/apm/transaction/{traceId}', params: { path: { - traceId - } - } + traceId, + }, + }, }); } }, @@ -82,7 +82,7 @@ export const TraceLink = () => { ? redirectToTransactionDetailPage({ transaction: data.transaction, rangeFrom, - rangeTo + rangeTo, }) : redirectToTracePage({ traceId, rangeFrom, rangeTo }); return ; diff --git a/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx b/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx index 92d5a38cc11ca..8fb70504be9f3 100644 --- a/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceOverview/TraceList.tsx @@ -32,7 +32,7 @@ const traceListColumns: Array> = [ { field: 'name', name: i18n.translate('xpack.apm.tracesTable.nameColumnLabel', { - defaultMessage: 'Name' + defaultMessage: 'Name', }), width: '40%', sortable: true, @@ -48,35 +48,35 @@ const traceListColumns: Array> = [ {name} - ) + ), }, { field: 'sample.service.name', name: i18n.translate( 'xpack.apm.tracesTable.originatingServiceColumnLabel', { - defaultMessage: 'Originating service' + defaultMessage: 'Originating service', } ), - sortable: true + sortable: true, }, { field: 'averageResponseTime', name: i18n.translate('xpack.apm.tracesTable.avgResponseTimeColumnLabel', { - defaultMessage: 'Avg. response time' + defaultMessage: 'Avg. response time', }), sortable: true, dataType: 'number', render: (time: number) => convertTo({ unit: 'milliseconds', - microseconds: time - }).formatted + microseconds: time, + }).formatted, }, { field: 'transactionsPerMinute', name: i18n.translate('xpack.apm.tracesTable.tracesPerMinuteColumnLabel', { - defaultMessage: 'Traces per minute' + defaultMessage: 'Traces per minute', }), sortable: true, dataType: 'number', @@ -84,9 +84,9 @@ const traceListColumns: Array> = [ `${value.toLocaleString()} ${i18n.translate( 'xpack.apm.tracesTable.tracesPerMinuteUnitLabel', { - defaultMessage: 'tpm' + defaultMessage: 'tpm', } - )}` + )}`, }, { field: 'impact', @@ -96,13 +96,13 @@ const traceListColumns: Array> = [ 'xpack.apm.tracesTable.impactColumnDescription', { defaultMessage: - "The most used and slowest endpoints in your service. It's calculated by taking the relative average duration times the number of transactions per minute." + "The most used and slowest endpoints in your service. It's calculated by taking the relative average duration times the number of transactions per minute.", } )} > <> {i18n.translate('xpack.apm.tracesTable.impactColumnLabel', { - defaultMessage: 'Impact' + defaultMessage: 'Impact', })}{' '} > = [ width: '20%', align: 'left', sortable: true, - render: (value: number) => - } + render: (value: number) => , + }, ]; const noItemsMessage = ( ); diff --git a/x-pack/plugins/apm/public/components/app/TraceOverview/index.tsx b/x-pack/plugins/apm/public/components/app/TraceOverview/index.tsx index a7fa927f9e9b1..cb6003c58e90d 100644 --- a/x-pack/plugins/apm/public/components/app/TraceOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TraceOverview/index.tsx @@ -17,7 +17,7 @@ export function TraceOverview() { const { urlParams, uiFilters } = useUrlParams(); const { start, end } = urlParams; const { status, data = [] } = useFetcher( - callApmApi => { + (callApmApi) => { if (start && end) { return callApmApi({ pathname: '/api/apm/traces', @@ -25,9 +25,9 @@ export function TraceOverview() { query: { start, end, - uiFilters: JSON.stringify(uiFilters) - } - } + uiFilters: JSON.stringify(uiFilters), + }, + }, }); } }, @@ -40,7 +40,7 @@ export function TraceOverview() { const localUIFiltersConfig = useMemo(() => { const config: React.ComponentProps = { filterNames: ['transactionResult', 'host', 'containerId', 'podName'], - projection: PROJECTION.TRACES + projection: PROJECTION.TRACES, }; return config; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/__test__/distribution.test.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/__test__/distribution.test.ts index 7ad0a77505b9d..488dba00f96f5 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/__test__/distribution.test.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/__test__/distribution.test.ts @@ -19,19 +19,19 @@ describe('Distribution', () => { count: 5, samples: [ { - transactionId: 'someTransactionId' - } - ] + transactionId: 'someTransactionId', + }, + ], }, { key: 80, count: 100, samples: [ { - transactionId: 'anotherTransactionId' - } - ] - } + transactionId: 'anotherTransactionId', + }, + ], + }, ] as IBucket[]; expect(getFormattedBuckets(buckets, 20)).toEqual([ { x: 20, x0: 0, y: 0, style: { cursor: 'default' }, samples: [] }, @@ -44,9 +44,9 @@ describe('Distribution', () => { style: { cursor: 'pointer' }, samples: [ { - transactionId: 'someTransactionId' - } - ] + transactionId: 'someTransactionId', + }, + ], }, { x: 100, @@ -55,10 +55,10 @@ describe('Distribution', () => { style: { cursor: 'pointer' }, samples: [ { - transactionId: 'anotherTransactionId' - } - ] - } + transactionId: 'anotherTransactionId', + }, + ], + }, ]); }); }); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx index b7dbfbdbd7d7e..d39ad530c1b4c 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/Distribution/index.tsx @@ -45,8 +45,8 @@ export function getFormattedBuckets(buckets: IBucket[], bucketSize: number) { x: key + bucketSize, y: count, style: { - cursor: isEmpty(samples) ? 'default' : 'pointer' - } + cursor: isEmpty(samples) ? 'default' : 'pointer', + }, }; } ); @@ -62,8 +62,8 @@ const getFormatYShort = (transactionType: string | undefined) => ( '{transCount} {transType, select, request {req.} other {trans.}}', values: { transCount: t, - transType: transactionType - } + transType: transactionType, + }, } ); }; @@ -76,8 +76,8 @@ const getFormatYLong = (transactionType: string | undefined) => (t: number) => { defaultMessage: '{transCount, plural, =0 {# request} one {# request} other {# requests}}', values: { - transCount: t - } + transCount: t, + }, } ) : i18n.translate( @@ -86,8 +86,8 @@ const getFormatYLong = (transactionType: string | undefined) => (t: number) => { defaultMessage: '{transCount, plural, =0 {# transaction} one {# transaction} other {# transactions}}', values: { - transCount: t - } + transCount: t, + }, } ); }; @@ -106,15 +106,15 @@ export const TransactionDistribution: FunctionComponent = ( distribution, urlParams: { transactionType }, isLoading, - bucketIndex + bucketIndex, } = props; const formatYShort = useCallback(getFormatYShort(transactionType), [ - transactionType + transactionType, ]); const formatYLong = useCallback(getFormatYLong(transactionType), [ - transactionType + transactionType, ]); // no data in response @@ -127,7 +127,7 @@ export const TransactionDistribution: FunctionComponent = ( return ( ); @@ -138,7 +138,7 @@ export const TransactionDistribution: FunctionComponent = ( distribution.bucketSize ); - const xMax = d3.max(buckets, d => d.x) || 0; + const xMax = d3.max(buckets, (d) => d.x) || 0; const timeFormatter = getDurationFormatter(xMax); return ( @@ -148,21 +148,21 @@ export const TransactionDistribution: FunctionComponent = ( {i18n.translate( 'xpack.apm.transactionDetails.transactionsDurationDistributionChartTitle', { - defaultMessage: 'Transactions duration distribution' + defaultMessage: 'Transactions duration distribution', } )}{' '} = ( search: fromQuery({ ...toQuery(history.location.search), transactionId: sample.transactionId, - traceId: sample.traceId - }) + traceId: sample.traceId, + }), }); } }} @@ -202,7 +202,7 @@ export const TransactionDistribution: FunctionComponent = ( i18n.translate( 'xpack.apm.transactionDetails.transactionsDurationDistributionChart.noSampleTooltip', { - defaultMessage: 'No sample available for this bucket' + defaultMessage: 'No sample available for this bucket', } ) } diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx index ff2cb69d011fa..89757b227f8fd 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/ErrorCount.tsx @@ -24,7 +24,7 @@ export const ErrorCount = ({ count }: Props) => ( {i18n.translate('xpack.apm.transactionDetails.errorCount', { defaultMessage: '{errorCount, number} {errorCount, plural, one {Error} other {Errors}}', - values: { errorCount: count } + values: { errorCount: count }, })} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/MaybeViewTraceLink.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/MaybeViewTraceLink.tsx index 1db8e02e38692..9a40d7834d18a 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/MaybeViewTraceLink.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/MaybeViewTraceLink.tsx @@ -13,7 +13,7 @@ import { IWaterfall } from './WaterfallContainer/Waterfall/waterfall_helpers/wat export const MaybeViewTraceLink = ({ transaction, - waterfall + waterfall, }: { transaction: ITransaction; waterfall: IWaterfall; @@ -21,7 +21,7 @@ export const MaybeViewTraceLink = ({ const viewFullTraceButtonLabel = i18n.translate( 'xpack.apm.transactionDetails.viewFullTraceButtonLabel', { - defaultMessage: 'View full trace' + defaultMessage: 'View full trace', } ); @@ -34,7 +34,7 @@ export const MaybeViewTraceLink = ({ content={i18n.translate( 'xpack.apm.transactionDetails.noTraceParentButtonTooltip', { - defaultMessage: 'The trace parent cannot be found' + defaultMessage: 'The trace parent cannot be found', } )} > @@ -56,7 +56,7 @@ export const MaybeViewTraceLink = ({ content={i18n.translate( 'xpack.apm.transactionDetails.viewingFullTraceButtonTooltip', { - defaultMessage: 'Currently viewing the full trace' + defaultMessage: 'Currently viewing the full trace', } )} > diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/PercentOfParent.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/PercentOfParent.tsx index 813192793b936..1725a13f4da66 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/PercentOfParent.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/PercentOfParent.tsx @@ -18,7 +18,7 @@ interface PercentOfParentProps { export function PercentOfParent({ duration, totalDuration, - parentType + parentType, }: PercentOfParentProps) { totalDuration = totalDuration || duration; const isOver100 = duration > totalDuration; @@ -29,7 +29,7 @@ export function PercentOfParent({ const percentOfParentText = i18n.translate('xpack.apm.percentOfParent', { defaultMessage: '({value} of {parentType, select, transaction { transaction } trace {trace} })', - values: { value: percentOfParent, parentType } + values: { value: percentOfParent, parentType }, }); const childType = parentType === 'trace' ? 'transaction' : 'span'; @@ -45,8 +45,8 @@ export function PercentOfParent({ 'The % of {parentType, select, transaction {transaction} trace {trace} } exceeds 100% because this {childType, select, span {span} transaction {transaction} } takes longer than the root transaction.', values: { parentType, - childType - } + childType, + }, } )} > diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/TransactionTabs.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/TransactionTabs.tsx index 27e0584c696c1..15d0f08ae9933 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/TransactionTabs.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/TransactionTabs.tsx @@ -19,15 +19,15 @@ import { IWaterfall } from './WaterfallContainer/Waterfall/waterfall_helpers/wat const timelineTab = { key: 'timeline', label: i18n.translate('xpack.apm.propertiesTable.tabs.timelineLabel', { - defaultMessage: 'Timeline' - }) + defaultMessage: 'Timeline', + }), }; const metadataTab = { key: 'metadata', label: i18n.translate('xpack.apm.propertiesTable.tabs.metadataLabel', { - defaultMessage: 'Metadata' - }) + defaultMessage: 'Metadata', + }), }; interface Props { @@ -43,7 +43,7 @@ export function TransactionTabs({ transaction, urlParams, waterfall, - exceedsMax + exceedsMax, }: Props) { const tabs = [timelineTab, metadataTab]; const currentTab = @@ -60,8 +60,8 @@ export function TransactionTabs({ ...location, search: fromQuery({ ...toQuery(location.search), - detailTab: key - }) + detailTab: key, + }), }); }} isSelected={currentTab.key === key} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_agent_marks.test.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_agent_marks.test.ts index ae908b25cc615..72533cf2930d2 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_agent_marks.test.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_agent_marks.test.ts @@ -15,43 +15,43 @@ describe('getAgentMarks', () => { agent: { domInteractive: 117, timeToFirstByte: 10, - domComplete: 118 - } - } - } + domComplete: 118, + }, + }, + }, } as any; expect(getAgentMarks(transaction)).toEqual([ { id: 'timeToFirstByte', offset: 10000, type: 'agentMark', - verticalLine: true + verticalLine: true, }, { id: 'domInteractive', offset: 117000, type: 'agentMark', - verticalLine: true + verticalLine: true, }, { id: 'domComplete', offset: 118000, type: 'agentMark', - verticalLine: true - } + verticalLine: true, + }, ]); }); it('should return empty array if marks are missing', () => { const transaction: Transaction = { - transaction: {} + transaction: {}, } as any; expect(getAgentMarks(transaction)).toEqual([]); }); it('should return empty array if agent marks are missing', () => { const transaction: Transaction = { - transaction: { marks: {} } + transaction: { marks: {} }, } as any; expect(getAgentMarks(transaction)).toEqual([]); }); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_error_marks.test.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_error_marks.test.ts index b7e83073a205b..abfecc3f70d24 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_error_marks.test.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/__test__/get_error_marks.test.ts @@ -20,14 +20,14 @@ describe('getErrorMarks', () => { docType: 'error', offset: 10, skew: 5, - doc: { error: { id: 1 }, service: { name: 'opbeans-java' } } + doc: { error: { id: 1 }, service: { name: 'opbeans-java' } }, } as unknown, { docType: 'error', offset: 50, skew: 0, - doc: { error: { id: 2 }, service: { name: 'opbeans-node' } } - } as unknown + doc: { error: { id: 2 }, service: { name: 'opbeans-node' } }, + } as unknown, ] as IWaterfallError[]; expect( getErrorMarks(items, { 'opbeans-java': 'red', 'opbeans-node': 'blue' }) @@ -38,7 +38,7 @@ describe('getErrorMarks', () => { verticalLine: false, id: 1, error: { error: { id: 1 }, service: { name: 'opbeans-java' } }, - serviceColor: 'red' + serviceColor: 'red', }, { type: 'errorMark', @@ -46,8 +46,8 @@ describe('getErrorMarks', () => { verticalLine: false, id: 2, error: { error: { id: 2 }, service: { name: 'opbeans-node' } }, - serviceColor: 'blue' - } + serviceColor: 'blue', + }, ]); }); @@ -57,14 +57,14 @@ describe('getErrorMarks', () => { docType: 'error', offset: 10, skew: 5, - doc: { error: { id: 1 }, service: { name: 'opbeans-java' } } + doc: { error: { id: 1 }, service: { name: 'opbeans-java' } }, } as unknown, { docType: 'error', offset: 50, skew: 0, - doc: { error: { id: 2 }, service: { name: 'opbeans-node' } } - } as unknown + doc: { error: { id: 2 }, service: { name: 'opbeans-node' } }, + } as unknown, ] as IWaterfallError[]; expect(getErrorMarks(items, {})).toEqual([ { @@ -73,7 +73,7 @@ describe('getErrorMarks', () => { verticalLine: false, id: 1, error: { error: { id: 1 }, service: { name: 'opbeans-java' } }, - serviceColor: undefined + serviceColor: undefined, }, { type: 'errorMark', @@ -81,8 +81,8 @@ describe('getErrorMarks', () => { verticalLine: false, id: 2, error: { error: { id: 2 }, service: { name: 'opbeans-node' } }, - serviceColor: undefined - } + serviceColor: undefined, + }, ]); }); }); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts index 2bc64e30b4f7e..97630f7d957f9 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_agent_marks.ts @@ -24,7 +24,7 @@ export function getAgentMarks(transaction?: Transaction): AgentMark[] { type: 'agentMark', id: name, offset: ms * 1000, - verticalLine: true + verticalLine: true, })), 'offset' ); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts index ad54cec5c26a7..5d8c5bc9ec6cf 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Marks/get_error_marks.ts @@ -7,7 +7,7 @@ import { isEmpty } from 'lodash'; import { ErrorRaw } from '../../../../../../../typings/es_schemas/raw/error_raw'; import { IWaterfallError, - IServiceColors + IServiceColors, } from '../Waterfall/waterfall_helpers/waterfall_helpers'; import { Mark } from '.'; @@ -25,12 +25,12 @@ export const getErrorMarks = ( return []; } - return errorItems.map(error => ({ + return errorItems.map((error) => ({ type: 'errorMark', offset: error.offset + error.skew, verticalLine: false, id: error.doc.error.id, error: error.doc, - serviceColor: serviceColors[error.doc.service.name] + serviceColor: serviceColors[error.doc.service.name], })); }; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/ServiceLegends.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/ServiceLegends.tsx index 4e6a0eaf45585..519d0b476d769 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/ServiceLegends.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/ServiceLegends.tsx @@ -34,7 +34,7 @@ export function ServiceLegends({ serviceColors }: Props) { {i18n.translate('xpack.apm.transactionDetails.servicesTitle', { - defaultMessage: 'Services' + defaultMessage: 'Services', })} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx index bbc457450e475..0187ecd927e65 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/FlyoutTopLevelProperties.tsx @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { SERVICE_NAME, - TRANSACTION_NAME + TRANSACTION_NAME, } from '../../../../../../../common/elasticsearch_fieldnames'; import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; import { TransactionDetailLink } from '../../../../../shared/Links/apm/TransactionDetailLink'; @@ -27,7 +27,7 @@ export function FlyoutTopLevelProperties({ transaction }: Props) { const stickyProperties = [ { label: i18n.translate('xpack.apm.transactionDetails.serviceLabel', { - defaultMessage: 'Service' + defaultMessage: 'Service', }), fieldName: SERVICE_NAME, val: ( @@ -35,11 +35,11 @@ export function FlyoutTopLevelProperties({ transaction }: Props) { {transaction.service.name} ), - width: '25%' + width: '25%', }, { label: i18n.translate('xpack.apm.transactionDetails.transactionLabel', { - defaultMessage: 'Transaction' + defaultMessage: 'Transaction', }), fieldName: TRANSACTION_NAME, val: ( @@ -53,8 +53,8 @@ export function FlyoutTopLevelProperties({ transaction }: Props) { {transaction.transaction.name} ), - width: '25%' - } + width: '25%', + }, ]; return ; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx index 7a08a84bf30ba..933cb3c8e8637 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/DatabaseContext.tsx @@ -12,7 +12,7 @@ import React, { Fragment } from 'react'; // @ts-ignore import sql from 'react-syntax-highlighter/dist/languages/sql'; import SyntaxHighlighter, { - registerLanguage + registerLanguage, // @ts-ignore } from 'react-syntax-highlighter/dist/light'; // @ts-ignore @@ -25,7 +25,7 @@ import { fontSize, px, unit, - units + units, } from '../../../../../../../style/variables'; import { TruncateHeightSection } from './TruncateHeightSection'; @@ -62,7 +62,7 @@ export function DatabaseContext({ dbContext }: Props) { {i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.databaseStatementTitle', { - defaultMessage: 'Database statement' + defaultMessage: 'Database statement', } )} @@ -79,7 +79,7 @@ export function DatabaseContext({ dbContext }: Props) { padding: null, lineHeight: px(dbSyntaxLineHeight), whiteSpace: 'pre-wrap', - overflowX: 'scroll' + overflowX: 'scroll', }} > {dbContext.statement} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx index 28564481074fa..7b296ebc54eab 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/HttpContext.tsx @@ -15,7 +15,7 @@ import { fontSize, px, unit, - units + units, } from '../../../../../../../style/variables'; import { Span } from '../../../../../../../../typings/es_schemas/ui/span'; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx index d49959c5cbffb..c068fee3cd6c3 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/StickySpanProperties.tsx @@ -10,7 +10,7 @@ import { Transaction } from '../../../../../../../../typings/es_schemas/ui/trans import { SPAN_NAME, TRANSACTION_NAME, - SERVICE_NAME + SERVICE_NAME, } from '../../../../../../../../common/elasticsearch_fieldnames'; import { NOT_AVAILABLE_LABEL } from '../../../../../../../../common/i18n'; import { Span } from '../../../../../../../../typings/es_schemas/ui/span'; @@ -29,7 +29,7 @@ export function StickySpanProperties({ span, transaction }: Props) { ? [ { label: i18n.translate('xpack.apm.transactionDetails.serviceLabel', { - defaultMessage: 'Service' + defaultMessage: 'Service', }), fieldName: SERVICE_NAME, val: ( @@ -37,13 +37,13 @@ export function StickySpanProperties({ span, transaction }: Props) { {transaction.service.name} ), - width: '25%' + width: '25%', }, { label: i18n.translate( 'xpack.apm.transactionDetails.transactionLabel', { - defaultMessage: 'Transaction' + defaultMessage: 'Transaction', } ), fieldName: TRANSACTION_NAME, @@ -58,8 +58,8 @@ export function StickySpanProperties({ span, transaction }: Props) { {transaction.transaction.name} ), - width: '25%' - } + width: '25%', + }, ] : []; @@ -68,15 +68,15 @@ export function StickySpanProperties({ span, transaction }: Props) { label: i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.nameLabel', { - defaultMessage: 'Name' + defaultMessage: 'Name', } ), fieldName: SPAN_NAME, val: spanName || NOT_AVAILABLE_LABEL, truncated: true, - width: '25%' + width: '25%', }, - ...transactionStickyProperties + ...transactionStickyProperties, ]; return ; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx index a42b2435ff914..64e20cf10d8aa 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/TruncateHeightSection.tsx @@ -21,7 +21,7 @@ interface Props { export const TruncateHeightSection: React.FC = ({ children, - previewHeight + previewHeight, }) => { const contentContainerEl = useRef(null); @@ -42,7 +42,7 @@ export const TruncateHeightSection: React.FC = ({ ref={contentContainerEl} style={{ overflow: 'hidden', - maxHeight: isOpen ? 'initial' : px(previewHeight) + maxHeight: isOpen ? 'initial' : px(previewHeight), }} > {children} @@ -57,16 +57,16 @@ export const TruncateHeightSection: React.FC = ({ {' '} {isOpen ? i18n.translate('xpack.apm.toggleHeight.showLessButtonLabel', { - defaultMessage: 'Show fewer lines' + defaultMessage: 'Show fewer lines', }) : i18n.translate('xpack.apm.toggleHeight.showMoreButtonLabel', { - defaultMessage: 'Show more lines' + defaultMessage: 'Show more lines', })} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/index.tsx index 1da22516629f2..4f28f7020541a 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SpanFlyout/index.tsx @@ -16,7 +16,7 @@ import { EuiTabbedContent, EuiTitle, EuiBadge, - EuiToolTip + EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { Fragment } from 'react'; @@ -44,7 +44,7 @@ function formatType(type: string) { return i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.spanType.navigationTimingLabel', { - defaultMessage: 'Navigation timing' + defaultMessage: 'Navigation timing', } ); default: @@ -67,7 +67,7 @@ function getSpanTypes(span: Span) { return { spanType: formatType(type), spanSubtype: formatSubtype(subtype), - spanAction: action + spanAction: action, }; } @@ -91,7 +91,7 @@ export function SpanFlyout({ span, parentTransaction, totalDuration, - onClose + onClose, }: Props) { if (!span) { return null; @@ -117,7 +117,7 @@ export function SpanFlyout({ {i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.spanDetailsTitle', { - defaultMessage: 'Span details' + defaultMessage: 'Span details', } )} @@ -130,7 +130,7 @@ export function SpanFlyout({ {i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.viewSpanInDiscoverButtonLabel', { - defaultMessage: 'View span in Discover' + defaultMessage: 'View span in Discover', } )} @@ -190,7 +190,7 @@ export function SpanFlyout({ )} - + , ]} /> @@ -202,7 +202,7 @@ export function SpanFlyout({ name: i18n.translate( 'xpack.apm.transactionDetails.spanFlyout.stackTraceTabLabel', { - defaultMessage: 'Stack Trace' + defaultMessage: 'Stack Trace', } ), content: ( @@ -213,14 +213,14 @@ export function SpanFlyout({ codeLanguage={codeLanguage} /> - ) + ), }, { id: 'metadata', name: i18n.translate( 'xpack.apm.propertiesTable.tabs.metadataLabel', { - defaultMessage: 'Metadata' + defaultMessage: 'Metadata', } ), content: ( @@ -228,8 +228,8 @@ export function SpanFlyout({ - ) - } + ), + }, ]} /> diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx index c7d3f6cc6f0c6..31d0d5891fca4 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.stories.tsx @@ -16,8 +16,8 @@ storiesOf('app/TransactionDetails/SyncBadge', module) }, { info: { - source: false - } + source: false, + }, } ) .add( @@ -27,8 +27,8 @@ storiesOf('app/TransactionDetails/SyncBadge', module) }, { info: { - source: false - } + source: false, + }, } ) .add( @@ -38,7 +38,7 @@ storiesOf('app/TransactionDetails/SyncBadge', module) }, { info: { - source: false - } + source: false, + }, } ); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx index f01b2aa335a3a..815f20ba244e5 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/SyncBadge.tsx @@ -28,7 +28,7 @@ export function SyncBadge({ sync }: SyncBadgeProps) { return ( {i18n.translate('xpack.apm.transactionDetails.syncBadgeBlocking', { - defaultMessage: 'blocking' + defaultMessage: 'blocking', })} ); @@ -36,7 +36,7 @@ export function SyncBadge({ sync }: SyncBadgeProps) { return ( {i18n.translate('xpack.apm.transactionDetails.syncBadgeAsync', { - defaultMessage: 'async' + defaultMessage: 'async', })} ); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx index 87ecb96f74735..d5cac547fa097 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/DroppedSpansWarning.tsx @@ -11,7 +11,7 @@ import { Transaction } from '../../../../../../../../typings/es_schemas/ui/trans import { ElasticDocsLink } from '../../../../../../shared/Links/ElasticDocsLink'; export function DroppedSpansWarning({ - transactionDoc + transactionDoc, }: { transactionDoc: Transaction; }) { @@ -28,7 +28,7 @@ export function DroppedSpansWarning({ { defaultMessage: 'The APM agent that reported this transaction dropped {dropped} spans or more based on its configuration.', - values: { dropped } + values: { dropped }, } )}{' '} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx index 5fb679818f0a7..1d23c0561ea40 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/TransactionFlyout/index.tsx @@ -12,7 +12,7 @@ import { EuiPortal, EuiSpacer, EuiTitle, - EuiHorizontalRule + EuiHorizontalRule, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; @@ -32,7 +32,7 @@ interface Props { } function TransactionPropertiesTable({ - transaction + transaction, }: { transaction: Transaction; }) { @@ -50,7 +50,7 @@ export function TransactionFlyout({ transaction: transactionDoc, onClose, errorCount = 0, - rootTransactionDuration + rootTransactionDuration, }: Props) { if (!transactionDoc) { return null; @@ -67,7 +67,7 @@ export function TransactionFlyout({ {i18n.translate( 'xpack.apm.transactionDetails.transFlyout.transactionDetailsTitle', { - defaultMessage: 'Transaction details' + defaultMessage: 'Transaction details', } )} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx index 426088f0bb36a..f0150e5a1b758 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallFlyout.tsx @@ -19,9 +19,11 @@ export const WaterfallFlyout: React.FC = ({ waterfallItemId, waterfall, location, - toggleFlyout + toggleFlyout, }) => { - const currentItem = waterfall.items.find(item => item.id === waterfallItemId); + const currentItem = waterfall.items.find( + (item) => item.id === waterfallItemId + ); if (!currentItem) { return null; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx index d8edcce46c2d7..1226db7e36c57 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/WaterfallItem.tsx @@ -39,10 +39,10 @@ const Container = styled.div` user-select: none; padding-top: ${px(units.half)}; padding-bottom: ${px(units.plus)}; - margin-right: ${props => px(props.timelineMargins.right)}; - margin-left: ${props => px(props.timelineMargins.left)}; + margin-right: ${(props) => px(props.timelineMargins.right)}; + margin-left: ${(props) => px(props.timelineMargins.left)}; border-top: 1px solid ${theme.euiColorLightShade}; - background-color: ${props => + background-color: ${(props) => props.isSelected ? theme.euiColorLightestShade : 'initial'}; cursor: pointer; @@ -56,7 +56,7 @@ const ItemBar = styled.div` position: relative; height: ${px(unit)}; min-width: 2px; - background-color: ${props => props.color}; + background-color: ${(props) => props.color}; `; const ItemText = styled.span` @@ -115,7 +115,7 @@ interface SpanActionToolTipProps { const SpanActionToolTip: React.FC = ({ item, - children + children, }) => { if (item?.docType === 'span') { return ( @@ -171,7 +171,7 @@ export function WaterfallItem({ color, isSelected, errorCount, - onClick + onClick, }: IWaterfallItemProps) { if (!totalDuration) { return null; @@ -185,7 +185,7 @@ export function WaterfallItem({ { values: { errorCount }, defaultMessage: - '{errorCount, plural, one {View 1 related error} other {View # related errors}}' + '{errorCount, plural, one {View 1 related error} other {View # related errors}}', } ); @@ -215,7 +215,7 @@ export function WaterfallItem({ query={{ kuery: encodeURIComponent( `${TRACE_ID} : "${item.doc.trace.id}" and transaction.id : "${item.doc.transaction.id}"` - ) + ), }} color="danger" style={{ textDecoration: 'none' }} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx index 329ad12c28ebd..78235594f40ec 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/index.tsx @@ -21,7 +21,7 @@ import { WaterfallFlyout } from './WaterfallFlyout'; import { WaterfallItem } from './WaterfallItem'; import { IWaterfall, - IWaterfallItem + IWaterfallItem, } from './waterfall_helpers/waterfall_helpers'; const Container = styled.div` @@ -34,12 +34,12 @@ const TIMELINE_MARGINS = { top: 40, left: 50, right: 50, - bottom: 0 + bottom: 0, }; const toggleFlyout = ({ item, - location + location, }: { item?: IWaterfallItem; location: Location; @@ -49,15 +49,15 @@ const toggleFlyout = ({ search: fromQuery({ ...toQuery(location.search), flyoutDetailTab: undefined, - waterfallItemId: item?.id - }) + waterfallItemId: item?.id, + }), }); }; const WaterfallItemsContainer = styled.div<{ paddingTop: number; }>` - padding-top: ${props => px(props.paddingTop)}; + padding-top: ${(props) => px(props.paddingTop)}; `; interface Props { @@ -71,7 +71,7 @@ export const Waterfall: React.FC = ({ waterfall, exceedsMax, waterfallItemId, - location + location, }) => { const itemContainerHeight = 58; // TODO: This is a nasty way to calculate the height of the svg element. A better approach should be found const waterfallHeight = itemContainerHeight * waterfall.items.length; @@ -110,7 +110,7 @@ export const Waterfall: React.FC = ({ iconType="alert" title={i18n.translate('xpack.apm.waterfall.exceedsMax', { defaultMessage: - 'Number of items in this trace exceed what is displayed' + 'Number of items in this trace exceed what is displayed', })} /> )} diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts index 75304932ed2ba..c3f334d8e46ed 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.test.ts @@ -13,7 +13,7 @@ import { getWaterfall, IWaterfallItem, IWaterfallTransaction, - IWaterfallError + IWaterfallError, } from './waterfall_helpers'; import { APMError } from '../../../../../../../../typings/es_schemas/ui/apm_error'; @@ -27,9 +27,9 @@ describe('waterfall_helpers', () => { transaction: { duration: { us: 49660 }, name: 'GET /api', - id: 'myTransactionId1' + id: 'myTransactionId1', }, - timestamp: { us: 1549324795784006 } + timestamp: { us: 1549324795784006 }, } as Transaction, { parent: { id: 'mySpanIdA' }, @@ -41,8 +41,8 @@ describe('waterfall_helpers', () => { span: { duration: { us: 481 }, name: 'SELECT FROM products', - id: 'mySpanIdB' - } + id: 'mySpanIdB', + }, } as Span, { parent: { id: 'myTransactionId2' }, @@ -53,9 +53,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 6161 }, name: 'Api::ProductsController#index', - id: 'mySpanIdA' + id: 'mySpanIdA', }, - timestamp: { us: 1549324795824504 } + timestamp: { us: 1549324795824504 }, } as Span, { parent: { id: 'mySpanIdA' }, @@ -66,9 +66,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 532 }, name: 'SELECT FROM product', - id: 'mySpanIdC' + id: 'mySpanIdC', }, - timestamp: { us: 1549324795827905 } + timestamp: { us: 1549324795827905 }, } as Span, { parent: { id: 'myTransactionId1' }, @@ -79,9 +79,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 47557 }, name: 'GET opbeans-ruby:3000/api/products', - id: 'mySpanIdD' + id: 'mySpanIdD', }, - timestamp: { us: 1549324795785760 } + timestamp: { us: 1549324795785760 }, } as Span, ({ parent: { id: 'mySpanIdD' }, @@ -96,12 +96,12 @@ describe('waterfall_helpers', () => { agent: { domInteractive: 382, domComplete: 383, - timeToFirstByte: 14 - } - } + timeToFirstByte: 14, + }, + }, }, - timestamp: { us: 1549324795823304 } - } as unknown) as Transaction + timestamp: { us: 1549324795823304 }, + } as unknown) as Transaction, ]; const errorDocs = [ ({ @@ -114,27 +114,27 @@ describe('waterfall_helpers', () => { id: 'error1', grouping_key: 'errorGroupingKey1', log: { - message: 'error message' - } + message: 'error message', + }, }, service: { name: 'opbeans-ruby' }, agent: { name: 'ruby', - version: '2' - } - } as unknown) as APMError + version: '2', + }, + } as unknown) as APMError, ]; it('should return full waterfall', () => { const entryTransactionId = 'myTransactionId1'; const errorsPerTransaction = { myTransactionId1: 2, - myTransactionId2: 3 + myTransactionId2: 3, }; const waterfall = getWaterfall( { trace: { items: hits, errorDocs, exceedsMax: false }, - errorsPerTransaction + errorsPerTransaction, }, entryTransactionId ); @@ -150,12 +150,12 @@ describe('waterfall_helpers', () => { const entryTransactionId = 'myTransactionId2'; const errorsPerTransaction = { myTransactionId1: 2, - myTransactionId2: 3 + myTransactionId2: 3, }; const waterfall = getWaterfall( { trace: { items: hits, errorDocs, exceedsMax: false }, - errorsPerTransaction + errorsPerTransaction, }, entryTransactionId ); @@ -175,9 +175,9 @@ describe('waterfall_helpers', () => { transaction: { duration: { us: 49660 }, name: 'GET /api', - id: 'myTransactionId1' + id: 'myTransactionId1', }, - timestamp: { us: 1549324795784006 } + timestamp: { us: 1549324795784006 }, } as Transaction, { parent: { id: 'mySpanIdD' }, @@ -189,9 +189,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 481 }, name: 'SELECT FROM products', - id: 'mySpanIdB' + id: 'mySpanIdB', }, - child: { id: ['mySpanIdA', 'mySpanIdC'] } + child: { id: ['mySpanIdA', 'mySpanIdC'] }, } as Span, { parent: { id: 'mySpanIdD' }, @@ -202,9 +202,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 6161 }, name: 'Api::ProductsController#index', - id: 'mySpanIdA' + id: 'mySpanIdA', }, - timestamp: { us: 1549324795824504 } + timestamp: { us: 1549324795824504 }, } as Span, { parent: { id: 'mySpanIdD' }, @@ -215,9 +215,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 532 }, name: 'SELECT FROM product', - id: 'mySpanIdC' + id: 'mySpanIdC', }, - timestamp: { us: 1549324795827905 } + timestamp: { us: 1549324795827905 }, } as Span, { parent: { id: 'myTransactionId1' }, @@ -228,43 +228,43 @@ describe('waterfall_helpers', () => { span: { duration: { us: 47557 }, name: 'GET opbeans-ruby:3000/api/products', - id: 'mySpanIdD' + id: 'mySpanIdD', }, - timestamp: { us: 1549324795785760 } - } as Span + timestamp: { us: 1549324795785760 }, + } as Span, ]; const entryTransactionId = 'myTransactionId1'; const waterfall = getWaterfall( { trace: { items: traceItems, errorDocs: [], exceedsMax: false }, - errorsPerTransaction: {} + errorsPerTransaction: {}, }, entryTransactionId ); const getIdAndParentId = (item: IWaterfallItem) => ({ id: item.id, - parentId: item.parent?.id + parentId: item.parent?.id, }); expect(waterfall.items.length).toBe(5); expect(getIdAndParentId(waterfall.items[0])).toEqual({ id: 'myTransactionId1', - parentId: undefined + parentId: undefined, }); expect(getIdAndParentId(waterfall.items[1])).toEqual({ id: 'mySpanIdD', - parentId: 'myTransactionId1' + parentId: 'myTransactionId1', }); expect(getIdAndParentId(waterfall.items[2])).toEqual({ id: 'mySpanIdB', - parentId: 'mySpanIdD' + parentId: 'mySpanIdD', }); expect(getIdAndParentId(waterfall.items[3])).toEqual({ id: 'mySpanIdA', - parentId: 'mySpanIdB' + parentId: 'mySpanIdB', }); expect(getIdAndParentId(waterfall.items[4])).toEqual({ id: 'mySpanIdC', - parentId: 'mySpanIdB' + parentId: 'mySpanIdB', }); expect(waterfall.errorItems.length).toBe(0); expect(waterfall.errorsCount).toEqual(0); @@ -278,9 +278,9 @@ describe('waterfall_helpers', () => { transaction: { duration: { us: 49660 }, name: 'GET /api', - id: 'myTransactionId1' + id: 'myTransactionId1', }, - timestamp: { us: 1549324795784006 } + timestamp: { us: 1549324795784006 }, } as Transaction, { parent: { id: 'mySpanIdD' }, @@ -292,9 +292,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 481 }, name: 'SELECT FROM products', - id: 'mySpanIdB' + id: 'mySpanIdB', }, - child: { id: ['incorrectId', 'mySpanIdC'] } + child: { id: ['incorrectId', 'mySpanIdC'] }, } as Span, { parent: { id: 'mySpanIdD' }, @@ -305,9 +305,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 6161 }, name: 'Api::ProductsController#index', - id: 'mySpanIdA' + id: 'mySpanIdA', }, - timestamp: { us: 1549324795824504 } + timestamp: { us: 1549324795824504 }, } as Span, { parent: { id: 'mySpanIdD' }, @@ -318,9 +318,9 @@ describe('waterfall_helpers', () => { span: { duration: { us: 532 }, name: 'SELECT FROM product', - id: 'mySpanIdC' + id: 'mySpanIdC', }, - timestamp: { us: 1549324795827905 } + timestamp: { us: 1549324795827905 }, } as Span, { parent: { id: 'myTransactionId1' }, @@ -331,43 +331,43 @@ describe('waterfall_helpers', () => { span: { duration: { us: 47557 }, name: 'GET opbeans-ruby:3000/api/products', - id: 'mySpanIdD' + id: 'mySpanIdD', }, - timestamp: { us: 1549324795785760 } - } as Span + timestamp: { us: 1549324795785760 }, + } as Span, ]; const entryTransactionId = 'myTransactionId1'; const waterfall = getWaterfall( { trace: { items: traceItems, errorDocs: [], exceedsMax: false }, - errorsPerTransaction: {} + errorsPerTransaction: {}, }, entryTransactionId ); const getIdAndParentId = (item: IWaterfallItem) => ({ id: item.id, - parentId: item.parent?.id + parentId: item.parent?.id, }); expect(waterfall.items.length).toBe(5); expect(getIdAndParentId(waterfall.items[0])).toEqual({ id: 'myTransactionId1', - parentId: undefined + parentId: undefined, }); expect(getIdAndParentId(waterfall.items[1])).toEqual({ id: 'mySpanIdD', - parentId: 'myTransactionId1' + parentId: 'myTransactionId1', }); expect(getIdAndParentId(waterfall.items[2])).toEqual({ id: 'mySpanIdA', - parentId: 'mySpanIdD' + parentId: 'mySpanIdD', }); expect(getIdAndParentId(waterfall.items[3])).toEqual({ id: 'mySpanIdB', - parentId: 'mySpanIdD' + parentId: 'mySpanIdD', }); expect(getIdAndParentId(waterfall.items[4])).toEqual({ id: 'mySpanIdC', - parentId: 'mySpanIdB' + parentId: 'mySpanIdB', }); expect(waterfall.errorItems.length).toBe(0); expect(waterfall.errorsCount).toEqual(0); @@ -383,19 +383,19 @@ describe('waterfall_helpers', () => { parent: { id: 'c' }, service: { name: 'opbeans-java' }, transaction: { - id: 'c' + id: 'c', }, timestamp: { us: 1536763736371000 }, span: { id: 'd', - name: 'SELECT' - } + name: 'SELECT', + }, } as Span, id: 'd', parentId: 'c', duration: 210, offset: 0, - skew: 0 + skew: 0, }, { docType: 'span', @@ -403,19 +403,19 @@ describe('waterfall_helpers', () => { parent: { id: 'a' }, service: { name: 'opbeans-java' }, transaction: { - id: 'a' + id: 'a', }, timestamp: { us: 1536763736368000 }, span: { id: 'b', - name: 'GET [0:0:0:0:0:0:0:1]' - } + name: 'GET [0:0:0:0:0:0:0:1]', + }, } as Span, id: 'b', parentId: 'a', duration: 4694, offset: 0, - skew: 0 + skew: 0, }, { docType: 'span', @@ -423,19 +423,19 @@ describe('waterfall_helpers', () => { parent: { id: 'a' }, service: { name: 'opbeans-java' }, transaction: { - id: 'a' + id: 'a', }, timestamp: { us: 1536763736367000 }, span: { id: 'b2', - name: 'GET [0:0:0:0:0:0:0:1]' - } + name: 'GET [0:0:0:0:0:0:0:1]', + }, } as Span, id: 'b2', parentId: 'a', duration: 4694, offset: 0, - skew: 0 + skew: 0, }, { docType: 'transaction', @@ -443,13 +443,13 @@ describe('waterfall_helpers', () => { parent: { id: 'b' }, service: { name: 'opbeans-java' }, timestamp: { us: 1536763736369000 }, - transaction: { id: 'c', name: 'APIRestController#productsRemote' } + transaction: { id: 'c', name: 'APIRestController#productsRemote' }, } as Transaction, id: 'c', parentId: 'b', duration: 3581, offset: 0, - skew: 0 + skew: 0, }, { docType: 'transaction', @@ -458,17 +458,17 @@ describe('waterfall_helpers', () => { timestamp: { us: 1536763736366000 }, transaction: { id: 'a', - name: 'APIRestController#products' - } + name: 'APIRestController#products', + }, } as Transaction, id: 'a', duration: 9480, offset: 0, - skew: 0 - } + skew: 0, + }, ]; - const childrenByParentId = groupBy(items, hit => + const childrenByParentId = groupBy(items, (hit) => hit.parentId ? hit.parentId : 'root' ); const entryTransactionItem = childrenByParentId @@ -486,8 +486,8 @@ describe('waterfall_helpers', () => { id: 'a', doc: ({ transaction: { id: 'a' }, - timestamp: { us: 10 } - } as unknown) as Transaction + timestamp: { us: 10 }, + } as unknown) as Transaction, } as IWaterfallItem, { docType: 'span', @@ -495,14 +495,14 @@ describe('waterfall_helpers', () => { parentId: 'a', doc: ({ span: { - id: 'b' + id: 'b', }, parent: { id: 'a' }, - timestamp: { us: 20 } - } as unknown) as Span - } as IWaterfallItem + timestamp: { us: 20 }, + } as unknown) as Span, + } as IWaterfallItem, ]; - const childrenByParentId = groupBy(items, hit => + const childrenByParentId = groupBy(items, (hit) => hit.parentId ? hit.parentId : 'root' ); const entryTransactionItem = childrenByParentId @@ -518,18 +518,18 @@ describe('waterfall_helpers', () => { const child = { docType: 'transaction', doc: { - timestamp: { us: 0 } + timestamp: { us: 0 }, }, - duration: 50 + duration: 50, } as IWaterfallItem; const parent = { docType: 'transaction', doc: { - timestamp: { us: 100 } + timestamp: { us: 100 }, }, duration: 100, - skew: 5 + skew: 5, } as IWaterfallItem; expect(getClockSkew(child, parent)).toBe(130); @@ -539,18 +539,18 @@ describe('waterfall_helpers', () => { const child = { docType: 'transaction', doc: { - timestamp: { us: 250 } + timestamp: { us: 250 }, }, - duration: 50 + duration: 50, } as IWaterfallItem; const parent = { docType: 'transaction', doc: { - timestamp: { us: 100 } + timestamp: { us: 100 }, }, duration: 100, - skew: 5 + skew: 5, } as IWaterfallItem; expect(getClockSkew(child, parent)).toBe(0); @@ -560,18 +560,18 @@ describe('waterfall_helpers', () => { const child = { docType: 'transaction', doc: { - timestamp: { us: 150 } + timestamp: { us: 150 }, }, - duration: 50 + duration: 50, } as IWaterfallItem; const parent = { docType: 'transaction', doc: { - timestamp: { us: 100 } + timestamp: { us: 100 }, }, duration: 100, - skew: 5 + skew: 5, } as IWaterfallItem; expect(getClockSkew(child, parent)).toBe(0); @@ -579,16 +579,16 @@ describe('waterfall_helpers', () => { it('should return parent skew for spans', () => { const child = { - docType: 'span' + docType: 'span', } as IWaterfallItem; const parent = { docType: 'span', doc: { - timestamp: { us: 100 } + timestamp: { us: 100 }, }, duration: 100, - skew: 5 + skew: 5, } as IWaterfallItem; expect(getClockSkew(child, parent)).toBe(5); @@ -596,16 +596,16 @@ describe('waterfall_helpers', () => { it('should return parent skew for errors', () => { const child = { - docType: 'error' + docType: 'error', } as IWaterfallError; const parent = { docType: 'transaction', doc: { - timestamp: { us: 100 } + timestamp: { us: 100 }, }, duration: 100, - skew: 5 + skew: 5, } as IWaterfallItem; expect(getClockSkew(child, parent)).toBe(5); @@ -613,7 +613,7 @@ describe('waterfall_helpers', () => { it('should handle missing parent', () => { const child = { - docType: 'transaction' + docType: 'transaction', } as IWaterfallItem; const parent = undefined; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts index e15cf2df38c5f..441a51bcba646 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/Waterfall/waterfall_helpers/waterfall_helpers.ts @@ -13,7 +13,7 @@ import { sortBy, sum, uniq, - zipObject + zipObject, } from 'lodash'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { TraceAPIResponse } from '../../../../../../../../server/lib/traces/get_trace'; @@ -84,7 +84,7 @@ function getTransactionItem(transaction: Transaction): IWaterfallTransaction { parentId: transaction.parent?.id, duration: transaction.transaction.duration.us, offset: 0, - skew: 0 + skew: 0, }; } @@ -96,7 +96,7 @@ function getSpanItem(span: Span): IWaterfallSpan { parentId: span.parent?.id, duration: span.span.duration.us, offset: 0, - skew: 0 + skew: 0, }; } @@ -107,7 +107,7 @@ function getErrorItem( ): IWaterfallError { const entryTimestamp = entryWaterfallTransaction?.doc.timestamp.us ?? 0; const parent = items.find( - waterfallItem => waterfallItem.id === error.parent?.id + (waterfallItem) => waterfallItem.id === error.parent?.id ); const errorItem: IWaterfallError = { docType: 'error', @@ -117,12 +117,12 @@ function getErrorItem( parentId: parent?.id, offset: error.timestamp.us - entryTimestamp, skew: 0, - duration: 0 + duration: 0, }; return { ...errorItem, - skew: getClockSkew(errorItem, parent) + skew: getClockSkew(errorItem, parent), }; } @@ -186,7 +186,7 @@ export function getOrderedWaterfallItems( item.skew = getClockSkew(item, parentItem); const deepChildren = flatten( - children.map(child => getSortedChildren(child, item)) + children.map((child) => getSortedChildren(child, item)) ); return [item, ...deepChildren]; } @@ -204,7 +204,7 @@ function getRootTransaction(childrenByParentId: IWaterfallGroup) { export type IServiceColors = Record; function getServiceColors(waterfallItems: IWaterfallItem[]) { - const services = uniq(waterfallItems.map(item => item.doc.service.name)); + const services = uniq(waterfallItems.map((item) => item.doc.service.name)); const assignedColors = [ theme.euiColorVis1, @@ -213,7 +213,7 @@ function getServiceColors(waterfallItems: IWaterfallItem[]) { theme.euiColorVis2, theme.euiColorVis6, theme.euiColorVis7, - theme.euiColorVis5 + theme.euiColorVis5, ]; return zipObject(services, assignedColors) as IServiceColors; @@ -221,12 +221,12 @@ function getServiceColors(waterfallItems: IWaterfallItem[]) { const getWaterfallDuration = (waterfallItems: IWaterfallItem[]) => Math.max( - ...waterfallItems.map(item => item.offset + item.skew + item.duration), + ...waterfallItems.map((item) => item.offset + item.skew + item.duration), 0 ); const getWaterfallItems = (items: TraceAPIResponse['trace']['items']) => - items.map(item => { + items.map((item) => { const docType = item.processor.event; switch (docType) { case 'span': @@ -240,10 +240,10 @@ function reparentSpans(waterfallItems: IWaterfallItem[]) { // find children that needs to be re-parented and map them to their correct parent id const childIdToParentIdMapping = Object.fromEntries( flatten( - waterfallItems.map(waterfallItem => { + waterfallItems.map((waterfallItem) => { if (waterfallItem.docType === 'span') { const childIds = waterfallItem.doc.child?.id ?? []; - return childIds.map(id => [id, waterfallItem.id]); + return childIds.map((id) => [id, waterfallItem.id]); } return []; }) @@ -251,12 +251,12 @@ function reparentSpans(waterfallItems: IWaterfallItem[]) { ); // update parent id for children that needs it or return unchanged - return waterfallItems.map(waterfallItem => { + return waterfallItems.map((waterfallItem) => { const newParentId = childIdToParentIdMapping[waterfallItem.id]; if (newParentId) { return { ...waterfallItem, - parentId: newParentId + parentId: newParentId, }; } @@ -265,14 +265,14 @@ function reparentSpans(waterfallItems: IWaterfallItem[]) { } const getChildrenGroupedByParentId = (waterfallItems: IWaterfallItem[]) => - groupBy(waterfallItems, item => (item.parentId ? item.parentId : ROOT_ID)); + groupBy(waterfallItems, (item) => (item.parentId ? item.parentId : ROOT_ID)); const getEntryWaterfallTransaction = ( entryTransactionId: string, waterfallItems: IWaterfallItem[] ): IWaterfallTransaction | undefined => waterfallItems.find( - item => item.docType === 'transaction' && item.id === entryTransactionId + (item) => item.docType === 'transaction' && item.id === entryTransactionId ) as IWaterfallTransaction; function isInEntryTransaction( @@ -295,7 +295,7 @@ function getWaterfallErrors( items: IWaterfallItem[], entryWaterfallTransaction?: IWaterfallTransaction ) { - const errorItems = errorDocs.map(errorDoc => + const errorItems = errorDocs.map((errorDoc) => getErrorItem(errorDoc, items, entryWaterfallTransaction) ); if (!entryWaterfallTransaction) { @@ -308,7 +308,7 @@ function getWaterfallErrors( }, new Map() ); - return errorItems.filter(errorItem => + return errorItems.filter((errorItem) => isInEntryTransaction( parentIdLookup, entryWaterfallTransaction?.id, @@ -328,7 +328,7 @@ export function getWaterfall( errorsPerTransaction, errorsCount: sum(Object.values(errorsPerTransaction)), serviceColors: {}, - errorItems: [] + errorItems: [], }; } @@ -367,6 +367,6 @@ export function getWaterfall( errorsPerTransaction, errorsCount: errorItems.length, serviceColors, - errorItems + errorItems, }; } diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx index 87710fb9b8d96..69cb091e76880 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/WaterfallContainer.stories.tsx @@ -15,7 +15,7 @@ import { simpleTrace, traceWithErrors, traceChildStartBeforeParent, - inferredSpans + inferredSpans, } from './waterfallContainer.stories.data'; import { getWaterfall } from './Waterfall/waterfall_helpers/waterfall_helpers'; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/index.tsx index 77be5c999f7c3..6fd139b470ce1 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/index.tsx @@ -22,7 +22,7 @@ export function WaterfallContainer({ location, urlParams, waterfall, - exceedsMax + exceedsMax, }: Props) { if (!waterfall) { return null; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts index 6f4a0629c7bc5..f78fe39120d8d 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/WaterfallContainer/waterfallContainer.stories.data.ts @@ -11,7 +11,7 @@ export const location = { pathname: '/services/opbeans-go/transactions/view', search: '?rangeFrom=now-24h&rangeTo=now&refreshPaused=true&refreshInterval=0&kuery=service.name%253A%2520%2522opbeans-java%2522%2520or%2520service.name%2520%253A%2520%2522opbeans-go%2522&traceId=513d33fafe99bbe6134749310c9b5322&transactionId=975c8d5bfd1dd20b&transactionName=GET%20%2Fapi%2Forders&transactionType=request', - hash: '' + hash: '', } as Location; export const urlParams = { @@ -28,7 +28,7 @@ export const urlParams = { transactionName: 'GET /api/orders', transactionType: 'request', processorEvent: 'transaction', - serviceName: 'opbeans-go' + serviceName: 'opbeans-go', } as IUrlParams; export const simpleTrace = { @@ -36,36 +36,37 @@ export const simpleTrace = { items: [ { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 46 - } + value: 46, + }, }, source: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: '172.19.0.9', - full: 'http://172.19.0.9:3000/api/orders' + full: 'http://172.19.0.9:3000/api/orders', }, observer: { hostname: 'f37f48d8b60b', @@ -73,40 +74,40 @@ export const simpleTrace = { ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, http: { request: { @@ -114,210 +115,211 @@ export const simpleTrace = { Accept: ['*/*'], 'User-Agent': ['Python/3.7 aiohttp/3.3.2'], Host: ['172.19.0.9:3000'], - 'Accept-Encoding': ['gzip, deflate'] + 'Accept-Encoding': ['gzip, deflate'], }, method: 'get', socket: { encrypted: false, - remote_address: '172.19.0.13' + remote_address: '172.19.0.13', }, body: { - original: '[REDACTED]' - } + original: '[REDACTED]', + }, }, response: { headers: { 'Transfer-Encoding': ['chunked'], Date: ['Mon, 23 Mar 2020 15:04:28 GMT'], - 'Content-Type': ['application/json;charset=ISO-8859-1'] + 'Content-Type': ['application/json;charset=ISO-8859-1'], }, status_code: 200, finished: true, - headers_sent: true + headers_sent: true, }, - version: '1.1' + version: '1.1', }, client: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, transaction: { duration: { - us: 18842 + us: 18842, }, result: 'HTTP 2xx', name: 'DispatcherServlet#doGet', id: '49809ad3c26adf74', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, user_agent: { original: 'Python/3.7 aiohttp/3.3.2', name: 'Other', device: { - name: 'Other' - } + name: 'Other', + }, }, timestamp: { - us: 1584975868785000 - } + us: 1584975868785000, + }, }, { parent: { - id: 'fc107f7b556eb49b' + id: 'fc107f7b556eb49b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { name: 'gin', - version: 'v1.4.0' + version: 'v1.4.0', }, name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { duration: { - us: 16597 + us: 16597, }, result: 'HTTP 2xx', name: 'GET /api/orders', id: '975c8d5bfd1dd20b', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, timestamp: { - us: 1584975868787052 - } + us: 1584975868787052, + }, }, { parent: { - id: 'daae24d83c269918' + id: 'daae24d83c269918', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, timestamp: { - us: 1584975868788603 + us: 1584975868788603, }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { result: 'HTTP 2xx', duration: { - us: 14648 + us: 14648, }, name: 'GET opbeans.views.orders', span_count: { dropped: 0, - started: 1 + started: 1, }, id: '6fb0ff7365b87298', type: 'request', - sampled: true - } + sampled: true, + }, }, { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, parent: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 44 - } + value: 44, + }, }, destination: { address: 'opbeans-go', - port: 3000 + port: 3000, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: 'f37f48d8b60b', @@ -325,54 +327,54 @@ export const simpleTrace = { type: 'apm-server', ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, connection: { hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}" + "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, timestamp: { - us: 1584975868785273 + us: 1584975868785273, }, span: { duration: { - us: 17530 + us: 17530, }, subtype: 'http', name: 'GET opbeans-go', @@ -380,134 +382,135 @@ export const simpleTrace = { service: { resource: 'opbeans-go:3000', name: 'http://opbeans-go:3000', - type: 'external' - } + type: 'external', + }, }, http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-go:3000/api/orders' - } + original: 'http://opbeans-go:3000/api/orders', + }, }, id: 'fc107f7b556eb49b', - type: 'external' - } + type: 'external', + }, }, { parent: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, timestamp: { - us: 1584975868787174 + us: 1584975868787174, }, span: { duration: { - us: 16250 + us: 16250, }, subtype: 'http', destination: { service: { resource: 'opbeans-python:3000', name: 'http://opbeans-python:3000', - type: 'external' - } + type: 'external', + }, }, name: 'GET opbeans-python:3000', http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-python:3000/api/orders' - } + original: 'http://opbeans-python:3000/api/orders', + }, }, id: 'daae24d83c269918', - type: 'external' - } + type: 'external', + }, }, { container: { - id: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + id: + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, parent: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, timestamp: { - us: 1584975868790080 + us: 1584975868790080, }, span: { duration: { - us: 2519 + us: 2519, }, subtype: 'postgresql', name: 'SELECT FROM opbeans_order', @@ -515,8 +518,8 @@ export const simpleTrace = { service: { resource: 'postgresql', name: 'postgresql', - type: 'db' - } + type: 'db', + }, }, action: 'query', id: 'c9407abb4d08ead1', @@ -525,15 +528,15 @@ export const simpleTrace = { db: { statement: 'SELECT "opbeans_order"."id", "opbeans_order"."customer_id", "opbeans_customer"."full_name", "opbeans_order"."created_at" FROM "opbeans_order" INNER JOIN "opbeans_customer" ON ("opbeans_order"."customer_id" = "opbeans_customer"."id") LIMIT 1000', - type: 'sql' - } - } - } + type: 'sql', + }, + }, + }, ], exceedsMax: false, - errorDocs: [] + errorDocs: [], }, - errorsPerTransaction: {} + errorsPerTransaction: {}, }; export const traceWithErrors = { @@ -541,36 +544,37 @@ export const traceWithErrors = { items: [ { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 46 - } + value: 46, + }, }, source: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: '172.19.0.9', - full: 'http://172.19.0.9:3000/api/orders' + full: 'http://172.19.0.9:3000/api/orders', }, observer: { hostname: 'f37f48d8b60b', @@ -578,40 +582,40 @@ export const traceWithErrors = { ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, http: { request: { @@ -619,210 +623,211 @@ export const traceWithErrors = { Accept: ['*/*'], 'User-Agent': ['Python/3.7 aiohttp/3.3.2'], Host: ['172.19.0.9:3000'], - 'Accept-Encoding': ['gzip, deflate'] + 'Accept-Encoding': ['gzip, deflate'], }, method: 'get', socket: { encrypted: false, - remote_address: '172.19.0.13' + remote_address: '172.19.0.13', }, body: { - original: '[REDACTED]' - } + original: '[REDACTED]', + }, }, response: { headers: { 'Transfer-Encoding': ['chunked'], Date: ['Mon, 23 Mar 2020 15:04:28 GMT'], - 'Content-Type': ['application/json;charset=ISO-8859-1'] + 'Content-Type': ['application/json;charset=ISO-8859-1'], }, status_code: 200, finished: true, - headers_sent: true + headers_sent: true, }, - version: '1.1' + version: '1.1', }, client: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, transaction: { duration: { - us: 18842 + us: 18842, }, result: 'HTTP 2xx', name: 'DispatcherServlet#doGet', id: '49809ad3c26adf74', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, user_agent: { original: 'Python/3.7 aiohttp/3.3.2', name: 'Other', device: { - name: 'Other' - } + name: 'Other', + }, }, timestamp: { - us: 1584975868785000 - } + us: 1584975868785000, + }, }, { parent: { - id: 'fc107f7b556eb49b' + id: 'fc107f7b556eb49b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { name: 'gin', - version: 'v1.4.0' + version: 'v1.4.0', }, name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { duration: { - us: 16597 + us: 16597, }, result: 'HTTP 2xx', name: 'GET /api/orders', id: '975c8d5bfd1dd20b', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, timestamp: { - us: 1584975868787052 - } + us: 1584975868787052, + }, }, { parent: { - id: 'daae24d83c269918' + id: 'daae24d83c269918', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, timestamp: { - us: 1584975868788603 + us: 1584975868788603, }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { result: 'HTTP 2xx', duration: { - us: 14648 + us: 14648, }, name: 'GET opbeans.views.orders', span_count: { dropped: 0, - started: 1 + started: 1, }, id: '6fb0ff7365b87298', type: 'request', - sampled: true - } + sampled: true, + }, }, { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, parent: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 44 - } + value: 44, + }, }, destination: { address: 'opbeans-go', - port: 3000 + port: 3000, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: 'f37f48d8b60b', @@ -830,54 +835,54 @@ export const traceWithErrors = { type: 'apm-server', ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, connection: { hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}" + "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, timestamp: { - us: 1584975868785273 + us: 1584975868785273, }, span: { duration: { - us: 17530 + us: 17530, }, subtype: 'http', name: 'GET opbeans-go', @@ -885,134 +890,135 @@ export const traceWithErrors = { service: { resource: 'opbeans-go:3000', name: 'http://opbeans-go:3000', - type: 'external' - } + type: 'external', + }, }, http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-go:3000/api/orders' - } + original: 'http://opbeans-go:3000/api/orders', + }, }, id: 'fc107f7b556eb49b', - type: 'external' - } + type: 'external', + }, }, { parent: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, timestamp: { - us: 1584975868787174 + us: 1584975868787174, }, span: { duration: { - us: 16250 + us: 16250, }, subtype: 'http', destination: { service: { resource: 'opbeans-python:3000', name: 'http://opbeans-python:3000', - type: 'external' - } + type: 'external', + }, }, name: 'GET opbeans-python:3000', http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-python:3000/api/orders' - } + original: 'http://opbeans-python:3000/api/orders', + }, }, id: 'daae24d83c269918', - type: 'external' - } + type: 'external', + }, }, { container: { - id: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + id: + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, parent: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, timestamp: { - us: 1584975868790080 + us: 1584975868790080, }, span: { duration: { - us: 2519 + us: 2519, }, subtype: 'postgresql', name: 'SELECT FROM opbeans_order', @@ -1020,8 +1026,8 @@ export const traceWithErrors = { service: { resource: 'postgresql', name: 'postgresql', - type: 'db' - } + type: 'db', + }, }, action: 'query', id: 'c9407abb4d08ead1', @@ -1030,115 +1036,115 @@ export const traceWithErrors = { db: { statement: 'SELECT "opbeans_order"."id", "opbeans_order"."customer_id", "opbeans_customer"."full_name", "opbeans_order"."created_at" FROM "opbeans_order" INNER JOIN "opbeans_customer" ON ("opbeans_order"."customer_id" = "opbeans_customer"."id") LIMIT 1000', - type: 'sql' - } - } - } + type: 'sql', + }, + }, + }, ], exceedsMax: false, errorDocs: [ { parent: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, error: { culprit: 'logrusMiddleware', log: { level: 'error', - message: 'GET //api/products (502)' + message: 'GET //api/products (502)', }, id: '1f3cb98206b5c54225cb7c8908a658da', - grouping_key: '4dba2ff58fe6c036a5dee2ce411e512a' + grouping_key: '4dba2ff58fe6c036a5dee2ce411e512a', }, processor: { name: 'error', - event: 'error' + event: 'error', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T16:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { id: '975c8d5bfd1dd20b', - sampled: false + sampled: false, }, timestamp: { - us: 1584975868787052 - } + us: 1584975868787052, + }, }, { parent: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, error: { culprit: 'logrusMiddleware', log: { level: 'error', - message: 'GET //api/products (502)' + message: 'GET //api/products (502)', }, id: '1f3cb98206b5c54225cb7c8908a658d2', - grouping_key: '4dba2ff58fe6c036a5dee2ce411e512a' + grouping_key: '4dba2ff58fe6c036a5dee2ce411e512a', }, processor: { name: 'error', - event: 'error' + event: 'error', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T16:04:28.790Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-python', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { id: '6fb0ff7365b87298', - sampled: false + sampled: false, }, timestamp: { - us: 1584975868790000 - } - } - ] + us: 1584975868790000, + }, + }, + ], }, errorsPerTransaction: { '975c8d5bfd1dd20b': 1, - '6fb0ff7365b87298': 1 - } + '6fb0ff7365b87298': 1, + }, }; export const traceChildStartBeforeParent = { @@ -1146,36 +1152,37 @@ export const traceChildStartBeforeParent = { items: [ { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 46 - } + value: 46, + }, }, source: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: '172.19.0.9', - full: 'http://172.19.0.9:3000/api/orders' + full: 'http://172.19.0.9:3000/api/orders', }, observer: { hostname: 'f37f48d8b60b', @@ -1183,40 +1190,40 @@ export const traceChildStartBeforeParent = { ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, http: { request: { @@ -1224,210 +1231,211 @@ export const traceChildStartBeforeParent = { Accept: ['*/*'], 'User-Agent': ['Python/3.7 aiohttp/3.3.2'], Host: ['172.19.0.9:3000'], - 'Accept-Encoding': ['gzip, deflate'] + 'Accept-Encoding': ['gzip, deflate'], }, method: 'get', socket: { encrypted: false, - remote_address: '172.19.0.13' + remote_address: '172.19.0.13', }, body: { - original: '[REDACTED]' - } + original: '[REDACTED]', + }, }, response: { headers: { 'Transfer-Encoding': ['chunked'], Date: ['Mon, 23 Mar 2020 15:04:28 GMT'], - 'Content-Type': ['application/json;charset=ISO-8859-1'] + 'Content-Type': ['application/json;charset=ISO-8859-1'], }, status_code: 200, finished: true, - headers_sent: true + headers_sent: true, }, - version: '1.1' + version: '1.1', }, client: { - ip: '172.19.0.13' + ip: '172.19.0.13', }, transaction: { duration: { - us: 18842 + us: 18842, }, result: 'HTTP 2xx', name: 'DispatcherServlet#doGet', id: '49809ad3c26adf74', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, user_agent: { original: 'Python/3.7 aiohttp/3.3.2', name: 'Other', device: { - name: 'Other' - } + name: 'Other', + }, }, timestamp: { - us: 1584975868785000 - } + us: 1584975868785000, + }, }, { parent: { - id: 'fc107f7b556eb49b' + id: 'fc107f7b556eb49b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', framework: { name: 'gin', - version: 'v1.4.0' + version: 'v1.4.0', }, name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { duration: { - us: 16597 + us: 16597, }, result: 'HTTP 2xx', name: 'GET /api/orders', id: '975c8d5bfd1dd20b', span_count: { dropped: 0, - started: 1 + started: 1, }, type: 'request', - sampled: true + sampled: true, }, timestamp: { - us: 1584975868787052 - } + us: 1584975868787052, + }, }, { parent: { - id: 'daae24d83c269918' + id: 'daae24d83c269918', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, timestamp: { - us: 1584975868780000 + us: 1584975868780000, }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/orders', scheme: 'http', port: 3000, domain: 'opbeans-go', - full: 'http://opbeans-go:3000/api/orders' + full: 'http://opbeans-go:3000/api/orders', }, '@timestamp': '2020-03-23T15:04:28.788Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { result: 'HTTP 2xx', duration: { - us: 1464 + us: 1464, }, name: 'I started before my parent 😰', span_count: { dropped: 0, - started: 1 + started: 1, }, id: '6fb0ff7365b87298', type: 'request', - sampled: true - } + sampled: true, + }, }, { container: { - id: '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + id: + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, parent: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, process: { pid: 6, title: '/usr/lib/jvm/java-10-openjdk-amd64/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '99ce8403-5875-4945-b074-d37dc10563eb', - version: '1.14.1-SNAPSHOT' + version: '1.14.1-SNAPSHOT', }, internal: { sampler: { - value: 44 - } + value: 44, + }, }, destination: { address: 'opbeans-go', - port: 3000 + port: 3000, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: 'f37f48d8b60b', @@ -1435,54 +1443,54 @@ export const traceChildStartBeforeParent = { type: 'apm-server', ephemeral_id: '6ed88f14-170e-478d-a4f5-ea5e7f4b16b9', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.785Z', ecs: { - version: '1.4.0' + version: '1.4.0', }, service: { node: { name: - '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e' + '4cf84d094553201997ddb7fea344b7c6ef18dcb8233eba39278946ee8449794e', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, language: { name: 'Java', - version: '10.0.2' + version: '10.0.2', }, - version: 'None' + version: 'None', }, host: { hostname: '4cf84d094553', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.19.0.9', name: '4cf84d094553', - architecture: 'amd64' + architecture: 'amd64', }, connection: { hash: - "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}" + "{service.environment:'production'}/{service.name:'opbeans-java'}/{span.subtype:'http'}/{destination.address:'opbeans-go'}/{span.type:'external'}", }, transaction: { - id: '49809ad3c26adf74' + id: '49809ad3c26adf74', }, timestamp: { - us: 1584975868785273 + us: 1584975868785273, }, span: { duration: { - us: 17530 + us: 17530, }, subtype: 'http', name: 'GET opbeans-go', @@ -1490,134 +1498,135 @@ export const traceChildStartBeforeParent = { service: { resource: 'opbeans-go:3000', name: 'http://opbeans-go:3000', - type: 'external' - } + type: 'external', + }, }, http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-go:3000/api/orders' - } + original: 'http://opbeans-go:3000/api/orders', + }, }, id: 'fc107f7b556eb49b', - type: 'external' - } + type: 'external', + }, }, { parent: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, agent: { name: 'go', - version: '1.7.2' + version: '1.7.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.787Z', service: { node: { name: - 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29' + 'e948a08b8f5efe99b5da01f50da48c7d8aee3bbf4701f3da85ebe760c2ffef29', }, environment: 'production', name: 'opbeans-go', runtime: { name: 'gc', - version: 'go1.14.1' + version: 'go1.14.1', }, language: { name: 'go', - version: 'go1.14.1' + version: 'go1.14.1', }, - version: 'None' + version: 'None', }, transaction: { - id: '975c8d5bfd1dd20b' + id: '975c8d5bfd1dd20b', }, timestamp: { - us: 1584975868787174 + us: 1584975868787174, }, span: { duration: { - us: 16250 + us: 16250, }, subtype: 'http', destination: { service: { resource: 'opbeans-python:3000', name: 'http://opbeans-python:3000', - type: 'external' - } + type: 'external', + }, }, name: 'I am his 👇🏻 parent 😡', http: { response: { - status_code: 200 + status_code: 200, }, url: { - original: 'http://opbeans-python:3000/api/orders' - } + original: 'http://opbeans-python:3000/api/orders', + }, }, id: 'daae24d83c269918', - type: 'external' - } + type: 'external', + }, }, { container: { - id: 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + id: + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, parent: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, agent: { name: 'python', - version: '5.5.2' + version: '5.5.2', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, trace: { - id: '513d33fafe99bbe6134749310c9b5322' + id: '513d33fafe99bbe6134749310c9b5322', }, '@timestamp': '2020-03-23T15:04:28.790Z', service: { node: { name: - 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51' + 'a636915f1f6eec81ab44342b13a3ea9597ef03a24391e4e55f34ae2e20b30f51', }, environment: 'production', framework: { name: 'django', - version: '2.1.13' + version: '2.1.13', }, name: 'opbeans-python', runtime: { name: 'CPython', - version: '3.6.10' + version: '3.6.10', }, language: { name: 'python', - version: '3.6.10' + version: '3.6.10', }, - version: 'None' + version: 'None', }, transaction: { - id: '6fb0ff7365b87298' + id: '6fb0ff7365b87298', }, timestamp: { - us: 1584975868781000 + us: 1584975868781000, }, span: { duration: { - us: 2519 + us: 2519, }, subtype: 'postgresql', name: 'I am using my parents skew 😇', @@ -1625,8 +1634,8 @@ export const traceChildStartBeforeParent = { service: { resource: 'postgresql', name: 'postgresql', - type: 'db' - } + type: 'db', + }, }, action: 'query', id: 'c9407abb4d08ead1', @@ -1635,15 +1644,15 @@ export const traceChildStartBeforeParent = { db: { statement: 'SELECT "opbeans_order"."id", "opbeans_order"."customer_id", "opbeans_customer"."full_name", "opbeans_order"."created_at" FROM "opbeans_order" INNER JOIN "opbeans_customer" ON ("opbeans_order"."customer_id" = "opbeans_customer"."id") LIMIT 1000', - type: 'sql' - } - } - } + type: 'sql', + }, + }, + }, ], exceedsMax: false, - errorDocs: [] + errorDocs: [], }, - errorsPerTransaction: {} + errorsPerTransaction: {}, }; export const inferredSpans = { @@ -1651,31 +1660,32 @@ export const inferredSpans = { items: [ { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, source: { - ip: '172.18.0.8' + ip: '172.18.0.8', }, processor: { name: 'transaction', - event: 'transaction' + event: 'transaction', }, url: { path: '/api/products/2', scheme: 'http', port: 3000, domain: '172.18.0.7', - full: 'http://172.18.0.7:3000/api/products/2' + full: 'http://172.18.0.7:3000/api/products/2', }, observer: { hostname: '7189f754b5a3', @@ -1683,43 +1693,43 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.786Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, client: { - ip: '172.18.0.8' + ip: '172.18.0.8', }, http: { request: { @@ -1727,71 +1737,72 @@ export const inferredSpans = { Accept: ['*/*'], 'User-Agent': ['Python/3.7 aiohttp/3.3.2'], Host: ['172.18.0.7:3000'], - 'Accept-Encoding': ['gzip, deflate'] + 'Accept-Encoding': ['gzip, deflate'], }, method: 'get', socket: { encrypted: false, - remote_address: '172.18.0.8' - } + remote_address: '172.18.0.8', + }, }, response: { headers: { 'Transfer-Encoding': ['chunked'], Date: ['Thu, 09 Apr 2020 11:36:01 GMT'], - 'Content-Type': ['application/json;charset=UTF-8'] + 'Content-Type': ['application/json;charset=UTF-8'], }, status_code: 200, finished: true, - headers_sent: true + headers_sent: true, }, - version: '1.1' + version: '1.1', }, user_agent: { original: 'Python/3.7 aiohttp/3.3.2', name: 'Other', device: { - name: 'Other' - } + name: 'Other', + }, }, transaction: { duration: { - us: 237537 + us: 237537, }, result: 'HTTP 2xx', name: 'APIRestController#product', span_count: { dropped: 0, - started: 3 + started: 3, }, id: 'f2387d37260d00bd', type: 'request', - sampled: true + sampled: true, }, timestamp: { - us: 1586432160786001 - } + us: 1586432160786001, + }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: '7189f754b5a3', @@ -1799,77 +1810,78 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.810Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, span: { duration: { - us: 204574 + us: 204574, }, subtype: 'inferred', name: 'ServletInvocableHandlerMethod#invokeAndHandle', id: 'a5df600bd7bd5e38', - type: 'app' + type: 'app', }, timestamp: { - us: 1586432160810441 - } + us: 1586432160810441, + }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: 'a5df600bd7bd5e38' + id: 'a5df600bd7bd5e38', }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: '7189f754b5a3', @@ -1877,50 +1889,50 @@ export const inferredSpans = { type: 'apm-server', ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.810Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, timestamp: { - us: 1586432160810441 + us: 1586432160810441, }, span: { duration: { - us: 102993 + us: 102993, }, stacktrace: [ { @@ -1928,49 +1940,50 @@ export const inferredSpans = { exclude_from_grouping: false, filename: 'InvocableHandlerMethod.java', line: { - number: -1 + number: -1, }, - function: 'doInvoke' + function: 'doInvoke', }, { exclude_from_grouping: false, library_frame: true, filename: 'InvocableHandlerMethod.java', line: { - number: -1 + number: -1, }, - function: 'invokeForRequest' - } + function: 'invokeForRequest', + }, ], subtype: 'inferred', name: 'APIRestController#product', id: '808dc34fc41ce522', - type: 'app' - } + type: 'app', + }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, labels: { - productId: '2' + productId: '2', }, observer: { hostname: '7189f754b5a3', @@ -1978,77 +1991,78 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.832Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, timestamp: { - us: 1586432160832300 + us: 1586432160832300, }, span: { duration: { - us: 99295 + us: 99295, }, name: 'OpenTracing product span', id: '41226ae63af4f235', - type: 'unknown' + type: 'unknown', }, - child: { id: ['8d80de06aa11a6fc'] } + child: { id: ['8d80de06aa11a6fc'] }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: '808dc34fc41ce522' + id: '808dc34fc41ce522', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: '7189f754b5a3', @@ -2056,81 +2070,82 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.859Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, timestamp: { - us: 1586432160859600 + us: 1586432160859600, }, span: { duration: { - us: 53835 + us: 53835, }, subtype: 'inferred', name: 'Loader#executeQueryStatement', id: '8d80de06aa11a6fc', - type: 'app' - } + type: 'app', + }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: '41226ae63af4f235' + id: '41226ae63af4f235', }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, destination: { address: 'postgres', - port: 5432 + port: 5432, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: '7189f754b5a3', @@ -2138,58 +2153,58 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.903Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, timestamp: { - us: 1586432160903236 + us: 1586432160903236, }, span: { duration: { - us: 10211 + us: 10211, }, subtype: 'postgresql', destination: { service: { resource: 'postgresql', name: 'postgresql', - type: 'db' - } + type: 'db', + }, }, name: 'SELECT FROM products', action: 'query', @@ -2200,35 +2215,36 @@ export const inferredSpans = { 'select product0_.id as col_0_0_, product0_.sku as col_1_0_, product0_.name as col_2_0_, product0_.description as col_3_0_, product0_.cost as col_4_0_, product0_.selling_price as col_5_0_, product0_.stock as col_6_0_, producttyp1_.id as col_7_0_, producttyp1_.name as col_8_0_, (select sum(orderline2_.amount) from order_lines orderline2_ where orderline2_.product_id=product0_.id) as col_9_0_ from products product0_ left outer join product_types producttyp1_ on product0_.type_id=producttyp1_.id where product0_.id=?', type: 'sql', user: { - name: 'postgres' - } - } - } + name: 'postgres', + }, + }, + }, }, { container: { - id: 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + id: + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, parent: { - id: '41226ae63af4f235' + id: '41226ae63af4f235', }, process: { pid: 6, title: '/opt/java/openjdk/bin/java', - ppid: 1 + ppid: 1, }, agent: { name: 'java', ephemeral_id: '1cb5c830-c677-4b13-b340-ab1502f527c3', - version: '1.15.1-SNAPSHOT' + version: '1.15.1-SNAPSHOT', }, destination: { address: 'postgres', - port: 5432 + port: 5432, }, processor: { name: 'transaction', - event: 'span' + event: 'span', }, observer: { hostname: '7189f754b5a3', @@ -2236,58 +2252,58 @@ export const inferredSpans = { ephemeral_id: 'bff20764-0195-4f78-aa84-d799fc47b954', type: 'apm-server', version: '8.0.0', - version_major: 8 + version_major: 8, }, trace: { - id: '3b0dc77f3754e5bcb9da0e4c15e0db97' + id: '3b0dc77f3754e5bcb9da0e4c15e0db97', }, '@timestamp': '2020-04-09T11:36:00.859Z', ecs: { - version: '1.5.0' + version: '1.5.0', }, service: { node: { name: - 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad' + 'fc2ae281f56fb84728bc9b5e6c17f3d13bbb7f4efd461158558e5c38e655abad', }, environment: 'production', name: 'opbeans-java', runtime: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, language: { name: 'Java', - version: '11.0.6' + version: '11.0.6', }, - version: 'None' + version: 'None', }, host: { hostname: 'fc2ae281f56f', os: { - platform: 'Linux' + platform: 'Linux', }, ip: '172.18.0.7', name: 'fc2ae281f56f', - architecture: 'amd64' + architecture: 'amd64', }, transaction: { - id: 'f2387d37260d00bd' + id: 'f2387d37260d00bd', }, timestamp: { - us: 1586432160859508 + us: 1586432160859508, }, span: { duration: { - us: 4503 + us: 4503, }, subtype: 'postgresql', destination: { service: { resource: 'postgresql', name: 'postgresql', - type: 'db' - } + type: 'db', + }, }, name: 'empty query', action: 'query', @@ -2298,14 +2314,14 @@ export const inferredSpans = { statement: '(empty query)', type: 'sql', user: { - name: 'postgres' - } - } - } - } + name: 'postgres', + }, + }, + }, + }, ], exceedsMax: false, - errorDocs: [] + errorDocs: [], }, - errorsPerTransaction: {} + errorsPerTransaction: {}, }; diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/__tests__/ErrorCount.test.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/__tests__/ErrorCount.test.tsx index 62b5f7834d3a9..40b8a57f55051 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/__tests__/ErrorCount.test.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/__tests__/ErrorCount.test.tsx @@ -29,7 +29,7 @@ describe('ErrorCount', () => { getByText('1 Error'), new MouseEvent('click', { bubbles: true, - cancelable: true + cancelable: true, }) ); expect(mock).not.toHaveBeenCalled(); diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx index 056e9cdb75148..beb0c03f37f8f 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/WaterfallWithSummmary/index.tsx @@ -11,7 +11,7 @@ import { EuiPagination, EuiPanel, EuiSpacer, - EuiTitle + EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { Location } from 'history'; @@ -43,7 +43,7 @@ export const WaterfallWithSummmary: React.FC = ({ waterfall, exceedsMax, isLoading, - traceSamples + traceSamples, }) => { const [sampleActivePage, setSampleActivePage] = useState(0); @@ -59,8 +59,8 @@ export const WaterfallWithSummmary: React.FC = ({ search: fromQuery({ ...toQuery(history.location.search), transactionId: sample.transactionId, - traceId: sample.traceId - }) + traceId: sample.traceId, + }), }); }; @@ -73,7 +73,7 @@ export const WaterfallWithSummmary: React.FC = ({ title={
      {i18n.translate('xpack.apm.transactionDetails.traceNotFound', { - defaultMessage: 'The selected trace cannot be found' + defaultMessage: 'The selected trace cannot be found', })}
      } @@ -91,7 +91,7 @@ export const WaterfallWithSummmary: React.FC = ({
      {i18n.translate('xpack.apm.transactionDetails.traceSampleTitle', { - defaultMessage: 'Trace sample' + defaultMessage: 'Trace sample', })}
      diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx index 2544dc2a1a77c..c1bfce4cdca49 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx @@ -10,7 +10,7 @@ import { EuiTitle, EuiHorizontalRule, EuiFlexGroup, - EuiFlexItem + EuiFlexItem, } from '@elastic/eui'; import _ from 'lodash'; import React, { useMemo } from 'react'; @@ -36,7 +36,7 @@ export function TransactionDetails() { const { urlParams } = useUrlParams(); const { data: distributionData, - status: distributionStatus + status: distributionStatus, } = useTransactionDistribution(urlParams); const { data: transactionChartsData } = useTransactionCharts(); @@ -55,15 +55,15 @@ export function TransactionDetails() { params: { transactionName, transactionType, - serviceName - } + serviceName, + }, }; return config; }, [transactionName, transactionType, serviceName]); - const bucketIndex = distributionData.buckets.findIndex(bucket => + const bucketIndex = distributionData.buckets.findIndex((bucket) => bucket.samples.some( - sample => + (sample) => sample.transactionId === urlParams.transactionId && sample.traceId === urlParams.traceId ) diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx index f8dcec14630a5..61c8d3958b625 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/List/index.tsx @@ -32,7 +32,7 @@ interface Props { const toMilliseconds = (time: number) => convertTo({ unit: 'milliseconds', - microseconds: time + microseconds: time, }).formatted; export function TransactionList({ items, isLoading }: Props) { @@ -41,7 +41,7 @@ export function TransactionList({ items, isLoading }: Props) { { field: 'name', name: i18n.translate('xpack.apm.transactionsTable.nameColumnLabel', { - defaultMessage: 'Name' + defaultMessage: 'Name', }), width: '50%', sortable: true, @@ -62,38 +62,38 @@ export function TransactionList({ items, isLoading }: Props) { ); - } + }, }, { field: 'averageResponseTime', name: i18n.translate( 'xpack.apm.transactionsTable.avgDurationColumnLabel', { - defaultMessage: 'Avg. duration' + defaultMessage: 'Avg. duration', } ), sortable: true, dataType: 'number', - render: (time: number) => toMilliseconds(time) + render: (time: number) => toMilliseconds(time), }, { field: 'p95', name: i18n.translate( 'xpack.apm.transactionsTable.95thPercentileColumnLabel', { - defaultMessage: '95th percentile' + defaultMessage: '95th percentile', } ), sortable: true, dataType: 'number', - render: (time: number) => toMilliseconds(time) + render: (time: number) => toMilliseconds(time), }, { field: 'transactionsPerMinute', name: i18n.translate( 'xpack.apm.transactionsTable.transactionsPerMinuteColumnLabel', { - defaultMessage: 'Trans. per minute' + defaultMessage: 'Trans. per minute', } ), sortable: true, @@ -102,29 +102,29 @@ export function TransactionList({ items, isLoading }: Props) { `${asDecimal(value)} ${i18n.translate( 'xpack.apm.transactionsTable.transactionsPerMinuteUnitLabel', { - defaultMessage: 'tpm' + defaultMessage: 'tpm', } - )}` + )}`, }, { field: 'impact', name: ( <> {i18n.translate('xpack.apm.transactionsTable.impactColumnLabel', { - defaultMessage: 'Impact' + defaultMessage: 'Impact', })}{' '} @@ -132,8 +132,8 @@ export function TransactionList({ items, isLoading }: Props) { ), sortable: true, dataType: 'number', - render: (value: number) => - } + render: (value: number) => , + }, ], [] ); @@ -141,7 +141,7 @@ export function TransactionList({ items, isLoading }: Props) { const noItemsMessage = ( ); diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/__jest__/TransactionOverview.test.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/__jest__/TransactionOverview.test.tsx index 22cbeee5c6b7c..9c514e429c374 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionOverview/__jest__/TransactionOverview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/__jest__/TransactionOverview.test.tsx @@ -11,7 +11,7 @@ import { getByText, getByDisplayValue, queryByDisplayValue, - fireEvent + fireEvent, } from '@testing-library/react'; import { omit } from 'lodash'; import { history } from '../../../../utils/history'; @@ -30,18 +30,18 @@ jest.spyOn(history, 'replace'); jest.mock('ui/new_platform'); function setup({ urlParams, - serviceTransactionTypes + serviceTransactionTypes, }: { urlParams: IUrlParams; serviceTransactionTypes: string[]; }) { const defaultLocation = { pathname: '/services/foo/transactions', - search: fromQuery(omit(urlParams, 'serviceName')) + search: fromQuery(omit(urlParams, 'serviceName')), } as any; history.replace({ - ...defaultLocation + ...defaultLocation, }); jest @@ -71,12 +71,12 @@ describe('TransactionOverview', () => { setup({ serviceTransactionTypes: ['firstType', 'secondType'], urlParams: { - serviceName: 'MyServiceName' - } + serviceName: 'MyServiceName', + }, }); expect(history.replace).toHaveBeenCalledWith( expect.objectContaining({ - search: 'transactionType=firstType' + search: 'transactionType=firstType', }) ); }); @@ -90,8 +90,8 @@ describe('TransactionOverview', () => { serviceTransactionTypes: ['firstType', 'secondType'], urlParams: { transactionType: 'secondType', - serviceName: 'MyServiceName' - } + serviceName: 'MyServiceName', + }, }); // secondType is selected in the dropdown @@ -106,14 +106,14 @@ describe('TransactionOverview', () => { serviceTransactionTypes: ['firstType', 'secondType'], urlParams: { transactionType: 'secondType', - serviceName: 'MyServiceName' - } + serviceName: 'MyServiceName', + }, }); expect(queryByDisplayValue(container, 'firstType')).toBeNull(); fireEvent.change(getByDisplayValue(container, 'secondType'), { - target: { value: 'firstType' } + target: { value: 'firstType' }, }); expect(history.push).toHaveBeenCalled(); @@ -130,8 +130,8 @@ describe('TransactionOverview', () => { serviceTransactionTypes: ['firstType'], urlParams: { transactionType: 'firstType', - serviceName: 'MyServiceName' - } + serviceName: 'MyServiceName', + }, }); expect(queryByLabelText(container, FILTER_BY_TYPE_LABEL)).toBeNull(); diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx index 95e73d7383957..9018fbb2bc410 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx @@ -10,7 +10,7 @@ import { EuiTitle, EuiFlexGroup, EuiFlexItem, - EuiHorizontalRule + EuiHorizontalRule, } from '@elastic/eui'; import { Location } from 'history'; import { first } from 'lodash'; @@ -39,7 +39,7 @@ import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; function getRedirectLocation({ urlParams, location, - serviceTransactionTypes + serviceTransactionTypes, }: { location: Location; urlParams: IUrlParams; @@ -53,8 +53,8 @@ function getRedirectLocation({ ...location, search: fromQuery({ ...toQuery(location.search), - transactionType: firstTransactionType - }) + transactionType: firstTransactionType, + }), }; } } @@ -73,7 +73,7 @@ export function TransactionOverview() { getRedirectLocation({ urlParams, location, - serviceTransactionTypes + serviceTransactionTypes, }) ); @@ -83,7 +83,7 @@ export function TransactionOverview() { useTrackPageview({ app: 'apm', path: 'transaction_overview', delay: 15000 }); const { data: transactionListData, - status: transactionListStatus + status: transactionListStatus, } = useTransactionList(urlParams); const { http } = useApmPluginContext().core; @@ -105,13 +105,13 @@ export function TransactionOverview() { 'host', 'containerId', 'podName', - 'serviceVersion' + 'serviceVersion', ], params: { serviceName, - transactionType + transactionType, }, - projection: PROJECTION.TRANSACTION_GROUPS + projection: PROJECTION.TRANSACTION_GROUPS, }), [serviceName, transactionType] ); diff --git a/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx b/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx index 32379325c4020..639277a79ac9a 100644 --- a/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/DatePicker/__test__/DatePicker.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { LocationProvider } from '../../../../context/LocationContext'; import { UrlParamsContext, - useUiFilters + useUiFilters, } from '../../../../context/UrlParamsContext'; import { DatePicker } from '../index'; import { IUrlParams } from '../../../../context/UrlParamsContext/types'; @@ -27,7 +27,7 @@ const MockUrlParamsProvider: React.FC<{ value={{ urlParams: params, refreshTimeRange: mockRefreshTimeRange, - uiFilters: useUiFilters(params) + uiFilters: useUiFilters(params), }} children={children} /> @@ -60,18 +60,15 @@ describe('DatePicker', () => { it('should update the URL when the date range changes', () => { const datePicker = mountDatePicker(); - datePicker - .find(EuiSuperDatePicker) - .props() - .onTimeChange({ - start: 'updated-start', - end: 'updated-end', - isInvalid: false, - isQuickSelection: true - }); + datePicker.find(EuiSuperDatePicker).props().onTimeChange({ + start: 'updated-start', + end: 'updated-end', + isInvalid: false, + isQuickSelection: true, + }); expect(mockHistoryPush).toHaveBeenCalledWith( expect.objectContaining({ - search: 'rangeFrom=updated-start&rangeTo=updated-end' + search: 'rangeFrom=updated-start&rangeTo=updated-end', }) ); }); @@ -80,7 +77,7 @@ describe('DatePicker', () => { jest.useFakeTimers(); const wrapper = mountDatePicker({ refreshPaused: false, - refreshInterval: 1000 + refreshInterval: 1000, }); expect(mockRefreshTimeRange).not.toHaveBeenCalled(); jest.advanceTimersByTime(1000); diff --git a/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx b/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx index db21d837c900a..4391e4a5b8952 100644 --- a/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/DatePicker/index.tsx @@ -21,58 +21,58 @@ export function DatePicker() { start: 'now-15m', end: 'now', label: i18n.translate('xpack.apm.datePicker.last15MinutesLabel', { - defaultMessage: 'Last 15 minutes' - }) + defaultMessage: 'Last 15 minutes', + }), }, { start: 'now-30m', end: 'now', label: i18n.translate('xpack.apm.datePicker.last30MinutesLabel', { - defaultMessage: 'Last 30 minutes' - }) + defaultMessage: 'Last 30 minutes', + }), }, { start: 'now-1h', end: 'now', label: i18n.translate('xpack.apm.datePicker.last1HourLabel', { - defaultMessage: 'Last 1 hour' - }) + defaultMessage: 'Last 1 hour', + }), }, { start: 'now-24h', end: 'now', label: i18n.translate('xpack.apm.datePicker.last24HoursLabel', { - defaultMessage: 'Last 24 hours' - }) + defaultMessage: 'Last 24 hours', + }), }, { start: 'now-7d', end: 'now', label: i18n.translate('xpack.apm.datePicker.last7DaysLabel', { - defaultMessage: 'Last 7 days' - }) + defaultMessage: 'Last 7 days', + }), }, { start: 'now-30d', end: 'now', label: i18n.translate('xpack.apm.datePicker.last30DaysLabel', { - defaultMessage: 'Last 30 days' - }) + defaultMessage: 'Last 30 days', + }), }, { start: 'now-90d', end: 'now', label: i18n.translate('xpack.apm.datePicker.last90DaysLabel', { - defaultMessage: 'Last 90 days' - }) + defaultMessage: 'Last 90 days', + }), }, { start: 'now-1y', end: 'now', label: i18n.translate('xpack.apm.datePicker.last1YearLabel', { - defaultMessage: 'Last 1 year' - }) - } + defaultMessage: 'Last 1 year', + }), + }, ]; function updateUrl(nextQuery: { @@ -85,14 +85,14 @@ export function DatePicker() { ...location, search: fromQuery({ ...toQuery(location.search), - ...nextQuery - }) + ...nextQuery, + }), }); } function onRefreshChange({ isPaused, - refreshInterval + refreshInterval, }: { isPaused: boolean; refreshInterval: number; diff --git a/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx b/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx index 3c279d525410c..f300ed9d65aac 100644 --- a/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx +++ b/x-pack/plugins/apm/public/components/shared/EmptyMessage.tsx @@ -16,12 +16,12 @@ interface Props { const EmptyMessage: React.FC = ({ heading = i18n.translate('xpack.apm.emptyMessage.noDataFoundLabel', { - defaultMessage: 'No data found.' + defaultMessage: 'No data found.', }), subheading = i18n.translate('xpack.apm.emptyMessage.noDataFoundDescription', { - defaultMessage: 'Try another time range or reset the search filter.' + defaultMessage: 'Try another time range or reset the search filter.', }), - hideSubheading = false + hideSubheading = false, }) => { return ( = ({ environments = [] }) => { if (environments.length < 3) { return ( <> - {environments.map(env => ( + {environments.map((env) => ( {env} @@ -26,7 +26,7 @@ export const EnvironmentBadge: React.FC = ({ environments = [] }) => { return ( ( + content={environments.map((env) => ( {env}
      @@ -37,7 +37,7 @@ export const EnvironmentBadge: React.FC = ({ environments = [] }) => { {i18n.translate('xpack.apm.servicesTable.environmentCount', { values: { environmentCount: environments.length }, defaultMessage: - '{environmentCount, plural, one {1 environment} other {# environments}}' + '{environmentCount, plural, one {1 environment} other {# environments}}', })}
      diff --git a/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx b/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx index 5d03dbbfdf4ff..28dd5e7a5a363 100644 --- a/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/EnvironmentFilter/index.tsx @@ -13,7 +13,7 @@ import { history } from '../../../utils/history'; import { fromQuery, toQuery } from '../Links/url_helpers'; import { ENVIRONMENT_ALL, - ENVIRONMENT_NOT_DEFINED + ENVIRONMENT_NOT_DEFINED, } from '../../../../common/environment_filter_values'; import { useEnvironments, ALL_OPTION } from '../../../hooks/useEnvironments'; @@ -27,16 +27,16 @@ function updateEnvironmentUrl( ...location, search: fromQuery({ ...toQuery(location.search), - environment: nextEnvironmentQueryParam - }) + environment: nextEnvironmentQueryParam, + }), }); } const NOT_DEFINED_OPTION = { value: ENVIRONMENT_NOT_DEFINED, text: i18n.translate('xpack.apm.filter.environment.notDefinedLabel', { - defaultMessage: 'Not defined' - }) + defaultMessage: 'Not defined', + }), }; const SEPARATOR_OPTION = { @@ -44,15 +44,15 @@ const SEPARATOR_OPTION = { 'xpack.apm.filter.environment.selectEnvironmentLabel', { defaultMessage: 'Select environment' } )} -`, - disabled: true + disabled: true, }; function getOptions(environments: string[]) { const environmentOptions = environments - .filter(env => env !== ENVIRONMENT_NOT_DEFINED) - .map(environment => ({ + .filter((env) => env !== ENVIRONMENT_NOT_DEFINED) + .map((environment) => ({ value: environment, - text: environment + text: environment, })); return [ @@ -61,7 +61,7 @@ function getOptions(environments: string[]) { ? [NOT_DEFINED_OPTION] : []), ...(environmentOptions.length > 0 ? [SEPARATOR_OPTION] : []), - ...environmentOptions + ...environmentOptions, ]; } @@ -74,17 +74,17 @@ export const EnvironmentFilter: React.FC = () => { const { environments, status = 'loading' } = useEnvironments({ serviceName, start, - end + end, }); return ( { + onChange={(event) => { updateEnvironmentUrl(location, event.target.value); }} isLoading={status === 'loading'} diff --git a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx index 4ef8de7c2b208..ddfca94e567d9 100644 --- a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.stories.tsx @@ -8,10 +8,10 @@ import { storiesOf } from '@storybook/react'; import React from 'react'; import { ErrorRateAlertTrigger } from '.'; -storiesOf('app/ErrorRateAlertTrigger', module).add('example', props => { +storiesOf('app/ErrorRateAlertTrigger', module).add('example', (props) => { const params = { threshold: 2, - window: '5m' + window: '5m', }; return ( diff --git a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.tsx b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.tsx index 649412ecd238e..fd107a087cace 100644 --- a/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/ErrorRateAlertTrigger/index.tsx @@ -39,12 +39,12 @@ export function ErrorRateAlertTrigger(props: Props) { threshold: 25, windowSize: 1, windowUnit: 'm', - environment: ALL_OPTION.value + environment: ALL_OPTION.value, }; const params = { ...defaults, - ...alertParams + ...alertParams, }; const threshold = isFinite(params.threshold) ? params.threshold : ''; @@ -57,13 +57,13 @@ export function ErrorRateAlertTrigger(props: Props) { : params.environment } title={i18n.translate('xpack.apm.errorRateAlertTrigger.environment', { - defaultMessage: 'Environment' + defaultMessage: 'Environment', })} > + onChange={(e) => setAlertParams( 'environment', e.target.value as ErrorRateAlertTriggerParams['environment'] @@ -74,36 +74,36 @@ export function ErrorRateAlertTrigger(props: Props) { , + onChange={(e) => setAlertParams('threshold', parseInt(e.target.value, 10)) } compressed append={i18n.translate('xpack.apm.errorRateAlertTrigger.errors', { - defaultMessage: 'errors' + defaultMessage: 'errors', })} /> , + onChangeWindowSize={(windowSize) => setAlertParams('windowSize', windowSize || '') } - onChangeWindowUnit={windowUnit => + onChangeWindowUnit={(windowUnit) => setAlertParams('windowUnit', windowUnit) } timeWindowSize={params.windowSize} timeWindowUnit={params.windowUnit} errors={{ timeWindowSize: [], - timeWindowUnit: [] + timeWindowUnit: [], }} - /> + />, ]; return ( diff --git a/x-pack/plugins/apm/public/components/shared/ErrorStatePrompt.tsx b/x-pack/plugins/apm/public/components/shared/ErrorStatePrompt.tsx index 7154d006fcaae..6534b50109716 100644 --- a/x-pack/plugins/apm/public/components/shared/ErrorStatePrompt.tsx +++ b/x-pack/plugins/apm/public/components/shared/ErrorStatePrompt.tsx @@ -14,12 +14,12 @@ export function ErrorStatePrompt() { title={
      {i18n.translate('xpack.apm.error.prompt.title', { - defaultMessage: `Sorry, an error occured :(` + defaultMessage: `Sorry, an error occured :(`, })}
      } body={i18n.translate('xpack.apm.error.prompt.body', { - defaultMessage: `Please inspect your browser's developer console for details.` + defaultMessage: `Please inspect your browser's developer console for details.`, })} titleSize="s" /> diff --git a/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx b/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx index e37b562782655..73fd2544a34ae 100644 --- a/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/EuiTabLink.tsx @@ -37,7 +37,7 @@ const EuiTabLink = (props: Props) => { const { isSelected, children } = props; const className = cls('euiTab', { - 'euiTab-isSelected': isSelected + 'euiTab-isSelected': isSelected, }); return ( diff --git a/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx b/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx index aeb2d25ffeae1..be8ff87617c80 100644 --- a/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/HeightRetainer/index.tsx @@ -6,7 +6,7 @@ import React, { useEffect, useRef } from 'react'; -export const HeightRetainer: React.FC = props => { +export const HeightRetainer: React.FC = (props) => { const containerElement = useRef(null); const minHeight = useRef(0); diff --git a/x-pack/plugins/apm/public/components/shared/KeyValueTable/FormattedValue.tsx b/x-pack/plugins/apm/public/components/shared/KeyValueTable/FormattedValue.tsx index d33960fe5196b..ac4f8a2086bd5 100644 --- a/x-pack/plugins/apm/public/components/shared/KeyValueTable/FormattedValue.tsx +++ b/x-pack/plugins/apm/public/components/shared/KeyValueTable/FormattedValue.tsx @@ -17,7 +17,7 @@ const EmptyValue = styled.span` export function FormattedKey({ k, - value + value, }: { k: string; value: unknown; diff --git a/x-pack/plugins/apm/public/components/shared/KeyValueTable/__test__/KeyValueTable.test.tsx b/x-pack/plugins/apm/public/components/shared/KeyValueTable/__test__/KeyValueTable.test.tsx index 20125afb52f48..4384b21c06159 100644 --- a/x-pack/plugins/apm/public/components/shared/KeyValueTable/__test__/KeyValueTable.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/KeyValueTable/__test__/KeyValueTable.test.tsx @@ -10,12 +10,12 @@ import { render } from '@testing-library/react'; function getKeys(output: ReturnType) { const keys = output.getAllByTestId('dot-key'); - return Array.isArray(keys) ? keys.map(node => node.textContent) : []; + return Array.isArray(keys) ? keys.map((node) => node.textContent) : []; } function getValues(output: ReturnType) { const values = output.getAllByTestId('value'); - return Array.isArray(values) ? values.map(node => node.textContent) : []; + return Array.isArray(values) ? values.map((node) => node.textContent) : []; } describe('KeyValueTable', () => { @@ -29,7 +29,7 @@ describe('KeyValueTable', () => { { key: 'start', value: null }, { key: 'end', value: undefined }, { key: 'nested.b.c', value: 'ccc' }, - { key: 'nested.a', value: 'aaa' } + { key: 'nested.a', value: 'aaa' }, ]; const output = render(); const rows = output.container.querySelectorAll('tr'); @@ -44,7 +44,7 @@ describe('KeyValueTable', () => { 'start', 'end', 'nested.b.c', - 'nested.a' + 'nested.a', ]); expect(getValues(output)).toEqual([ @@ -56,7 +56,7 @@ describe('KeyValueTable', () => { 'N/A', 'N/A', 'ccc', - 'aaa' + 'aaa', ]); }); }); diff --git a/x-pack/plugins/apm/public/components/shared/KeyValueTable/index.tsx b/x-pack/plugins/apm/public/components/shared/KeyValueTable/index.tsx index e8ed39bf9ac33..86edd8bd6c57b 100644 --- a/x-pack/plugins/apm/public/components/shared/KeyValueTable/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/KeyValueTable/index.tsx @@ -10,14 +10,14 @@ import { EuiTableProps, EuiTableBody, EuiTableRow, - EuiTableRowCell + EuiTableRowCell, } from '@elastic/eui'; import { FormattedValue } from './FormattedValue'; import { KeyValuePair } from '../../../utils/flattenObject'; export function KeyValueTable({ keyValuePairs, - tableProps = {} + tableProps = {}, }: { keyValuePairs: KeyValuePair[]; tableProps?: EuiTableProps & TableHTMLAttributes; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js index 93a95c844a975..be7004ec857f5 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/ClickOutside.js @@ -16,11 +16,11 @@ export default class ClickOutside extends Component { document.removeEventListener('mousedown', this.onClick); } - setNodeRef = node => { + setNodeRef = (node) => { this.nodeRef = node; }; - onClick = event => { + onClick = (event) => { if (this.nodeRef && !this.nodeRef.contains(event.target)) { this.props.onClickOutside(); } @@ -38,5 +38,5 @@ export default class ClickOutside extends Component { } ClickOutside.propTypes = { - onClickOutside: PropTypes.func.isRequired + onClickOutside: PropTypes.func.isRequired, }; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js index e7c5564851efa..a4d68feffdc46 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestion.js @@ -13,7 +13,7 @@ import { px, units, fontSizes, - unit + unit, } from '../../../../style/variables'; import { tint } from 'polished'; import theme from '@elastic/eui/dist/eui_theme_light.json'; @@ -53,14 +53,14 @@ const ListItem = styled.li` height: ${px(units.double)}; align-items: center; display: flex; - background: ${props => + background: ${(props) => props.selected ? theme.euiColorLightestShade : 'initial'}; cursor: pointer; border-radius: ${px(units.quarter)}; ${Description} { p span { - background: ${props => + background: ${(props) => props.selected ? theme.euiColorEmptyShade : theme.euiColorLightestShade}; @@ -70,8 +70,8 @@ const ListItem = styled.li` const Icon = styled.div` flex: 0 0 ${px(units.double)}; - background: ${props => tint(0.1, getIconColor(props.type))}; - color: ${props => getIconColor(props.type)}; + background: ${(props) => tint(0.1, getIconColor(props.type))}; + color: ${(props) => getIconColor(props.type)}; width: 100%; height: 100%; text-align: center; @@ -123,7 +123,7 @@ Suggestion.propTypes = { onMouseEnter: PropTypes.func.isRequired, selected: PropTypes.bool, suggestion: PropTypes.object.isRequired, - innerRef: PropTypes.func.isRequired + innerRef: PropTypes.func.isRequired, }; export default Suggestion; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js index 4f17ead213985..fbc7cbcb78535 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/Suggestions.js @@ -61,7 +61,7 @@ class Suggestions extends Component { const key = suggestion + '_' + index; return ( (this.childNodes[index] = node)} + innerRef={(node) => (this.childNodes[index] = node)} selected={index === this.props.index} suggestion={suggestion} onClick={this.props.onClick} @@ -72,7 +72,7 @@ class Suggestions extends Component { }); return ( - (this.parentNode = node)}>{suggestions} + (this.parentNode = node)}>{suggestions} ); } } @@ -82,7 +82,7 @@ Suggestions.propTypes = { onClick: PropTypes.func.isRequired, onMouseEnter: PropTypes.func.isRequired, show: PropTypes.bool, - suggestions: PropTypes.array.isRequired + suggestions: PropTypes.array.isRequired, }; export default Suggestions; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js index 7a7dfe8b50e3e..741df4ca2eb8c 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/Typeahead/index.js @@ -17,7 +17,7 @@ const KEY_CODES = { DOWN: 40, ENTER: 13, ESC: 27, - TAB: 9 + TAB: 9, }; export class Typeahead extends Component { @@ -25,7 +25,7 @@ export class Typeahead extends Component { isSuggestionsVisible: false, index: null, value: '', - initialValue: '' + initialValue: '', }; static getDerivedStateFromProps(props, state) { @@ -33,14 +33,14 @@ export class Typeahead extends Component { if (initialValue !== state.initialValue) { return { value: initialValue, - initialValue + initialValue, }; } return null; } - incrementIndex = currentIndex => { + incrementIndex = (currentIndex) => { let nextIndex = currentIndex + 1; if (currentIndex === null || nextIndex >= this.props.suggestions.length) { nextIndex = 0; @@ -48,7 +48,7 @@ export class Typeahead extends Component { this.setState({ index: nextIndex }); }; - decrementIndex = currentIndex => { + decrementIndex = (currentIndex) => { let previousIndex = currentIndex - 1; if (previousIndex < 0) { previousIndex = null; @@ -56,7 +56,7 @@ export class Typeahead extends Component { this.setState({ index: previousIndex }); }; - onKeyUp = event => { + onKeyUp = (event) => { const { selectionStart } = event.target; const { value } = this.state; switch (event.keyCode) { @@ -71,7 +71,7 @@ export class Typeahead extends Component { } }; - onKeyDown = event => { + onKeyDown = (event) => { const { isSuggestionsVisible, index, value } = this.state; switch (event.keyCode) { case KEY_CODES.DOWN: @@ -107,7 +107,7 @@ export class Typeahead extends Component { } }; - selectSuggestion = suggestion => { + selectSuggestion = (suggestion) => { const nextInputValue = this.state.value.substr(0, suggestion.start) + suggestion.text + @@ -121,13 +121,13 @@ export class Typeahead extends Component { this.setState({ isSuggestionsVisible: false }); }; - onChangeInputValue = event => { + onChangeInputValue = (event) => { const { value, selectionStart } = event.target; const hasValue = Boolean(value.trim()); this.setState({ value, isSuggestionsVisible: hasValue, - index: null + index: null, }); if (!hasValue) { @@ -136,17 +136,17 @@ export class Typeahead extends Component { this.props.onChange(value, selectionStart); }; - onClickInput = event => { + onClickInput = (event) => { const { selectionStart } = event.target; this.props.onChange(this.state.value, selectionStart); }; - onClickSuggestion = suggestion => { + onClickSuggestion = (suggestion) => { this.selectSuggestion(suggestion); this.inputRef.focus(); }; - onMouseEnterSuggestion = index => { + onMouseEnterSuggestion = (index) => { this.setState({ index }); }; @@ -167,10 +167,10 @@ export class Typeahead extends Component { { + inputRef={(node) => { if (node) { this.inputRef = node; } @@ -192,7 +192,7 @@ export class Typeahead extends Component { position="absolute" style={{ bottom: 0, - top: 'initial' + top: 'initial', }} /> )} @@ -217,11 +217,11 @@ Typeahead.propTypes = { onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, suggestions: PropTypes.array.isRequired, - placeholder: PropTypes.string.isRequired + placeholder: PropTypes.string.isRequired, }; Typeahead.defaultProps = { isLoading: false, disabled: false, - suggestions: [] + suggestions: [], }; diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts b/x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts index f4628524cced5..5bac01cfaf55d 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/get_bool_filter.ts @@ -10,7 +10,7 @@ import { ERROR_GROUP_ID, PROCESSOR_EVENT, TRANSACTION_NAME, - SERVICE_NAME + SERVICE_NAME, } from '../../../../common/elasticsearch_fieldnames'; import { IUrlParams } from '../../../context/UrlParamsContext/types'; @@ -27,52 +27,52 @@ export function getBoolFilter(urlParams: IUrlParams) { '@timestamp': { gte: new Date(start).getTime(), lte: new Date(end).getTime(), - format: 'epoch_millis' - } - } - } + format: 'epoch_millis', + }, + }, + }, ]; if (serviceName) { boolFilter.push({ - term: { [SERVICE_NAME]: serviceName } + term: { [SERVICE_NAME]: serviceName }, }); } switch (processorEvent) { case 'transaction': boolFilter.push({ - term: { [PROCESSOR_EVENT]: 'transaction' } + term: { [PROCESSOR_EVENT]: 'transaction' }, }); if (urlParams.transactionName) { boolFilter.push({ - term: { [TRANSACTION_NAME]: urlParams.transactionName } + term: { [TRANSACTION_NAME]: urlParams.transactionName }, }); } if (urlParams.transactionType) { boolFilter.push({ - term: { [TRANSACTION_TYPE]: urlParams.transactionType } + term: { [TRANSACTION_TYPE]: urlParams.transactionType }, }); } break; case 'error': boolFilter.push({ - term: { [PROCESSOR_EVENT]: 'error' } + term: { [PROCESSOR_EVENT]: 'error' }, }); if (urlParams.errorGroupId) { boolFilter.push({ - term: { [ERROR_GROUP_ID]: urlParams.errorGroupId } + term: { [ERROR_GROUP_ID]: urlParams.errorGroupId }, }); } break; case 'metric': boolFilter.push({ - term: { [PROCESSOR_EVENT]: 'metric' } + term: { [PROCESSOR_EVENT]: 'metric' }, }); break; @@ -82,9 +82,9 @@ export function getBoolFilter(urlParams: IUrlParams) { should: [ { term: { [PROCESSOR_EVENT]: 'error' } }, { term: { [PROCESSOR_EVENT]: 'transaction' } }, - { term: { [PROCESSOR_EVENT]: 'metric' } } - ] - } + { term: { [PROCESSOR_EVENT]: 'metric' } }, + ], + }, }); } diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx index 2622d08d4779d..d01deb8160858 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx @@ -20,7 +20,7 @@ import { useDynamicIndexPattern } from '../../../hooks/useDynamicIndexPattern'; import { QuerySuggestion, esKuery, - IIndexPattern + IIndexPattern, } from '../../../../../../../src/plugins/data/public'; const Container = styled.div` @@ -40,7 +40,7 @@ function convertKueryToEsQuery(kuery: string, indexPattern: IIndexPattern) { export function KueryBar() { const [state, setState] = useState({ suggestions: [], - isLoadingSuggestions: false + isLoadingSuggestions: false, }); const { urlParams } = useUrlParams(); const location = useLocation(); @@ -55,7 +55,7 @@ export function KueryBar() { error: 'http.response.status_code >= 400', metric: 'process.pid = "1234"', defaults: - 'transaction.duration.us > 300000 AND http.response.status_code >= 400' + 'transaction.duration.us > 300000 AND http.response.status_code >= 400', }; const example = examples[processorEvent || 'defaults']; @@ -71,8 +71,8 @@ export function KueryBar() { } (E.g. {queryExample})`, values: { queryExample: example, - event: processorEvent - } + event: processorEvent, + }, }); // The bar should be disabled when viewing the service map @@ -100,10 +100,10 @@ export function KueryBar() { boolFilter: getBoolFilter(urlParams), query: inputValue, selectionStart, - selectionEnd: selectionStart + selectionEnd: selectionStart, })) || [] ) - .filter(suggestion => !startsWith(suggestion.text, 'span.')) + .filter((suggestion) => !startsWith(suggestion.text, 'span.')) .slice(0, 15); if (currentRequest !== currentRequestCheck) { @@ -132,8 +132,8 @@ export function KueryBar() { ...location, search: fromQuery({ ...toQuery(location.search), - kuery: encodeURIComponent(inputValue.trim()) - }) + kuery: encodeURIComponent(inputValue.trim()), + }), }); } catch (e) { console.log('Invalid kuery syntax'); // eslint-disable-line no-console diff --git a/x-pack/plugins/apm/public/components/shared/LicensePrompt/LicensePrompt.stories.tsx b/x-pack/plugins/apm/public/components/shared/LicensePrompt/LicensePrompt.stories.tsx index 010bba7677f00..89f5bf28a4938 100644 --- a/x-pack/plugins/apm/public/components/shared/LicensePrompt/LicensePrompt.stories.tsx +++ b/x-pack/plugins/apm/public/components/shared/LicensePrompt/LicensePrompt.stories.tsx @@ -8,7 +8,7 @@ import { storiesOf } from '@storybook/react'; import React from 'react'; import { ApmPluginContext, - ApmPluginContextValue + ApmPluginContextValue, } from '../../../context/ApmPluginContext'; import { LicensePrompt } from '.'; @@ -16,7 +16,7 @@ storiesOf('app/LicensePrompt', module).add( 'example', () => { const contextMock = ({ - core: { http: { basePath: { prepend: () => {} } } } + core: { http: { basePath: { prepend: () => {} } } }, } as unknown) as ApmPluginContextValue; return ( @@ -27,7 +27,7 @@ storiesOf('app/LicensePrompt', module).add( }, { info: { - source: false - } + source: false, + }, } ); diff --git a/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx b/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx index 96e8c754fcc5f..d8464fdfa8481 100644 --- a/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LicensePrompt/index.tsx @@ -27,7 +27,7 @@ export const LicensePrompt = ({ text, showBetaBadge = false }: Props) => { title={

      {i18n.translate('xpack.apm.license.title', { - defaultMessage: 'Start free 30-day trial' + defaultMessage: 'Start free 30-day trial', })}

      } @@ -35,7 +35,7 @@ export const LicensePrompt = ({ text, showBetaBadge = false }: Props) => { actions={ {i18n.translate('xpack.apm.license.button', { - defaultMessage: 'Start trial' + defaultMessage: 'Start trial', })} } @@ -45,13 +45,13 @@ export const LicensePrompt = ({ text, showBetaBadge = false }: Props) => { const renderWithBetaBadge = ( diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx index 05e4080d5d0b7..5679e31a9898b 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverErrorLink.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { ERROR_GROUP_ID, - SERVICE_NAME + SERVICE_NAME, } from '../../../../../common/elasticsearch_fieldnames'; import { APMError } from '../../../../../typings/es_schemas/ui/apm_error'; import { DiscoverLink } from './DiscoverLink'; @@ -25,10 +25,10 @@ function getDiscoverQuery(error: APMError, kuery?: string) { interval: 'auto', query: { language: 'kuery', - query + query, }, - sort: { '@timestamp': 'desc' } - } + sort: { '@timestamp': 'desc' }, + }, }; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverLink.tsx index 8c3e2c2396cbd..a375df7f0b0b9 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverLink.tsx @@ -35,7 +35,7 @@ interface Props { export const getDiscoverHref = ({ basePath, location, - query + query, }: { basePath: AppMountContextBasePath; location: Location; @@ -45,15 +45,15 @@ export const getDiscoverHref = ({ _g: getTimepickerRisonData(location.search), _a: { ...query._a, - index: APM_STATIC_INDEX_PATTERN_ID - } + index: APM_STATIC_INDEX_PATTERN_ID, + }, }; const href = url.format({ pathname: basePath.prepend('/app/discover'), hash: `/?_g=${rison.encode(risonQuery._g)}&_a=${rison.encode( risonQuery._a as RisonValue - )}` + )}`, }); return href; }; @@ -65,7 +65,7 @@ export function DiscoverLink({ query = {}, ...rest }: Props) { const href = getDiscoverHref({ basePath: core.http.basePath, query, - location + location, }); return ; diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx index ac9e33b3acd69..5fce3e842d8da 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverSpanLink.tsx @@ -16,9 +16,9 @@ function getDiscoverQuery(span: Span) { interval: 'auto', query: { language: 'kuery', - query - } - } + query, + }, + }, }; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx index a5f4df7dbac1b..e2500617155c1 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/DiscoverTransactionLink.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { PROCESSOR_EVENT, TRACE_ID, - TRANSACTION_ID + TRANSACTION_ID, } from '../../../../../common/elasticsearch_fieldnames'; import { Transaction } from '../../../../../typings/es_schemas/ui/transaction'; import { DiscoverLink } from './DiscoverLink'; @@ -26,9 +26,9 @@ export function getDiscoverQuery(transaction: Transaction) { interval: 'auto', query: { language: 'kuery', - query - } - } + query, + }, + }, }; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorButton.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorButton.test.tsx index acf8d89432b23..f71c8b71aa2ee 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorButton.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorButton.test.tsx @@ -14,7 +14,7 @@ describe('DiscoverErrorLink without kuery', () => { beforeEach(() => { const error = { service: { name: 'myServiceName' }, - error: { grouping_key: 'myGroupingKey' } + error: { grouping_key: 'myGroupingKey' }, } as APMError; wrapper = shallow(); @@ -37,7 +37,7 @@ describe('DiscoverErrorLink with kuery', () => { beforeEach(() => { const error = { service: { name: 'myServiceName' }, - error: { grouping_key: 'myGroupingKey' } + error: { grouping_key: 'myGroupingKey' }, } as APMError; const kuery = 'transaction.sampled: true'; diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorLink.test.tsx index acf8d89432b23..f71c8b71aa2ee 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverErrorLink.test.tsx @@ -14,7 +14,7 @@ describe('DiscoverErrorLink without kuery', () => { beforeEach(() => { const error = { service: { name: 'myServiceName' }, - error: { grouping_key: 'myGroupingKey' } + error: { grouping_key: 'myGroupingKey' }, } as APMError; wrapper = shallow(); @@ -37,7 +37,7 @@ describe('DiscoverErrorLink with kuery', () => { beforeEach(() => { const error = { service: { name: 'myServiceName' }, - error: { grouping_key: 'myGroupingKey' } + error: { grouping_key: 'myGroupingKey' }, } as APMError; const kuery = 'transaction.sampled: true'; diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverLinks.integration.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverLinks.integration.test.tsx index 5e55e5761ccb3..f05bf052683f3 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverLinks.integration.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverLinks.integration.test.tsx @@ -18,17 +18,17 @@ describe('DiscoverLinks', () => { it('produces the correct URL for a transaction', async () => { const transaction = { transaction: { - id: '8b60bd32ecc6e150' + id: '8b60bd32ecc6e150', }, trace: { - id: '8b60bd32ecc6e1506735a8b6cfcf175c' - } + id: '8b60bd32ecc6e1506735a8b6cfcf175c', + }, } as Transaction; const href = await getRenderedHref( () => , { - search: '?rangeFrom=now/w&rangeTo=now' + search: '?rangeFrom=now/w&rangeTo=now', } as Location ); @@ -40,12 +40,12 @@ describe('DiscoverLinks', () => { it('produces the correct URL for a span', async () => { const span = { span: { - id: 'test-span-id' - } + id: 'test-span-id', + }, } as Span; const href = await getRenderedHref(() => , { - search: '?rangeFrom=now/w&rangeTo=now' + search: '?rangeFrom=now/w&rangeTo=now', } as Location); expect(href).toEqual( @@ -56,16 +56,16 @@ describe('DiscoverLinks', () => { test('DiscoverErrorLink should produce the correct URL', async () => { const error = { service: { - name: 'service-name' + name: 'service-name', }, error: { - grouping_key: 'grouping-key' - } + grouping_key: 'grouping-key', + }, } as APMError; const href = await getRenderedHref( () => , { - search: '?rangeFrom=now/w&rangeTo=now' + search: '?rangeFrom=now/w&rangeTo=now', } as Location ); @@ -77,17 +77,17 @@ describe('DiscoverLinks', () => { test('DiscoverErrorLink should include optional kuery string in URL', async () => { const error = { service: { - name: 'service-name' + name: 'service-name', }, error: { - grouping_key: 'grouping-key' - } + grouping_key: 'grouping-key', + }, } as APMError; const href = await getRenderedHref( () => , { - search: '?rangeFrom=now/w&rangeTo=now' + search: '?rangeFrom=now/w&rangeTo=now', } as Location ); diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionButton.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionButton.test.tsx index 5769ca34a9a87..02e0e72826f3a 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionButton.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionButton.test.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { Transaction } from '../../../../../../typings/es_schemas/ui/transaction'; import { DiscoverTransactionLink, - getDiscoverQuery + getDiscoverQuery, } from '../DiscoverTransactionLink'; import mockTransaction from './mockTransaction.json'; diff --git a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionLink.test.tsx index 2f65cf7734631..1fa9a0baa7265 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/DiscoverLinks/__test__/DiscoverTransactionLink.test.tsx @@ -12,11 +12,11 @@ import { getDiscoverQuery } from '../DiscoverTransactionLink'; function getMockTransaction() { return { transaction: { - id: '8b60bd32ecc6e150' + id: '8b60bd32ecc6e150', }, trace: { - id: '8b60bd32ecc6e1506735a8b6cfcf175c' - } + id: '8b60bd32ecc6e1506735a8b6cfcf175c', + }, } as Transaction; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/InfraLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/InfraLink.test.tsx index 0b39aa9ada756..d3d67bfd3aab9 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/InfraLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/InfraLink.test.tsx @@ -15,7 +15,7 @@ test('InfraLink produces the correct URL', async () => { ), { - search: '?rangeFrom=now-5h&rangeTo=now-2h' + search: '?rangeFrom=now-5h&rangeTo=now-2h', } as Location ); diff --git a/x-pack/plugins/apm/public/components/shared/Links/InfraLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/InfraLink.tsx index 0ae9f64dc24ef..f02bd921f40bf 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/InfraLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/InfraLink.tsx @@ -30,7 +30,7 @@ export const getInfraHref = ({ app, basePath, query, - path + path, }: { app: InfraAppId; basePath: AppMountContextBasePath; @@ -40,7 +40,7 @@ export const getInfraHref = ({ const nextSearch = fromQuery(query); return url.format({ pathname: basePath.prepend(`/app/${app}${path || ''}`), - search: nextSearch + search: nextSearch, }); }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.test.tsx index fad534e11f645..8768ce9d62e6f 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.test.tsx @@ -12,7 +12,7 @@ import { KibanaLink } from './KibanaLink'; describe('KibanaLink', () => { it('produces the correct URL', async () => { const href = await getRenderedHref(() => , { - search: '?rangeFrom=now-5h&rangeTo=now-2h' + search: '?rangeFrom=now-5h&rangeTo=now-2h', } as Location); expect(href).toMatchInlineSnapshot(`"/basepath/app/kibana#/some/path"`); }); diff --git a/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.tsx index 37e2c06d2f701..8aa0d4f5a3354 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/KibanaLink.tsx @@ -18,7 +18,7 @@ export function KibanaLink({ path, ...rest }: Props) { const { core } = useApmPluginContext(); const href = url.format({ pathname: core.http.basePath.prepend('/app/kibana'), - hash: path + hash: path, }); return ; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx index b085fab2b7ed6..346748964d529 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLJobLink.tsx @@ -20,13 +20,13 @@ type Props = (PropsServiceName | PropsJobId) & { external?: boolean; }; -export const MLJobLink: React.FC = props => { +export const MLJobLink: React.FC = (props) => { const jobId = 'jobId' in props ? props.jobId : getMlJobId(props.serviceName, props.transactionType); const query = { - ml: { jobIds: [jobId] } + ml: { jobIds: [jobId] }, }; return ( diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.test.tsx index d38d61fede37a..840846adae019 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.test.tsx @@ -15,7 +15,7 @@ test('MLLink produces the correct URL', async () => { ), { - search: '?rangeFrom=now-5h&rangeTo=now-2h' + search: '?rangeFrom=now-5h&rangeTo=now-2h', } as Location ); diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.tsx index 7b57c193d896d..5e2d728716704 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLLink.tsx @@ -39,7 +39,7 @@ export function MLLink({ children, path = '', query = {}, external }: Props) { const href = url.format({ pathname: core.http.basePath.prepend('/app/ml'), - hash: `${path}?_g=${rison.encode(risonQuery as RisonValue)}` + hash: `${path}?_g=${rison.encode(risonQuery as RisonValue)}`, }); return ( diff --git a/x-pack/plugins/apm/public/components/shared/Links/SetupInstructionsLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/SetupInstructionsLink.tsx index 42e8487d597b4..e85605e42981c 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/SetupInstructionsLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/SetupInstructionsLink.tsx @@ -12,13 +12,13 @@ import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; const SETUP_INSTRUCTIONS_LABEL = i18n.translate( 'xpack.apm.setupInstructionsButtonLabel', { - defaultMessage: 'Setup Instructions' + defaultMessage: 'Setup Instructions', } ); // renders a filled button or a link as a kibana link to setup instructions export function SetupInstructionsLink({ - buttonFill = false + buttonFill = false, }: { buttonFill?: boolean; }) { diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.test.tsx index a319860c75b62..d6518e76aa5e9 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.test.tsx @@ -13,7 +13,7 @@ test('APMLink should produce the correct URL', async () => { const href = await getRenderedHref( () => , { - search: '?rangeFrom=now-5h&rangeTo=now-2h' + search: '?rangeFrom=now-5h&rangeTo=now-2h', } as Location ); @@ -26,7 +26,7 @@ test('APMLink should retain current kuery value if it exists', async () => { const href = await getRenderedHref( () => , { - search: '?kuery=host.hostname~20~3A~20~22fakehostname~22' + search: '?kuery=host.hostname~20~3A~20~22fakehostname~22', } as Location ); @@ -44,7 +44,7 @@ test('APMLink should overwrite current kuery value if new kuery value is provide /> ), { - search: '?kuery=host.hostname~20~3A~20~22fakehostname~22' + search: '?kuery=host.hostname~20~3A~20~22fakehostname~22', } as Location ); diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx index 29b3fff2050c8..3aff241c6dee2 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx @@ -26,7 +26,7 @@ export const PERSISTENT_APM_PARAMS = [ 'rangeTo', 'refreshPaused', 'refreshInterval', - 'environment' + 'environment', ]; export function getAPMHref( @@ -38,13 +38,13 @@ export function getAPMHref( const nextQuery = { ...TIMEPICKER_DEFAULTS, ...pick(currentQuery, PERSISTENT_APM_PARAMS), - ...query + ...query, }; const nextSearch = fromQuery(nextQuery); return url.format({ pathname: '', - hash: `${path}?${nextSearch}` + hash: `${path}?${nextSearch}`, }); } diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx index ebcf220994cda..684531d50897c 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx @@ -30,7 +30,7 @@ const ErrorOverviewLink = ({ serviceName, query, ...rest }: Props) => { path={`/services/${serviceName}/errors`} query={{ ...persistedFilters, - ...query + ...query, }} {...rest} /> diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.test.ts b/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.test.ts index 3daeb3d09951d..1f772e0734404 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.test.ts +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.test.ts @@ -9,9 +9,9 @@ jest.mock('../../../app/Main/route_config/index.tsx', () => ({ routes: [ { name: 'link_to_trace', - path: '/link-to/trace/:traceId' - } - ] + path: '/link-to/trace/:traceId', + }, + ], })); describe('ExternalLinks', () => { diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.ts b/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.ts index ff5e4744dc19d..40b51098c4094 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.ts +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ExternalLinks.ts @@ -8,7 +8,7 @@ import url from 'url'; export const getTraceUrl = ({ traceId, rangeFrom, - rangeTo + rangeTo, }: { traceId: string; rangeFrom: string; @@ -16,6 +16,6 @@ export const getTraceUrl = ({ }) => { return url.format({ pathname: `/link-to/trace/${traceId}`, - query: { rangeFrom, rangeTo } + query: { rangeFrom, rangeTo }, }); }; diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx index 6278336751851..c7eba1984472e 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/TransactionDetailLink.tsx @@ -41,7 +41,7 @@ export const TransactionDetailLink = ({ transactionId, transactionName, transactionType, - ...persistedFilters + ...persistedFilters, }} {...rest} /> diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/agentConfigurationLinks.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/agentConfigurationLinks.tsx index 6885e44f1ad1f..11ce8fb911a20 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/agentConfigurationLinks.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/agentConfigurationLinks.tsx @@ -16,7 +16,7 @@ export function editAgentConfigurationHref( // ignoring because `name` has not been added to url params. Related: https://github.com/elastic/kibana/issues/51963 // @ts-ignore name: configService.name, - environment: configService.environment + environment: configService.environment, }); } diff --git a/x-pack/plugins/apm/public/components/shared/Links/rison_helpers.ts b/x-pack/plugins/apm/public/components/shared/Links/rison_helpers.ts index da273f7ad4242..434bd285029ab 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/rison_helpers.ts +++ b/x-pack/plugins/apm/public/components/shared/Links/rison_helpers.ts @@ -23,16 +23,16 @@ export function getTimepickerRisonData(currentSearch: Location['search']) { const currentQuery = toQuery(currentSearch); const nextQuery = { ...TIMEPICKER_DEFAULTS, - ...currentQuery + ...currentQuery, }; return { time: { from: encodeURIComponent(nextQuery.rangeFrom), - to: encodeURIComponent(nextQuery.rangeTo) + to: encodeURIComponent(nextQuery.rangeTo), }, refreshInterval: { pause: String(nextQuery.refreshPaused), - value: String(nextQuery.refreshInterval) - } + value: String(nextQuery.refreshInterval), + }, }; } diff --git a/x-pack/plugins/apm/public/components/shared/Links/url_helpers.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/url_helpers.test.tsx index 6fc5605492208..9bdc3043e9531 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/url_helpers.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/url_helpers.test.tsx @@ -10,7 +10,7 @@ describe('toQuery', () => { it('should parse string to object', () => { expect(toQuery('?foo=bar&name=john%20doe')).toEqual({ foo: 'bar', - name: 'john doe' + name: 'john doe', }); }); }); @@ -21,7 +21,7 @@ describe('fromQuery', () => { fromQuery({ a: true, b: 5000, - c: ':' + c: ':', }) ).toEqual('a=true&b=5000&c=:'); }); @@ -32,7 +32,7 @@ describe('fromQuery', () => { a: '@', b: '.', c: ';', - d: ' ' + d: ' ', }) ).toEqual('a=%40&b=.&c=%3B&d=%20'); }); @@ -41,7 +41,7 @@ describe('fromQuery', () => { expect( fromQuery({ a: undefined, - b: null + b: null, }) ).toEqual('a=&b='); }); @@ -49,7 +49,7 @@ describe('fromQuery', () => { it('should handle arrays', () => { expect( fromQuery({ - arr: ['a', 'b'] + arr: ['a', 'b'], }) ).toEqual('arr=a%2Cb'); }); @@ -58,7 +58,7 @@ describe('fromQuery', () => { expect( fromQuery({ traceId: 'bar', - transactionId: 'john doe' + transactionId: 'john doe', }) ).toEqual('traceId=bar&transactionId=john%20doe'); }); @@ -67,7 +67,7 @@ describe('fromQuery', () => { expect( fromQuery({ rangeFrom: '2019-03-03T12:00:00.000Z', - rangeTo: '2019-03-05T12:00:00.000Z' + rangeTo: '2019-03-05T12:00:00.000Z', }) ).toEqual( 'rangeFrom=2019-03-03T12:00:00.000Z&rangeTo=2019-03-05T12:00:00.000Z' @@ -79,7 +79,7 @@ describe('fromQuery', () => { fromQuery({ flyoutDetailTab: undefined, refreshPaused: true, - refreshInterval: 5000 + refreshInterval: 5000, }) ).toEqual('flyoutDetailTab=&refreshPaused=true&refreshInterval=5000'); }); diff --git a/x-pack/plugins/apm/public/components/shared/Links/url_helpers.ts b/x-pack/plugins/apm/public/components/shared/Links/url_helpers.ts index b296302c47edf..3f98fc449e8c1 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/url_helpers.ts +++ b/x-pack/plugins/apm/public/components/shared/Links/url_helpers.ts @@ -14,7 +14,7 @@ export function toQuery(search?: string): APMQueryParamsRaw { } export function fromQuery(query: Record) { - const encodedQuery = url.encodeQuery(query, value => + const encodedQuery = url.encodeQuery(query, (value) => encodeURIComponent(value).replace(/%3A/g, ':') ); diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx index 01d2d56b6d142..9191f4e797637 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/Filter/FilterBadgeList.tsx @@ -22,7 +22,7 @@ interface Props { const FilterBadgeList = ({ onRemove, value }: Props) => ( - {value.map(val => ( + {value.map((val) => (
{ public async updateBeatsData(beatsKBar?: string) { const beats = sortBy(await this.props.libs.beats.getAll(beatsKBar), 'id') || []; - const tags = await this.props.libs.tags.getTagsWithIds(flatten(beats.map(beat => beat.tags))); + const tags = await this.props.libs.tags.getTagsWithIds(flatten(beats.map((beat) => beat.tags))); this.setState({ tags, @@ -172,7 +172,7 @@ class BeatsPageComponent extends React.PureComponent { path={`/overview/enrolled_beats`} /> - {autocompleteProps => ( + {(autocompleteProps) => (
{ break; } }} - items={this.state.beats.map(beat => ({ + items={this.state.beats.map((beat) => ({ ...beat, - tags: (this.state.tags || []).filter(tag => beat.tags.includes(tag.id)), + tags: (this.state.tags || []).filter((tag) => beat.tags.includes(tag.id)), }))} ref={this.tableRef} type={BeatsTableType} @@ -348,7 +348,7 @@ class BeatsPageComponent extends React.PureComponent { const selectedIds = this.tableRef.current.state.selection.map((beat: any) => beat.id); const beats: CMBeat[] = []; selectedIds.forEach((id: any) => { - const beat = this.props.containers.beats.state.list.find(b => b.id === id); + const beat = this.props.containers.beats.state.list.find((b) => b.id === id); if (beat) { beats.push(beat); } diff --git a/x-pack/plugins/beats_management/public/pages/tag/create.tsx b/x-pack/plugins/beats_management/public/pages/tag/create.tsx index 65fe8bf5d52c1..881bb433b1d9a 100644 --- a/x-pack/plugins/beats_management/public/pages/tag/create.tsx +++ b/x-pack/plugins/beats_management/public/pages/tag/create.tsx @@ -72,7 +72,7 @@ class TagCreatePageComponent extends React.PureComponent< total: this.state.configuration_blocks.length, }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } @@ -82,13 +82,13 @@ class TagCreatePageComponent extends React.PureComponent< }); }} onConfigAddOrEdit={(block: ConfigurationBlock) => { - this.setState(previousState => ({ + this.setState((previousState) => ({ configuration_blocks: previousState.configuration_blocks.concat([block]), })); }} onConfigRemoved={(block: ConfigurationBlock) => { - this.setState(previousState => { - const selectedIndex = previousState.configuration_blocks.findIndex(c => { + this.setState((previousState) => { + const selectedIndex = previousState.configuration_blocks.findIndex((c) => { return isEqual(block, c); }); const blocks = [...previousState.configuration_blocks]; @@ -141,7 +141,7 @@ class TagCreatePageComponent extends React.PureComponent< ); } const createBlocksResponse = await this.props.libs.configBlocks.upsert( - this.state.configuration_blocks.map(block => ({ ...block, tag: this.state.tag.id })) + this.state.configuration_blocks.map((block) => ({ ...block, tag: this.state.tag.id })) ); const creationError = createBlocksResponse.results.reduce( (err: string, resp) => (!err ? (err = resp.error ? resp.error.message : '') : err), @@ -155,7 +155,7 @@ class TagCreatePageComponent extends React.PureComponent< }; private getNumExclusiveConfigurationBlocks = () => this.state.configuration_blocks - .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some(uniqueType => uniqueType === type)) + .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some((uniqueType) => uniqueType === type)) .reduce((acc, cur) => (cur ? acc + 1 : acc), 0); } diff --git a/x-pack/plugins/beats_management/public/pages/tag/edit.tsx b/x-pack/plugins/beats_management/public/pages/tag/edit.tsx index 918ae0bb6fcb2..10d7f7bbd7193 100644 --- a/x-pack/plugins/beats_management/public/pages/tag/edit.tsx +++ b/x-pack/plugins/beats_management/public/pages/tag/edit.tsx @@ -88,15 +88,15 @@ class TagEditPageComponent extends React.PureComponent< await this.loadAttachedBeats(); }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } attachedBeats={ - (this.state.attachedBeats || []).map(beat => ({ + (this.state.attachedBeats || []).map((beat) => ({ ...beat, tags: flatten( - beat.tags.map(tagId => this.state.beatsTags.filter(tag => tag.id === tagId)) + beat.tags.map((tagId) => this.state.beatsTags.filter((tag) => tag.id === tagId)) ), })) as any } @@ -186,7 +186,7 @@ class TagEditPageComponent extends React.PureComponent< private loadAttachedBeats = async () => { const beats = await this.props.libs.beats.getBeatsWithTag(this.props.match.params.tagid); const beatsTags = await this.props.libs.tags.getTagsWithIds( - flatten(beats.map(beat => beat.tags)) + flatten(beats.map((beat) => beat.tags)) ); this.setState({ attachedBeats: beats, @@ -199,7 +199,7 @@ class TagEditPageComponent extends React.PureComponent< }; private getNumExclusiveConfigurationBlocks = () => this.state.configuration_blocks.list - .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some(uniqueType => uniqueType === type)) + .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some((uniqueType) => uniqueType === type)) .reduce((acc, cur) => (cur ? acc + 1 : acc), 0); } diff --git a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx index a78bf3fa7cf8e..5b307692e8a4c 100644 --- a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx @@ -17,7 +17,7 @@ type Props = AppPageProps & { intl: InjectedIntl; }; -const InitialWalkthroughPageComponent: React.FC = props => { +const InitialWalkthroughPageComponent: React.FC = (props) => { if (props.location.pathname === '/walkthrough/initial') { return ( { total: this.state.configuration_blocks.length, }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } @@ -63,13 +63,13 @@ export class InitialTagPage extends Component { }); }} onConfigAddOrEdit={(block: ConfigurationBlock) => { - this.setState(previousState => ({ + this.setState((previousState) => ({ configuration_blocks: previousState.configuration_blocks.concat([block]), })); }} onConfigRemoved={(block: ConfigurationBlock) => { - this.setState(previousState => { - const selectedIndex = previousState.configuration_blocks.findIndex(c => { + this.setState((previousState) => { + const selectedIndex = previousState.configuration_blocks.findIndex((c) => { return isEqual(block, c); }); const blocks = [...previousState.configuration_blocks]; @@ -121,7 +121,7 @@ export class InitialTagPage extends Component { ); } const createBlocksResponse = await this.props.libs.configBlocks.upsert( - this.state.configuration_blocks.map(block => ({ ...block, tag: this.state.tag.id })) + this.state.configuration_blocks.map((block) => ({ ...block, tag: this.state.tag.id })) ); const creationError = createBlocksResponse.results.reduce( (err: string, resp) => (!err ? (err = resp.error ? resp.error.message : '') : err), diff --git a/x-pack/plugins/beats_management/public/router.tsx b/x-pack/plugins/beats_management/public/router.tsx index ec7aceaa6d747..c23d0dd4aca99 100644 --- a/x-pack/plugins/beats_management/public/router.tsx +++ b/x-pack/plugins/beats_management/public/router.tsx @@ -62,7 +62,7 @@ export class AppRouter extends Component { {/* License check (UI displays when license exists but is expired) */} {get(this.props.libs.framework.info, 'license.expired', true) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -73,7 +73,7 @@ export class AppRouter extends Component { {/* Ensure security is eanabled for elastic and kibana */} {!get(this.props.libs.framework.info, 'security.enabled', true) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -86,7 +86,7 @@ export class AppRouter extends Component { ['beats_admin'].concat(this.props.libs.framework.info.settings.defaultUserRoles) ) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -97,7 +97,7 @@ export class AppRouter extends Component { {/* If there are no beats or tags yet, redirect to the walkthrough */} {countOfEverything === 0 && ( + render={(props) => !props.location.pathname.includes('/walkthrough') ? ( ) : null diff --git a/x-pack/plugins/beats_management/public/utils/random_eui_color.ts b/x-pack/plugins/beats_management/public/utils/random_eui_color.ts index 5c358941f4bc3..edc3e2863a89a 100644 --- a/x-pack/plugins/beats_management/public/utils/random_eui_color.ts +++ b/x-pack/plugins/beats_management/public/utils/random_eui_color.ts @@ -8,8 +8,8 @@ import { sample } from 'lodash'; export const randomEUIColor = (euiVars: any) => { const rgb = sample( Object.keys(euiVars) - .filter(key => key.startsWith('euiColorVis')) - .map(key => (euiVars as any)[key]) + .filter((key) => key.startsWith('euiColorVis')) + .map((key) => (euiVars as any)[key]) ); const matchedrgb = rgb.match( diff --git a/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts b/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts index edf11f5a25c08..09b5e29cba87e 100644 --- a/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts +++ b/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts @@ -7,4 +7,4 @@ import { functions as browserFns } from '../../canvas_plugin_src/functions/browser'; import { ExpressionFunction } from '../../../../../src/plugins/expressions'; -export const functionSpecs = browserFns.map(fn => new ExpressionFunction(fn())); +export const functionSpecs = browserFns.map((fn) => new ExpressionFunction(fn())); diff --git a/x-pack/plugins/canvas/__tests__/fixtures/kibana.js b/x-pack/plugins/canvas/__tests__/fixtures/kibana.js index 4503adcec0c2c..e32041cd99f1a 100644 --- a/x-pack/plugins/canvas/__tests__/fixtures/kibana.js +++ b/x-pack/plugins/canvas/__tests__/fixtures/kibana.js @@ -24,10 +24,10 @@ export class Plugin { elasticsearch: mockElasticsearch, }, config: () => ({ - get: key => get(config, key), - has: key => has(config, key), + get: (key) => get(config, key), + has: (key) => has(config, key), }), - route: def => this.routes.push(def), + route: (def) => this.routes.push(def), }; const { init } = this.props; diff --git a/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js b/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js index 4f078169f699f..dc07932e70e0f 100644 --- a/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js +++ b/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js @@ -9,7 +9,7 @@ import { mapValues } from 'lodash'; // It takes a function spec and passes in default args into the spec fn export const functionWrapper = (fnSpec, mockReduxStore) => { const spec = fnSpec(); - const defaultArgs = mapValues(spec.args, argSpec => { + const defaultArgs = mapValues(spec.args, (argSpec) => { return argSpec.default; }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts index ec3b8a7798be1..961b0cd034248 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts @@ -66,7 +66,7 @@ const initializeElementFactories = [metricElementInitializer]; export const initializeElements: SetupInitializer = (core, plugins) => { const specs = [ ...elementSpecs, - ...initializeElementFactories.map(factory => factory(core, plugins)), + ...initializeElementFactories.map((factory) => factory(core, plugins)), ]; return applyElementStrings(specs); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts index 1e13ebdee3e4b..4a01df3b0ac50 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts @@ -24,7 +24,7 @@ export function location(): ExpressionFunctionDefinition<'location', null, {}, P args: {}, help, fn: () => { - return new Promise(resolve => { + return new Promise((resolve) => { function createLocation(geoposition: Position) { const { latitude, longitude } = geoposition.coords; return resolve({ diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js index 27ea290fb4dcc..71b6af6739408 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js @@ -31,7 +31,7 @@ describe('markdown', () => { it('compiles and concatenates handlebars expressions using context', () => { let expectedContent = 'Columns:'; - testTable.columns.map(col => (expectedContent += ` ${col.name}`)); + testTable.columns.map((col) => (expectedContent += ` ${col.name}`)); const result = fn(testTable, { content: ['Columns:', '{{#each columns}} {{name}}{{/each}}'], diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts index e94b9f201a174..41323a82f4ee0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts @@ -62,7 +62,7 @@ export function markdown(): ExpressionFunctionDefinition< }, }, fn: (input, args) => { - const compileFunctions = args.content.map(str => + const compileFunctions = args.content.map((str) => Handlebars.compile(String(str), { knownHelpersOnly: true }) ); const ctx = { @@ -76,7 +76,7 @@ export function markdown(): ExpressionFunctionDefinition< type: 'render', as: 'markdown', value: { - content: compileFunctions.map(fn => fn(ctx)).join(''), + content: compileFunctions.map((fn) => fn(ctx)).join(''), font: args.font, openLinksInNewTab: args.openLinksInNewTab, }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js index d53fe94d4a838..17f9defa15dc3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js @@ -18,9 +18,7 @@ describe('progress', () => { it('returns a render as progress', () => { const result = fn(0.2); - expect(result) - .to.have.property('type', 'render') - .and.to.have.property('as', 'progress'); + expect(result).to.have.property('type', 'render').and.to.have.property('as', 'progress'); }); it('sets the progress to context', () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts index e6739a71b1608..68c1957c808a3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts @@ -51,7 +51,7 @@ export function alterColumn(): ExpressionFunctionDefinition< return input; } - const column = input.columns.find(col => col.name === args.column); + const column = input.columns.find((col) => col.name === args.column); if (!column) { throw errors.columnNotFound(args.column); } @@ -94,7 +94,7 @@ export function alterColumn(): ExpressionFunctionDefinition< })(); } - const rows = input.rows.map(row => ({ + const rows = input.rows.map((row) => ({ ...omit(row, column.name), [name]: handler(row[column.name]), })); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts index 71c5376428a79..63d3102a19e9a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts @@ -43,27 +43,27 @@ export function columns(): ExpressionFunctionDefinition< let result = { ...input }; if (exclude) { - const fields = exclude.split(',').map(field => field.trim()); - const cols = contextColumns.filter(col => !fields.includes(col.name)); - const rows = cols.length > 0 ? contextRows.map(row => omit(row, fields)) : []; + const fields = exclude.split(',').map((field) => field.trim()); + const cols = contextColumns.filter((col) => !fields.includes(col.name)); + const rows = cols.length > 0 ? contextRows.map((row) => omit(row, fields)) : []; result = { rows, columns: cols, ...rest }; } if (include) { - const fields = include.split(',').map(field => field.trim()); + const fields = include.split(',').map((field) => field.trim()); // const columns = result.columns.filter(col => fields.includes(col.name)); // Include columns in the order the user specified const cols: DatatableColumn[] = []; - fields.forEach(field => { + fields.forEach((field) => { const column = find(result.columns, { name: field }); if (column) { cols.push(column); } }); - const rows = cols.length > 0 ? result.rows.map(row => pick(row, fields)) : []; + const rows = cols.length > 0 ? result.rows.map((row) => pick(row, fields)) : []; result = { rows, columns: cols, ...rest }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts index d1302a1e579a1..bc87d6793e2f0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts @@ -14,6 +14,6 @@ export function context(): ExpressionFunctionDefinition<'context', unknown, {}, name: 'context', help, args: {}, - fn: obj => obj, + fn: (obj) => obj, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts index 5f0c848d76708..0fe45243ce721 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts @@ -23,6 +23,6 @@ export function doFn(): ExpressionFunctionDefinition<'do', unknown, Arguments, u help: argHelp.fn, }, }, - fn: context => context, + fn: (context) => context, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts index 29a277283494a..7231f01671e02 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts @@ -53,7 +53,7 @@ export function dropdownControl(): ExpressionFunctionDefinition< let choices = []; if (input.rows[0][valueColumn]) { - choices = uniq(input.rows.map(row => row[valueColumn])).sort(); + choices = uniq(input.rows.map((row) => row[valueColumn])).sort(); } const column = filterColumn || valueColumn; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js index 2f44655f60e44..179be8aff2e19 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js @@ -8,29 +8,29 @@ import { functionWrapper } from '../../../__tests__/helpers/function_wrapper'; import { testTable } from './__tests__/fixtures/test_tables'; import { filterrows } from './filterrows'; -const inStock = datatable => datatable.rows[0].in_stock; +const inStock = (datatable) => datatable.rows[0].in_stock; const returnFalse = () => false; describe('filterrows', () => { const fn = functionWrapper(filterrows); it('returns a datable', () => { - return fn(testTable, { fn: inStock }).then(result => { + return fn(testTable, { fn: inStock }).then((result) => { expect(result).toHaveProperty('type', 'datatable'); }); }); it('keeps rows that evaluate to true and removes rows that evaluate to false', () => { - const inStockRows = testTable.rows.filter(row => row.in_stock); + const inStockRows = testTable.rows.filter((row) => row.in_stock); - return fn(testTable, { fn: inStock }).then(result => { + return fn(testTable, { fn: inStock }).then((result) => { expect(result.columns).toEqual(testTable.columns); expect(result.rows).toEqual(inStockRows); }); }); it('returns datatable with no rows when no rows meet function condition', () => { - return fn(testTable, { fn: returnFalse }).then(result => { + return fn(testTable, { fn: returnFalse }).then((result) => { expect(result.rows).toEqual([]); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts index 17d5211588238..1f8b9f4c238cf 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts @@ -35,7 +35,7 @@ export function filterrows(): ExpressionFunctionDefinition< }, }, fn(input, { fn }) { - const checks = input.rows.map(row => + const checks = input.rows.map((row) => fn({ ...input, rows: [row], @@ -43,9 +43,9 @@ export function filterrows(): ExpressionFunctionDefinition< ); return Promise.all(checks) - .then(results => input.rows.filter((row, i) => results[i])) + .then((results) => input.rows.filter((row, i) => results[i])) .then( - rows => + (rows) => ({ ...input, rows, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts index 7f8a7b525180c..fd2b8c6e5d5e4 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts @@ -56,7 +56,7 @@ export function joinRows(): ExpressionFunctionDefinition<'joinRows', Datatable, }, }, fn: (input, { column, separator, quote, distinct }) => { - const columnMatch = input.columns.find(col => col.name === column); + const columnMatch = input.columns.find((col) => col.name === column); if (!columnMatch) { throw errors.columnNotFound(column); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js index b170ebafd61c0..e5ef06d1503ee 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js @@ -8,13 +8,13 @@ import { functionWrapper } from '../../../__tests__/helpers/function_wrapper'; import { testTable, emptyTable } from './__tests__/fixtures/test_tables'; import { mapColumn } from './mapColumn'; -const pricePlusTwo = datatable => Promise.resolve(datatable.rows[0].price + 2); +const pricePlusTwo = (datatable) => Promise.resolve(datatable.rows[0].price + 2); describe('mapColumn', () => { const fn = functionWrapper(mapColumn); it('returns a datatable with a new column with the values from mapping a function over each row in a datatable', () => { - return fn(testTable, { name: 'pricePlusTwo', expression: pricePlusTwo }).then(result => { + return fn(testTable, { name: 'pricePlusTwo', expression: pricePlusTwo }).then((result) => { const arbitraryRowIndex = 2; expect(result.type).toBe('datatable'); @@ -28,7 +28,7 @@ describe('mapColumn', () => { }); it('overwrites existing column with the new column if an existing column name is provided', () => { - return fn(testTable, { name: 'name', expression: pricePlusTwo }).then(result => { + return fn(testTable, { name: 'name', expression: pricePlusTwo }).then((result) => { const nameColumnIndex = result.columns.findIndex(({ name }) => name === 'name'); const arbitraryRowIndex = 4; @@ -41,7 +41,7 @@ describe('mapColumn', () => { }); it('adds a column to empty tables', () => { - return fn(emptyTable, { name: 'name', expression: pricePlusTwo }).then(result => { + return fn(emptyTable, { name: 'name', expression: pricePlusTwo }).then((result) => { expect(result.type).toBe('datatable'); expect(result.columns).toHaveLength(1); expect(result.columns[0]).toHaveProperty('name', 'name'); @@ -51,7 +51,7 @@ describe('mapColumn', () => { describe('expression', () => { it('maps null values to the new column', () => { - return fn(testTable, { name: 'empty' }).then(result => { + return fn(testTable, { name: 'empty' }).then((result) => { const emptyColumnIndex = result.columns.findIndex(({ name }) => name === 'empty'); const arbitraryRowIndex = 8; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts index d8b15a65252e6..7dd309cba5c64 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts @@ -45,18 +45,18 @@ export function mapColumn(): ExpressionFunctionDefinition< const expression = args.expression || (() => Promise.resolve(null)); const columns = [...input.columns]; - const rowPromises = input.rows.map(row => { + const rowPromises = input.rows.map((row) => { return expression({ type: 'datatable', columns, rows: [row], - }).then(val => ({ + }).then((val) => ({ ...row, [args.name]: val, })); }); - return Promise.all(rowPromises).then(rows => { + return Promise.all(rowPromises).then((rows) => { const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); const type = rows.length ? getType(rows[0][args.name]) : 'null'; const newColumn = { name: args.name, type }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts index dfbb37be0797c..7f84dc54d8092 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts @@ -43,7 +43,7 @@ export function math(): ExpressionFunctionDefinition<'math', Input, Arguments, n const mathContext = isDatatable(input) ? pivotObjectArray( input.rows, - input.columns.map(col => col.name) + input.columns.map((col) => col.name) ) : { value: input }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js index f1cccd1d8dda4..4ef6583096213 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js @@ -56,7 +56,7 @@ describe('pie', () => { describe('seriesStyle', () => { it('sets the color for a specific series', () => { const result = fn(testPie, { seriesStyle: [seriesStyle] }).value; - const seriesIndex = result.data.findIndex(series => series.label === seriesStyle.label); + const seriesIndex = result.data.findIndex((series) => series.label === seriesStyle.label); const resultSeries = result.data[seriesIndex]; expect(resultSeries).toHaveProperty('color', seriesStyle.color); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts index 36f1bf85b97e7..6cb64a43ea582 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts @@ -141,7 +141,7 @@ export function pie(): ExpressionFunctionDefinition<'pie', PointSeries, Argument const data: PieData[] = map(groupBy(input.rows, 'color'), (series, label = '') => { const item: PieData = { label, - data: series.map(point => point.size || 1), + data: series.map((point) => point.size || 1), }; const style = seriesStyles[label]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js index 6ce2978b75d56..d983cb7429863 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js @@ -66,7 +66,7 @@ describe('plot', () => { describe('seriesStyle', () => { it('sets the seriesStyle for a specific series', () => { const result = fn(testPlot, { seriesStyle: [seriesStyle] }).value; - const seriesIndex = result.data.findIndex(series => series.label === seriesStyle.label); + const seriesIndex = result.data.findIndex((series) => series.label === seriesStyle.label); const resultSeries = result.data[seriesIndex]; expect(resultSeries.lines).toHaveProperty('lineWidth', seriesStyle.lines); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts index 64fa1b259ade6..4839db047c871 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts @@ -20,7 +20,7 @@ export const getTickHash = (columns: PointSeriesColumns, rows: DatatableRow[]) = }; if (get(columns, 'x.type') === 'string') { - sortBy(rows, ['x']).forEach(row => { + sortBy(rows, ['x']).forEach((row) => { if (!ticks.x.hash[row.x]) { ticks.x.hash[row.x] = ticks.x.counter++; } @@ -30,7 +30,7 @@ export const getTickHash = (columns: PointSeriesColumns, rows: DatatableRow[]) = if (get(columns, 'y.type') === 'string') { sortBy(rows, ['y']) .reverse() - .forEach(row => { + .forEach((row) => { if (!ticks.y.hash[row.y]) { ticks.y.hash[row.y] = ticks.y.counter++; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts index 34e5d9f600d8d..e8214ca8eaf9f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts @@ -96,7 +96,7 @@ export function plot(): ExpressionFunctionDefinition<'plot', PointSeries, Argume return { ...flotStyle, label, - data: series.map(point => { + data: series.map((point) => { const attrs: { size?: number; text?: string; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js index 59c76e594a40a..2dfb9eeea76bc 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js @@ -11,7 +11,7 @@ import { ply } from './ply'; const errors = getFunctionErrors().ply; -const averagePrice = datatable => { +const averagePrice = (datatable) => { const average = datatable.rows.reduce((sum, row) => sum + row.price, 0) / datatable.rows.length; return Promise.resolve({ @@ -21,8 +21,8 @@ const averagePrice = datatable => { }); }; -const doublePrice = datatable => { - const newRows = datatable.rows.map(row => ({ double_price: row.price * 2 })); +const doublePrice = (datatable) => { + const newRows = datatable.rows.map((row) => ({ double_price: row.price * 2 })); return Promise.resolve({ type: 'datatable', @@ -31,7 +31,7 @@ const doublePrice = datatable => { }); }; -const rowCount = datatable => { +const rowCount = (datatable) => { return Promise.resolve({ type: 'datatable', columns: [{ name: 'row_count', type: 'number' }], @@ -50,7 +50,7 @@ describe('ply', () => { const arbitaryRowIndex = 0; return fn(testTable, { by: ['name', 'in_stock'], expression: [averagePrice, rowCount] }).then( - result => { + (result) => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([ { name: 'name', type: 'string' }, @@ -66,12 +66,12 @@ describe('ply', () => { describe('missing args', () => { it('returns the original datatable if both args are missing', () => { - return fn(testTable).then(result => expect(result).toEqual(testTable)); + return fn(testTable).then((result) => expect(result).toEqual(testTable)); }); describe('by', () => { it('passes the entire context into the expression when no columns are provided', () => { - return fn(testTable, { expression: [rowCount] }).then(result => + return fn(testTable, { expression: [rowCount] }).then((result) => expect(result).toEqual({ type: 'datatable', rows: [{ row_count: testTable.rows.length }], @@ -95,7 +95,7 @@ describe('ply', () => { it('returns the original datatable grouped by the specified columns', () => { const arbitaryRowIndex = 6; - return fn(testTable, { by: ['price', 'quantity'] }).then(result => { + return fn(testTable, { by: ['price', 'quantity'] }).then((result) => { expect(result.columns[0]).toHaveProperty('name', 'price'); expect(result.columns[1]).toHaveProperty('name', 'quantity'); expect(result.rows[arbitaryRowIndex]).toHaveProperty('price'); @@ -104,7 +104,7 @@ describe('ply', () => { }); it('throws when row counts do not match across resulting datatables', () => { - return fn(testTable, { by: ['name'], expression: [doublePrice, rowCount] }).catch(e => + return fn(testTable, { by: ['name'], expression: [doublePrice, rowCount] }).catch((e) => expect(e.message).toBe(errors.rowCountMismatch().message) ); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts index 391ff20461fb4..a541fbc89c634 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts @@ -47,8 +47,8 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, let originalDatatables: Datatable[]; if (args.by) { - byColumns = args.by.map(by => { - const column = input.columns.find(col => col.name === by); + byColumns = args.by.map((by) => { + const column = input.columns.find((col) => col.name === by); if (!column) { throw errors.columnNotFound(by); @@ -57,9 +57,9 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, return column; }); - const keyedDatatables = groupBy(input.rows, row => JSON.stringify(pick(row, args.by))); + const keyedDatatables = groupBy(input.rows, (row) => JSON.stringify(pick(row, args.by))); - originalDatatables = Object.values(keyedDatatables).map(rows => ({ + originalDatatables = Object.values(keyedDatatables).map((rows) => ({ ...input, rows, })); @@ -67,11 +67,11 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, originalDatatables = [input]; } - const datatablePromises = originalDatatables.map(originalDatatable => { + const datatablePromises = originalDatatables.map((originalDatatable) => { let expressionResultPromises = []; if (args.expression) { - expressionResultPromises = args.expression.map(expression => + expressionResultPromises = args.expression.map((expression) => expression(originalDatatable) ); } else { @@ -81,13 +81,13 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, return Promise.all(expressionResultPromises).then(combineAcross); }); - return Promise.all(datatablePromises).then(newDatatables => { + return Promise.all(datatablePromises).then((newDatatables) => { // Here we're just merging each for the by splits, so it doesn't actually matter if the rows are the same length const columns = combineColumns([byColumns].concat(map(newDatatables, 'columns'))); const rows = flatten( newDatatables.map((dt, i) => { const byColumnValues = pick(originalDatatables[i].rows[0], args.by); - return dt.rows.map(row => ({ + return dt.rows.map((row) => ({ ...byColumnValues, ...row, })); @@ -107,8 +107,8 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, function combineColumns(arrayOfColumnsArrays: DatatableColumn[][]) { return arrayOfColumnsArrays.reduce((resultingColumns, columns) => { if (columns) { - columns.forEach(column => { - if (resultingColumns.find(resultingColumn => resultingColumn.name === column.name)) { + columns.forEach((column) => { + if (resultingColumns.find((resultingColumn) => resultingColumn.name === column.name)) { return; } else { resultingColumns.push(column); @@ -128,7 +128,7 @@ function combineAcross(datatableArray: Datatable[]) { const targetRowLength = referenceTable.rows.length; // Sanity check - datatableArray.forEach(datatable => { + datatableArray.forEach((datatable) => { if (datatable.rows.length !== targetRowLength) { throw errors.rowCountMismatch(); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts index d1027f784c9a9..d6425c7db8544 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts @@ -18,6 +18,6 @@ export function rowCount(): ExpressionFunctionDefinition<'rowCount', Datatable, inputTypes: ['datatable'], help, args: {}, - fn: input => input.rows.length, + fn: (input) => input.rows.length, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js index e38bb76edabe2..ff11669db05f7 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js @@ -16,8 +16,8 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([...testTable.columns, { name: 'foo', type: 'string' }]); - expect(result.rows.every(row => typeof row.foo === 'string')).toBe(true); - expect(result.rows.every(row => row.foo === 'bar')).toBe(true); + expect(result.rows.every((row) => typeof row.foo === 'string')).toBe(true); + expect(result.rows.every((row) => row.foo === 'bar')).toBe(true); }); it('overwrites an existing column if provided an existing column name', () => { @@ -25,8 +25,8 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual(testTable.columns); - expect(result.rows.every(row => typeof row.name === 'string')).toBe(true); - expect(result.rows.every(row => row.name === 'John')).toBe(true); + expect(result.rows.every((row) => typeof row.name === 'string')).toBe(true); + expect(result.rows.every((row) => row.name === 'John')).toBe(true); }); it('adds a column with null values', () => { @@ -34,7 +34,7 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([...testTable.columns, { name: 'empty', type: 'null' }]); - expect(result.rows.every(row => row.empty === null)).toBe(true); + expect(result.rows.every((row) => row.empty === null)).toBe(true); }); it('adds a column to empty tables', () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts index 228d879c91a9c..9dd38dd57c677 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts @@ -45,7 +45,7 @@ export function staticColumn(): ExpressionFunctionDefinition< }, }, fn: (input, args) => { - const rows = input.rows.map(row => ({ ...row, [args.name]: args.value })); + const rows = input.rows.map((row) => ({ ...row, [args.name]: args.value })); const type = getType(args.value) as DatatableColumnType; const columns = [...input.columns]; const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js index 7fd83d6a2b742..7ecccdd5ee544 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js @@ -9,7 +9,7 @@ import { switchFn } from './switch'; describe('switch', () => { const fn = functionWrapper(switchFn); - const getter = value => () => value; + const getter = (value) => () => value; const mockCases = [ { type: 'case', @@ -37,7 +37,7 @@ describe('switch', () => { result: 5, }, ]; - const nonMatchingCases = mockCases.filter(c => !c.matches); + const nonMatchingCases = mockCases.filter((c) => !c.matches); describe('spec', () => { it('is a function', () => { @@ -80,7 +80,7 @@ describe('switch', () => { it('should return the first match', async () => { const context = 'foo'; const args = { case: mockCases.map(getter) }; - const firstMatch = mockCases.find(c => c.matches); + const firstMatch = mockCases.find((c) => c.matches); expect(await fn(context, args)).toBe(firstMatch.result); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js index 834b9d195856c..2edbba278ffde 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js @@ -14,11 +14,11 @@ const errors = getFunctionErrors().timefilter; let clock = null; -beforeEach(function() { +beforeEach(function () { clock = sinon.useFakeTimers(); }); -afterEach(function() { +afterEach(function () { clock.restore(); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts index 1eb0a7c74780c..2b229b8957ec1 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts @@ -93,12 +93,12 @@ export function esdocs(): ExpressionFunctionDefinition< } if (fields) { - const allFields = fields.split(',').map(field => field.trim()); - allFields.forEach(field => (query = query.field(field))); + const allFields = fields.split(',').map((field) => field.trim()); + allFields.forEach((field) => (query = query.field(field))); } if (sort) { - const [sortField, sortOrder] = sort.split(',').map(str => str.trim()); + const [sortField, sortOrder] = sort.split(',').map((str) => str.trim()); if (sortField) { query.order(`"${sortField}"`, sortOrder === 'asc'); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts index 17f0af4c9689e..54e48c8abf04b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts @@ -81,7 +81,7 @@ export function pointseries(): ExpressionFunctionDefinition< fn: (input, args) => { const errors = getFunctionErrors().pointseries; // Note: can't replace pivotObjectArray with datatableToMathContext, lose name of non-numeric columns - const columnNames = input.columns.map(col => col.name); + const columnNames = input.columns.map((col) => col.name); const mathScope = pivotObjectArray(input.rows, columnNames); const autoQuoteColumn = (col: string | null) => { if (!col || !columnNames.includes(col)) { @@ -97,7 +97,7 @@ export function pointseries(): ExpressionFunctionDefinition< // Separates args into dimensions and measures arrays // by checking if arg is a column reference (dimension) - keysOf(args).forEach(argName => { + keysOf(args).forEach((argName) => { const mathExp = autoQuoteColumn(args[argName]); if (mathExp != null && mathExp.trim() !== '') { @@ -175,7 +175,7 @@ export function pointseries(): ExpressionFunctionDefinition< // Measures // First group up all of the distinct dimensioned bits. Each of these will be reduced to just 1 value // for each measure - const measureKeys = groupBy(rows, row => + const measureKeys = groupBy(rows, (row) => dimensions .map(({ name }) => { const value = args[name]; @@ -185,13 +185,13 @@ export function pointseries(): ExpressionFunctionDefinition< ); // Then compute that 1 value for each measure - Object.values(measureKeys).forEach(valueRows => { + Object.values(measureKeys).forEach((valueRows) => { const subtable = { type: 'datatable', columns: input.columns, rows: valueRows }; const subScope = pivotObjectArray( subtable.rows, - subtable.columns.map(col => col.name) + subtable.columns.map((col) => col.name) ); - const measureValues = measureNames.map(measure => { + const measureValues = measureNames.map((measure) => { try { const ev = evaluate(args[measure], subScope); if (Array.isArray(ev)) { @@ -205,14 +205,14 @@ export function pointseries(): ExpressionFunctionDefinition< } }); - valueRows.forEach(row => { + valueRows.forEach((row) => { Object.assign(results[row[PRIMARY_KEY]], zipObject(measureNames, measureValues)); }); }); // It only makes sense to uniq the rows in a point series as 2 values can not exist in the exact same place at the same time. const resultingRows = uniqBy( - Object.values(results).map(row => omit(row, PRIMARY_KEY)), + Object.values(results).map((row) => omit(row, PRIMARY_KEY)), JSON.stringify ); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx index 3e94c0d7476f4..e4d4510d40f53 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx @@ -22,7 +22,7 @@ export interface Props { export const AdvancedFilter: FunctionComponent = ({ value = '', onChange, commit }) => ( { + onSubmit={(e) => { e.preventDefault(); commit(value); }} @@ -35,7 +35,7 @@ export const AdvancedFilter: FunctionComponent = ({ value = '', onChange, className="canvasAdvancedFilter__input" placeholder={strings.getInputPlaceholder()} value={value} - onChange={e => onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx index 68fccb39f413e..9cade90bd5870 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx @@ -37,7 +37,7 @@ export const DropdownFilter: FunctionComponent = ({ let options = [ { value: '%%CANVAS_MATCH_ALL%%', text: `-- ${strings.getMatchAllOptionLabel()} --` }, ]; - options = options.concat(choices.map(choice => ({ value: choice, text: choice }))); + options = options.concat(choices.map((choice) => ({ value: choice, text: choice }))); const changeHandler = (e: FocusEvent | ChangeEvent) => { if (e && e.target) { @@ -47,7 +47,7 @@ export const DropdownFilter: FunctionComponent = ({ } }; - const dropdownOptions = options.map(option => { + const dropdownOptions = options.map((option) => { const { text } = option; const optionValue = option.value; const selected = optionValue === value; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx index 0ddfa1b41be70..1d4207ac0ae50 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx @@ -71,7 +71,7 @@ export const embeddableRendererFactory = (core: CoreStart, plugins: StartDeps) = if (!embeddablesRegistry[uniqueId]) { const factory = Array.from(plugins.embeddable.getEmbeddableFactories()).find( - embeddableFactory => embeddableFactory.type === embeddableType + (embeddableFactory) => embeddableFactory.type === embeddableType ) as EmbeddableFactory; if (!factory) { @@ -84,7 +84,7 @@ export const embeddableRendererFactory = (core: CoreStart, plugins: StartDeps) = embeddablesRegistry[uniqueId] = embeddableObject; ReactDOM.unmountComponentAtNode(domNode); - const subscription = embeddableObject.getInput$().subscribe(function(updatedInput) { + const subscription = embeddableObject.getInput$().subscribe(function (updatedInput) { const updatedExpression = embeddableInputToExpression(updatedInput, embeddableType); if (updatedExpression) { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts index 306020293abe6..07f828755e46f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts @@ -63,8 +63,8 @@ describe('toExpression', () => { const colors = ast.chain[0].arguments.colors as Ast[]; - const aColor = colors.find(color => color.chain[0].arguments.label[0] === 'a'); - const bColor = colors.find(color => color.chain[0].arguments.label[0] === 'b'); + const aColor = colors.find((color) => color.chain[0].arguments.label[0] === 'a'); + const bColor = colors.find((color) => color.chain[0].arguments.label[0] === 'b'); expect(aColor?.chain[0].arguments.color[0]).toBe(colorMap.a); expect(bColor?.chain[0].arguments.color[0]).toBe(colorMap.b); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js index 971792ae4bfab..b7e3fc300a189 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js @@ -21,7 +21,7 @@ export const error = () => ({ render(domNode, config, handlers) { const draw = () => { const buttonSize = Math.min(domNode.clientHeight, domNode.clientWidth); - const button = handleClick => ( + const button = (handleClick) => ( ( + .addDecorator((story) => (
({ }; config.options.series.pie.label.formatter = labelFormatter; - const legendFormatter = label => { + const legendFormatter = (label) => { const labelSpan = document.createElement('span'); Object.assign(labelSpan.style, config.font.spec); labelSpan.textContent = label; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js index 042cbe83fb10f..2c77f860fd14f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js @@ -89,7 +89,7 @@ function init(plot) { // add hook to determine if pie plugin in enabled, and then perform necessary operations - plot.hooks.processOptions.push(function(plot, options) { + plot.hooks.processOptions.push(function (plot, options) { if (options.series.pie.show) { options.grid.show = false; @@ -123,7 +123,7 @@ function init(plot) { } }); - plot.hooks.bindEvents.push(function(plot, eventHolder) { + plot.hooks.bindEvents.push(function (plot, eventHolder) { const options = plot.getOptions(); if (options.series.pie.show) { if (options.grid.hoverable) { @@ -136,21 +136,21 @@ function init(plot) { } }); - plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { + plot.hooks.processDatapoints.push(function (plot, series, data, datapoints) { const options = plot.getOptions(); if (options.series.pie.show) { processDatapoints(plot, series, data, datapoints); } }); - plot.hooks.drawOverlay.push(function(plot, octx) { + plot.hooks.drawOverlay.push(function (plot, octx) { const options = plot.getOptions(); if (options.series.pie.show) { drawOverlay(plot, octx); } }); - plot.hooks.draw.push(function(plot, newCtx) { + plot.hooks.draw.push(function (plot, newCtx) { const options = plot.getOptions(); if (options.series.pie.show) { draw(plot, newCtx); @@ -263,12 +263,7 @@ function init(plot) { const canvasWidth = plot.getPlaceholder().width(); const canvasHeight = plot.getPlaceholder().height(); - const legendWidth = - target - .children() - .filter('.legend') - .children() - .width() || 0; + const legendWidth = target.children().filter('.legend').children().width() || 0; ctx = newCtx; @@ -351,10 +346,7 @@ function init(plot) { function clear() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); - target - .children() - .filter('.pieLabel, .pieLabelBackground') - .remove(); + target.children().filter('.pieLabel, .pieLabelBackground').remove(); } function drawShadow() { @@ -867,7 +859,7 @@ const options = { }, label: { show: 'auto', - formatter: function(label, slice) { + formatter: function (label, slice) { return ( "
drawPoint(point)); + series.data.forEach((point) => drawPoint(point)); } } } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js index 65dc7517453a1..2c603a62c1d76 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js @@ -14,10 +14,10 @@ const options = { numbers: {}, }; -const xAlign = function(x) { +const xAlign = function (x) { return x; }; -const yAlign = function(y) { +const yAlign = function (y) { return y; }; //const horizontalShift = 1; @@ -28,7 +28,7 @@ function processOptions(/*plot, options*/) { function draw(plot, ctx) { $('.valueLabel', plot.getPlaceholder()).remove(); - plot.getData().forEach(function(series) { + plot.getData().forEach(function (series) { const show = get(series.numbers, 'show'); if (!show) { return; @@ -59,12 +59,9 @@ function draw(plot, ctx) { if (typeof text === 'undefined') { return; } - const textNode = $('
') - .text(String(text)) - .addClass('valueLabel') - .css({ - position: 'absolute', - }); + const textNode = $('
').text(String(text)).addClass('valueLabel').css({ + position: 'absolute', + }); plot.getPlaceholder().append(textNode); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js index 576a7f00cfa45..67d0abb65837d 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js @@ -30,7 +30,7 @@ export const progress = () => ({ const initialViewBox = shapeSvg .getAttribute('viewBox') .split(' ') - .map(v => parseInt(v, 10)); + .map((v) => parseInt(v, 10)); let [minX, minY, width, height] = initialViewBox; if (shape !== 'horizontalBar') { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js index 31f6d1056095e..2e48c8a2d5ec3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js @@ -41,7 +41,7 @@ export const repeatImage = () => ({ } const img = new Image(); - img.onload = function() { + img.onload = function () { setSize(img); if (settings.max && settings.count > settings.max) { settings.count = settings.max; @@ -54,7 +54,7 @@ export const repeatImage = () => ({ } const emptyImage = new Image(); - emptyImage.onload = function() { + emptyImage.onload = function () { setSize(emptyImage); times(settings.max - settings.count, () => container.append(emptyImage.cloneNode(true))); finish(); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js index a15345fed08bd..96c8d80794c0c 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js @@ -23,7 +23,7 @@ export const revealImage = () => ({ domNode.className = 'revealImage'; // set up the overlay image - img.onload = function() { + img.onload = function () { setSize(); finish(); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js index 1c9c76a74974a..02c86afd7182b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js @@ -40,7 +40,7 @@ export const shape = () => ({ const initialViewBox = shapeSvg .getAttribute('viewBox') .split(' ') - .map(v => parseInt(v, 10)); + .map((v) => parseInt(v, 10)); const draw = () => { const width = domNode.offsetWidth; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx index c854ea8267bf5..abc4be44c4b2e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx @@ -23,7 +23,7 @@ const timeRanges = [ ]; storiesOf('renderers/TimeFilter', module) - .addDecorator(story => ( + .addDecorator((story) => (
{ public state = defaultValues; - _onValueChange: (argValue: ExpressionAstExpression) => void = argValue => { + _onValueChange: (argValue: ExpressionAstExpression) => void = (argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }; @@ -46,13 +46,13 @@ class Interactive extends React.Component<{}, typeof defaultValues> { } storiesOf('arguments/AxisConfig', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended', () => ); storiesOf('arguments/AxisConfig/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended disabled', () => ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx index 1446fe2933f8a..14d61f13ea488 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx @@ -20,7 +20,7 @@ class Interactive extends React.Component<{}, typeof defaultValues> { public render() { return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -31,13 +31,13 @@ class Interactive extends React.Component<{}, typeof defaultValues> { } storiesOf('arguments/AxisConfig', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/AxisConfig/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple template', () => ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js index dbc129094acff..cb8e999489fbf 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js @@ -20,14 +20,14 @@ describe('getFormObject', () => { it('number', () => { expect(getFormObject) .withArgs('2') - .to.throwException(e => { + .to.throwException((e) => { expect(e.message).to.be('Cannot render scalar values or complex math expressions'); }); }); it('complex expression', () => { expect(getFormObject) .withArgs('mean(field * 3)') - .to.throwException(e => { + .to.throwException((e) => { expect(e.message).to.be('Cannot render scalar values or complex math expressions'); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js index 8c1a4aad5d0f3..56849d6fe0c41 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js @@ -17,7 +17,7 @@ import { SimpleMathFunction } from './simple_math_function'; import { getFormObject } from './get_form_object'; const { DataColumn: strings } = ArgumentStrings; -const maybeQuoteValue = val => (val.match(/\s/) ? `'${val}'` : val); +const maybeQuoteValue = (val) => (val.match(/\s/) ? `'${val}'` : val); // TODO: Garbage, we could make a much nicer math form that can handle way more. class DatacolumnArgInput extends Component { @@ -51,7 +51,7 @@ class DatacolumnArgInput extends Component { const allowedTypes = typeInstance.options.allowedTypes || false; const onlyShowMathFunctions = typeInstance.options.onlyMath || false; - const valueNotSet = val => !val || val.length === 0; + const valueNotSet = (val) => !val || val.length === 0; const updateFunctionValue = () => { const fn = this.inputRefs.fn.value; @@ -79,11 +79,12 @@ class DatacolumnArgInput extends Component { onValueChange(`${fn}(${maybeQuoteValue(column)})`); }; - const column = columns.map(col => col.name).find(colName => colName === mathValue.column) || ''; + const column = + columns.map((col) => col.name).find((colName) => colName === mathValue.column) || ''; const options = [{ value: '', text: 'select column', disabled: true }]; - sortBy(columns, 'name').forEach(column => { + sortBy(columns, 'name').forEach((column) => { if (allowedTypes && !allowedTypes.includes(column.type)) { return; } @@ -96,7 +97,7 @@ class DatacolumnArgInput extends Component { (this.inputRefs.fn = ref)} + inputRef={(ref) => (this.inputRefs.fn = ref)} onlymath={onlyShowMathFunctions} onChange={updateFunctionValue} /> @@ -106,7 +107,7 @@ class DatacolumnArgInput extends Component { compressed options={options} value={column} - inputRef={ref => (this.inputRefs.column = ref)} + inputRef={(ref) => (this.inputRefs.column = ref)} onChange={updateFunctionValue} /> @@ -117,7 +118,7 @@ class DatacolumnArgInput extends Component { const EnhancedDatacolumnArgInput = compose( withPropsOnChange(['argValue', 'columns'], ({ argValue, columns }) => ({ - mathValue: (argValue => { + mathValue: ((argValue) => { if (getType(argValue) !== 'string') { return { error: 'argValue is not a string type' }; } @@ -132,7 +133,7 @@ const EnhancedDatacolumnArgInput = compose( })), createStatefulPropHoc('mathValue', 'setMathValue'), withHandlers({ - setMathFunction: ({ mathValue, setMathValue }) => fn => setMathValue({ ...mathValue, fn }), + setMathFunction: ({ mathValue, setMathValue }) => (fn) => setMathValue({ ...mathValue, fn }), }) )(DatacolumnArgInput); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts index 655a362fe6d33..fce9b21fa0387 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts @@ -30,7 +30,7 @@ export const dateFormatInitializer: SetupInitializer ({ + const dateFormats = Object.values(formatMap).map((format) => ({ value: format, text: moment.utc(moment()).format(format), })); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js index 1659b0757cbd8..4a09fd5540d30 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js @@ -29,15 +29,15 @@ const FilterGroupInput = ({ onValueChange, argValue, argId, filterGroups }) => { const choices = [{ text: 'No group', value: '' }].concat( argValueChoice, - filterGroups.map(f => ({ text: f })) + filterGroups.map((f) => ({ text: f })) ); - const handleSelectGroup = ev => { + const handleSelectGroup = (ev) => { const selected = ev.target.value; onValueChange(selected); }; - const handleAddGroup = ev => { + const handleAddGroup = (ev) => { // stop the form from submitting ev.preventDefault(); // set the new value @@ -56,7 +56,7 @@ const FilterGroupInput = ({ onValueChange, argValue, argId, filterGroups }) => { compressed type="text" value={inputValue} - onChange={ev => setInputValue(ev.target.value)} + onChange={(ev) => setInputValue(ev.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js index a3c327da2e4dc..d7c7cd9e1a32f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js @@ -58,7 +58,7 @@ class ImageUpload extends React.Component { this._isMounted = false; } - updateAST = assetId => { + updateAST = (assetId) => { this.props.onValueChange({ type: 'expression', chain: [ @@ -73,7 +73,7 @@ class ImageUpload extends React.Component { }); }; - handleUpload = files => { + handleUpload = (files) => { const { onAssetAdd } = this.props; const [file] = files; @@ -82,8 +82,8 @@ class ImageUpload extends React.Component { this.setState({ loading: true }); // start loading indicator encode(file) - .then(dataurl => onAssetAdd('dataurl', dataurl)) - .then(assetId => { + .then((dataurl) => onAssetAdd('dataurl', dataurl)) + .then((assetId) => { this.updateAST(assetId); // this component can go away when onValueChange is called, check for _isMounted @@ -92,7 +92,7 @@ class ImageUpload extends React.Component { } }; - changeUrlType = optionId => { + changeUrlType = (optionId) => { this.setState({ urlType: optionId }); }; @@ -140,7 +140,7 @@ class ImageUpload extends React.Component { link: ( (this.inputRefs.srcUrlText = ref)} + inputRef={(ref) => (this.inputRefs.srcUrlText = ref)} onSubmit={this.setSrcUrl} /> ), diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts index bd84a2eb97d24..2f9a21d8a009f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts @@ -53,5 +53,5 @@ export const args = [ export const initializers = [dateFormatInitializer, numberFormatInitializer]; export const initializeArgs: SetupInitializer = (core, plugins) => { - return [...args, ...initializers.map(initializer => initializer(core, plugins))]; + return [...args, ...initializers.map((initializer) => initializer(core, plugins))]; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js index aae96f1266a36..f9c2f5eb21a2a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js @@ -27,7 +27,7 @@ const NumberArgInput = ({ updateValue, value, confirm, commit, argId }) => ( compressed id={argId} value={Number(value)} - onChange={confirm ? updateValue : ev => commit(Number(ev.target.value))} + onChange={confirm ? updateValue : (ev) => commit(Number(ev.target.value))} /> {confirm && ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js index d60dc13f0105b..eddaa20a4800e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js @@ -26,7 +26,7 @@ const PaletteArgInput = ({ onValueChange, argValue, renderError }) => { throwNotParsed(); } try { - const colors = chain[0].arguments._.map(astObj => { + const colors = chain[0].arguments._.map((astObj) => { if (getType(astObj) !== 'string') { throwNotParsed(); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js index 5fa2ca42ca78a..746d1ff7a9d18 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js @@ -13,7 +13,7 @@ import { ArgumentStrings } from '../../../i18n'; const { Percentage: strings } = ArgumentStrings; const PercentageArgInput = ({ onValueChange, argValue }) => { - const handleChange = ev => { + const handleChange = (ev) => { return onValueChange(ev.target.value / 100); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js index b3d1670c5d711..d23d6560f0124 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js @@ -14,7 +14,7 @@ const { Range: strings } = ArgumentStrings; const RangeArgInput = ({ typeInstance, onValueChange, argValue }) => { const { min, max, step } = typeInstance.options; - const handleChange = ev => { + const handleChange = (ev) => { return onValueChange(Number(ev.target.value)); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js index 478acd41d797f..d218ca39b7f72 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js @@ -14,7 +14,7 @@ const { Select: strings } = ArgumentStrings; const SelectArgInput = ({ typeInstance, onValueChange, argValue, argId }) => { const choices = typeInstance.options.choices.map(({ value, name }) => ({ value, text: name })); - const handleChange = ev => { + const handleChange = (ev) => { // Get the value from the choices passed in since it could be a number or // boolean, but ev.target.value is always a string const { value } = choices[ev.target.selectedIndex]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js index dc31497a7da78..53c4c8bee5282 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js @@ -22,7 +22,7 @@ const StringArgInput = ({ updateValue, value, confirm, commit, argId }) => ( compressed id={argId} value={value} - onChange={confirm ? updateValue : ev => commit(ev.target.value)} + onChange={confirm ? updateValue : (ev) => commit(ev.target.value)} /> {confirm && ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js index a0af71585eed0..3bbdd165541ff 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js @@ -30,7 +30,7 @@ const TextAreaArgInput = ({ updateValue, value, confirm, commit, renderError, ar rows={10} value={value} resize="none" - onChange={confirm ? updateValue : ev => commit(ev.target.value)} + onChange={confirm ? updateValue : (ev) => commit(ev.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js index 282ec17e94c9b..7384986fa5c2b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js @@ -59,12 +59,12 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { if (commas.length === 0) { return []; } - return commas.split(',').map(str => str.trim()); + return commas.split(',').map((str) => str.trim()); }; const getSortBy = () => { const commas = getSimpleArg('sort', args)[0] || ', DESC'; - return commas.split(',').map(str => str.trim()); + return commas.split(',').map((str) => str.trim()); }; const fields = getFields(); @@ -88,7 +88,7 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { helpText={strings.getIndexLabel()} display="rowCompressed" > - setArg('index', index)} /> + setArg('index', index)} /> { > setArg('fields', fields.join(', '))} + onChange={(fields) => setArg('fields', fields.join(', '))} selected={fields} /> @@ -114,14 +114,14 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { setArg('sort', [field, sortOrder].join(', '))} + onChange={(field) => setArg('sort', [field, sortOrder].join(', '))} /> setArg('sort', [sortField, e.target.value].join(', '))} + onChange={(e) => setArg('sort', [sortField, e.target.value].join(', '))} options={sortOptions} compressed /> @@ -140,7 +140,7 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { > setArg(getArgName(), e.target.value)} + onChange={(e) => setArg(getArgName(), e.target.value)} compressed /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js index 44e335dd7b41f..958898893d7eb 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js @@ -49,7 +49,7 @@ class EssqlDatasource extends PureComponent { }); }; - onChange = e => { + onChange = (e) => { const { value } = e.target; this.props.setInvalid(!value.trim()); this.setArg(this.getArgName(), value); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js index b36f1a747f120..c5126ab3e969f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js @@ -99,7 +99,7 @@ const TimelionDatasource = ({ args, updateArgs, defaultIndex }) => { setArg(argName, e.target.value)} + onChange={(e) => setArg(argName, e.target.value)} rows={15} /> @@ -115,7 +115,7 @@ const TimelionDatasource = ({ args, updateArgs, defaultIndex }) => { setArg('interval', e.target.value)} + onChange={(e) => setArg('interval', e.target.value)} />
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts index fdcaf21982050..34877f2fd551b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts @@ -54,5 +54,5 @@ export const viewSpecs = [ export const viewInitializers = [metricInitializer]; export const initializeViews: SetupInitializer = (core, plugins) => { - return [...viewSpecs, ...viewInitializers.map(initializer => initializer(core, plugins))]; + return [...viewSpecs, ...viewInitializers.map((initializer) => initializer(core, plugins))]; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js index 783140b0c8b9e..f1b6a48d1e7b0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js @@ -90,6 +90,6 @@ export const pie = () => ({ if (getState(context) !== 'ready') { return { labels: [] }; } - return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; + return { labels: uniq(map(getValue(context).rows, 'color').filter((v) => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js index 6e000336a6b34..1449bddf322b5 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js @@ -72,6 +72,6 @@ export const plot = () => ({ if (getState(context) !== 'ready') { return { labels: [] }; } - return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; + return { labels: uniq(map(getValue(context).rows, 'color').filter((v) => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js index ae68c9c5c6031..c36334e18704b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js @@ -22,7 +22,7 @@ export const progress = () => ({ help: strings.getShapeHelp(), argType: 'select', options: { - choices: Object.keys(shapes).map(key => ({ + choices: Object.keys(shapes).map((key) => ({ value: key, //turns camel into title case name: key[0].toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1'), diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js index 03a13b3f8fe21..73324feddcab0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js @@ -24,7 +24,7 @@ export const table = () => ({ argType: 'select', default: 10, options: { - choices: ['', 5, 10, 25, 50, 100].map(v => ({ name: String(v), value: v })), + choices: ['', 5, 10, 25, 50, 100].map((v) => ({ name: String(v), value: v })), }, }, { diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.test.ts b/x-pack/plugins/canvas/common/lib/autocomplete.test.ts index 31d213f4853ff..f7a773f6ca36a 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.test.ts +++ b/x-pack/plugins/canvas/common/lib/autocomplete.test.ts @@ -18,7 +18,7 @@ describe('autocomplete', () => { it('should return function definition for plot', () => { const expression = 'plot '; const def = getFnArgDefAtPosition(functionSpecs, expression, expression.length); - const plotFn = functionSpecs.find(spec => spec.name === 'plot'); + const plotFn = functionSpecs.find((spec) => spec.name === 'plot'); expect(def.fnDef).toBe(plotFn); }); }); @@ -34,7 +34,7 @@ describe('autocomplete', () => { it('should suggest arguments', () => { const expression = 'plot '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const plotFn = functionSpecs.find(spec => spec.name === 'plot'); + const plotFn = functionSpecs.find((spec) => spec.name === 'plot'); expect(suggestions.length).toBe(Object.keys(plotFn!.args).length); expect(suggestions[0].start).toBe(expression.length); expect(suggestions[0].end).toBe(expression.length); @@ -43,7 +43,7 @@ describe('autocomplete', () => { it('should suggest values', () => { const expression = 'shape shape='; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length); expect(suggestions[0].end).toBe(expression.length); @@ -85,14 +85,14 @@ describe('autocomplete', () => { expect(suggestions[0].fnDef.inputTypes).toEqual(['datatable']); const withReturnOnly = suggestions.findIndex( - suggestion => + (suggestion) => suggestion.fnDef.type === 'datatable' && suggestion.fnDef.inputTypes && !(suggestion.fnDef.inputTypes as string[]).includes('datatable') ); const withNeither = suggestions.findIndex( - suggestion => + (suggestion) => suggestion.fnDef.type !== 'datatable' && (!suggestion.fnDef.inputTypes || !(suggestion.fnDef.inputTypes as string[]).includes('datatable')) @@ -111,7 +111,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const ltFn = functionSpecs.find(spec => spec.name === 'lt'); + const ltFn = functionSpecs.find((spec) => spec.name === 'lt'); expect(suggestions.length).toBe(Object.keys(ltFn!.args).length); expect(suggestions[0].start).toBe(expression.length - 1); expect(suggestions[0].end).toBe(expression.length - 1); @@ -124,7 +124,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length - 1); expect(suggestions[0].end).toBe(expression.length - 1); @@ -137,7 +137,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length - '"ar"'.length); expect(suggestions[0].end).toBe(expression.length); @@ -146,32 +146,32 @@ describe('autocomplete', () => { it('should prioritize functions that match the previous function type', () => { const expression = 'plot | '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const renderIndex = suggestions.findIndex(suggestion => suggestion.text.includes('render')); - const anyIndex = suggestions.findIndex(suggestion => suggestion.text.includes('any')); + const renderIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('render')); + const anyIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('any')); expect(renderIndex).toBeLessThan(anyIndex); }); it('should alphabetize functions', () => { const expression = ''; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const metricIndex = suggestions.findIndex(suggestion => suggestion.text.includes('metric')); - const anyIndex = suggestions.findIndex(suggestion => suggestion.text.includes('any')); + const metricIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('metric')); + const anyIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('any')); expect(anyIndex).toBeLessThan(metricIndex); }); it('should prioritize unnamed arguments', () => { const expression = 'case '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const whenIndex = suggestions.findIndex(suggestion => suggestion.text.includes('when')); - const thenIndex = suggestions.findIndex(suggestion => suggestion.text.includes('then')); + const whenIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('when')); + const thenIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('then')); expect(whenIndex).toBeLessThan(thenIndex); }); it('should alphabetize arguments', () => { const expression = 'plot '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const yaxisIndex = suggestions.findIndex(suggestion => suggestion.text.includes('yaxis')); - const defaultStyleIndex = suggestions.findIndex(suggestion => + const yaxisIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('yaxis')); + const defaultStyleIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('defaultStyle') ); expect(defaultStyleIndex).toBeLessThan(yaxisIndex); diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.ts b/x-pack/plugins/canvas/common/lib/autocomplete.ts index 5ee4d2104a0f7..982aee1ea19c8 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.ts +++ b/x-pack/plugins/canvas/common/lib/autocomplete.ts @@ -200,7 +200,7 @@ export function getAutocompleteSuggestions( item. The context function for `formatnumber` is the return of `math "divide(value, 2)"`. */ function getFnArgAtPosition(ast: ExpressionASTWithMeta, position: number): FnArgAtPosition { - const fnIndex = ast.node.chain.findIndex(fn => fn.start <= position && position <= fn.end); + const fnIndex = ast.node.chain.findIndex((fn) => fn.start <= position && position <= fn.end); const fn = ast.node.chain[fnIndex]; for (const [argName, argValues] of Object.entries(fn.node.arguments)) { for (let argIndex = 0; argIndex < argValues.length; argIndex++) { @@ -285,7 +285,7 @@ function getFnNameSuggestions( return aScore > bScore ? -1 : 1; }); - return fnDefs.map(fnDef => { + return fnDefs.map((fnDef) => { return { type: 'function', text: `${fnDef.name} `, start, end: end - MARKER.length, fnDef }; }); } @@ -325,7 +325,7 @@ function getSubFnNameSuggestions( return aScore > bScore ? -1 : 1; }); - return fnDefs.map(fnDef => { + return fnDefs.map((fnDef) => { return { type: 'function', text: fnDef.name + ' ', start, end: end - MARKER.length, fnDef }; }); } @@ -402,7 +402,7 @@ function getArgNameSuggestions( // Filter the list of args by those which aren't already present (unless they allow multi) const argEntries = Object.entries(fn.arguments).map<[string, ExpressionArgASTWithMeta[]]>( ([name, values]) => { - return [name, values.filter(value => !value.text.includes(MARKER))]; + return [name, values.filter((value) => !value.text.includes(MARKER))]; } ); @@ -422,7 +422,7 @@ function getArgNameSuggestions( .map(([name, arg]) => ({ name, ...arg })) .sort(unnamedArgComparator); - return argDefs.map(argDef => { + return argDefs.map((argDef) => { return { type: 'argument', text: argDef.name + '=', @@ -464,7 +464,7 @@ function getArgValueSuggestions( suggestions.push(argDef.default); } - return uniq(suggestions).map(value => { + return uniq(suggestions).map((value) => { const text = maybeQuote(value) + ' '; return { start, end: end - MARKER.length, type: 'value', text }; }); diff --git a/x-pack/plugins/canvas/common/lib/datatable/query.js b/x-pack/plugins/canvas/common/lib/datatable/query.js index 63945ce7690f9..ec7530ca47a5b 100644 --- a/x-pack/plugins/canvas/common/lib/datatable/query.js +++ b/x-pack/plugins/canvas/common/lib/datatable/query.js @@ -13,17 +13,17 @@ export function queryDatatable(datatable, query) { } if (query.and) { - query.and.forEach(filter => { + query.and.forEach((filter) => { // handle exact matches if (filter.filterType === 'exactly') { - datatable.rows = datatable.rows.filter(row => { + datatable.rows = datatable.rows.filter((row) => { return row[filter.column] === filter.value; }); } // handle time filters if (filter.filterType === 'time') { - const columnNames = datatable.columns.map(col => col.name); + const columnNames = datatable.columns.map((col) => col.name); // remove row if no column match if (!columnNames.includes(filter.column)) { @@ -31,7 +31,7 @@ export function queryDatatable(datatable, query) { return; } - datatable.rows = datatable.rows.filter(row => { + datatable.rows = datatable.rows.filter((row) => { const fromTime = new Date(filter.from).getTime(); const toTime = new Date(filter.to).getTime(); const rowTime = new Date(row[filter.column]).getTime(); diff --git a/x-pack/plugins/canvas/common/lib/dataurl.ts b/x-pack/plugins/canvas/common/lib/dataurl.ts index eddc8da1a51aa..ea5a26b27e423 100644 --- a/x-pack/plugins/canvas/common/lib/dataurl.ts +++ b/x-pack/plugins/canvas/common/lib/dataurl.ts @@ -55,7 +55,7 @@ export function encode(data: any | null, type = 'text/plain') { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result as string); - reader.onerror = err => reject(err); + reader.onerror = (err) => reject(err); reader.readAsDataURL(data); }); } diff --git a/x-pack/plugins/canvas/common/lib/get_field_type.ts b/x-pack/plugins/canvas/common/lib/get_field_type.ts index aaea95334e62e..db817393a1cdb 100644 --- a/x-pack/plugins/canvas/common/lib/get_field_type.ts +++ b/x-pack/plugins/canvas/common/lib/get_field_type.ts @@ -19,6 +19,6 @@ export function getFieldType(columns: DatatableColumn[], field?: string): string return 'null'; } const realField = unquoteString(field); - const column = columns.find(dataTableColumn => dataTableColumn.name === realField); + const column = columns.find((dataTableColumn) => dataTableColumn.name === realField); return column ? column.type : 'null'; } diff --git a/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts b/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts index 586666e633e84..d05536ededae3 100644 --- a/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts +++ b/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts @@ -10,12 +10,12 @@ export const hexToRgb = (hex: string) => { const shorthandMatches = shorthandHexColor.exec(hex); if (shorthandMatches) { - return shorthandMatches.slice(1, 4).map(mappedHex => parseInt(mappedHex + mappedHex, 16)); + return shorthandMatches.slice(1, 4).map((mappedHex) => parseInt(mappedHex + mappedHex, 16)); } const hexMatches = hexColor.exec(hex); if (hexMatches) { - return hexMatches.slice(1, 4).map(slicedHex => parseInt(slicedHex, 16)); + return hexMatches.slice(1, 4).map((slicedHex) => parseInt(slicedHex, 16)); } return null; diff --git a/x-pack/plugins/canvas/common/lib/pivot_object_array.ts b/x-pack/plugins/canvas/common/lib/pivot_object_array.ts index f13a2a2af8844..c098b7772ef11 100644 --- a/x-pack/plugins/canvas/common/lib/pivot_object_array.ts +++ b/x-pack/plugins/canvas/common/lib/pivot_object_array.ts @@ -20,6 +20,6 @@ export function pivotObjectArray< throw new Error('Columns should be an array of strings'); } - const columnValues = map(columnNames, name => map(rows, name)); + const columnValues = map(columnNames, (name) => map(rows, name)); return zipObject(columnNames, columnValues); } diff --git a/x-pack/plugins/canvas/i18n/elements/apply_strings.ts b/x-pack/plugins/canvas/i18n/elements/apply_strings.ts index 4464ed5dbf185..5e5115abb0194 100644 --- a/x-pack/plugins/canvas/i18n/elements/apply_strings.ts +++ b/x-pack/plugins/canvas/i18n/elements/apply_strings.ts @@ -16,7 +16,7 @@ import { getElementStrings } from './index'; export const applyElementStrings = (elements: ElementFactory[]) => { const elementStrings = getElementStrings(); - return elements.map(spec => { + return elements.map((spec) => { const result = spec(); const { name } = result; const strings = elementStrings[name]; diff --git a/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts b/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts index 1eff73c1525b1..e1e35a5b6b0dd 100644 --- a/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts +++ b/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts @@ -11,27 +11,27 @@ const elementSpecs = initializeElements(coreMock.createSetup() as any, {} as any describe('ElementStrings', () => { const elementStrings = getElementStrings(); - const elementNames = elementSpecs.map(spec => spec().name); + const elementNames = elementSpecs.map((spec) => spec().name); const stringKeys = Object.keys(elementStrings); test('All element names should exist in the strings definition', () => { - elementNames.forEach(name => expect(stringKeys).toContain(name)); + elementNames.forEach((name) => expect(stringKeys).toContain(name)); }); test('All string definitions should correspond to an existing element', () => { - stringKeys.forEach(key => expect(elementNames).toContain(key)); + stringKeys.forEach((key) => expect(elementNames).toContain(key)); }); const strings = Object.values(elementStrings); test('All elements should have a displayName string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('displayName'); }); }); test('All elements should have a help string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('help'); }); }); diff --git a/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts b/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts index cc601b0ea0e31..f201e73d717eb 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts @@ -18,7 +18,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(DATATABLE_COLUMN_TYPES) .slice(0, -1) - .map(type => `\`${type}\``) + .map((type) => `\`${type}\``) .join(', '), end: Object.values(DATATABLE_COLUMN_TYPES).slice(-1)[0], mapColumnFn: '`mapColumn`', diff --git a/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts b/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts index 15708dd949b22..7cf0ec6c58761 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts @@ -38,7 +38,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Position) .slice(0, -1) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), end: Object.values(Position).slice(-1)[0], }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/pie.ts b/x-pack/plugins/canvas/i18n/functions/dict/pie.ts index 1a93cdee05749..2e4bfc88a273a 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/pie.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/pie.ts @@ -41,7 +41,7 @@ export const help: FunctionHelp> = { 'The legend position. For example, {positions}, or {BOOLEAN_FALSE}. When {BOOLEAN_FALSE}, the legend is hidden.', values: { positions: Object.values(Position) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), BOOLEAN_FALSE, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/plot.ts b/x-pack/plugins/canvas/i18n/functions/dict/plot.ts index 3d4624bd2495e..068156f14c91b 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/plot.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/plot.ts @@ -33,7 +33,7 @@ export const help: FunctionHelp> = { 'The legend position. For example, {positions}, or {BOOLEAN_FALSE}. When {BOOLEAN_FALSE}, the legend is hidden.', values: { positions: Object.values(Position) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), BOOLEAN_FALSE, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/progress.ts b/x-pack/plugins/canvas/i18n/functions/dict/progress.ts index 7e441df9bd246..1880c5dc807f0 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/progress.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/progress.ts @@ -48,7 +48,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Shape) .slice(0, -1) - .map(shape => `\`"${shape}"\``) + .map((shape) => `\`"${shape}"\``) .join(', '), end: `\`"${Object.values(Shape).slice(-1)[0]}"\``, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts b/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts index f210ec8c1d882..410ca29d7b4d4 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts @@ -39,7 +39,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Position) .slice(0, -1) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), end: Object.values(Position).slice(-1)[0], }, diff --git a/x-pack/plugins/canvas/i18n/templates/apply_strings.ts b/x-pack/plugins/canvas/i18n/templates/apply_strings.ts index 4ddd3a61543c2..01775e9daeb51 100644 --- a/x-pack/plugins/canvas/i18n/templates/apply_strings.ts +++ b/x-pack/plugins/canvas/i18n/templates/apply_strings.ts @@ -18,7 +18,7 @@ import { TagStrings } from '../../i18n'; export const applyTemplateStrings = (templates: CanvasTemplate[]) => { const templateStrings = getTemplateStrings(); - return templates.map(template => { + return templates.map((template) => { const { name: templateName } = template; const strings = templateStrings[templateName]; @@ -36,7 +36,7 @@ export const applyTemplateStrings = (templates: CanvasTemplate[]) => { } if (template.tags) { - template.tags = template.tags.map(tag => { + template.tags = template.tags.map((tag) => { if (TagStrings[tag]) { return TagStrings[tag](); } diff --git a/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts b/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts index eeeb06732d397..4f7b61e13fe69 100644 --- a/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts +++ b/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts @@ -11,7 +11,7 @@ import { TagStrings } from '../tags'; describe('TemplateStrings', () => { const templateStrings = getTemplateStrings(); - const templateNames = templateSpecs.map(template => template().name); + const templateNames = templateSpecs.map((template) => template().name); const stringKeys = Object.keys(templateStrings); test('All template names should exist in the strings definition', () => { @@ -19,19 +19,19 @@ describe('TemplateStrings', () => { }); test('All string definitions should correspond to an existing template', () => { - stringKeys.forEach(key => expect(templateNames).toContain(key)); + stringKeys.forEach((key) => expect(templateNames).toContain(key)); }); const strings = Object.values(templateStrings); test('All templates should have a name string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('name'); }); }); test('All templates should have a help string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('help'); }); }); @@ -39,7 +39,7 @@ describe('TemplateStrings', () => { test('All templates should have tags that are defined', () => { const tagNames = Object.keys(TagStrings); - templateSpecs.forEach(template => { + templateSpecs.forEach((template) => { template().tags.forEach((tagName: string) => expect(tagNames).toContain(tagName)); }); }); diff --git a/x-pack/plugins/canvas/public/application.tsx b/x-pack/plugins/canvas/public/application.tsx index d97e4944da13a..1cd0bc250feb2 100644 --- a/x-pack/plugins/canvas/public/application.tsx +++ b/x-pack/plugins/canvas/public/application.tsx @@ -115,7 +115,7 @@ export const initializeCanvas = async ( href: getDocumentationLinks().canvas, }, ], - content: domNode => { + content: (domNode) => { ReactDOM.render(, domNode); return () => ReactDOM.unmountComponentAtNode(domNode); }, diff --git a/x-pack/plugins/canvas/public/apps/export/export/index.js b/x-pack/plugins/canvas/public/apps/export/export/index.js index dafcb9f4c2510..95c46d9e1c8ae 100644 --- a/x-pack/plugins/canvas/public/apps/export/export/index.js +++ b/x-pack/plugins/canvas/public/apps/export/export/index.js @@ -11,12 +11,12 @@ import { getWorkpad, getSelectedPageIndex } from '../../../state/selectors/workp import { LoadWorkpad } from './load_workpad'; import { ExportApp as Component } from './export_app'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpad: getWorkpad(state), selectedPageIndex: getSelectedPageIndex(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ initializeWorkpad() { dispatch(initializeWorkpad()); }, diff --git a/x-pack/plugins/canvas/public/apps/export/routes.js b/x-pack/plugins/canvas/public/apps/export/routes.js index a0eafe3e3ffe9..33e375115aa19 100644 --- a/x-pack/plugins/canvas/public/apps/export/routes.js +++ b/x-pack/plugins/canvas/public/apps/export/routes.js @@ -18,7 +18,7 @@ export const routes = [ { name: 'exportWorkpad', path: '/pdf/:id/page/:page', - action: dispatch => async ({ params, router }) => { + action: (dispatch) => async ({ params, router }) => { // load workpad if given a new id via url param const fetchedWorkpad = await workpadService.get(params.id); const pageNumber = parseInt(params.page, 10); diff --git a/x-pack/plugins/canvas/public/apps/home/home_app/index.js b/x-pack/plugins/canvas/public/apps/home/home_app/index.js index f26b3510c7682..f78ee1f8a18af 100644 --- a/x-pack/plugins/canvas/public/apps/home/home_app/index.js +++ b/x-pack/plugins/canvas/public/apps/home/home_app/index.js @@ -8,7 +8,7 @@ import { connect } from 'react-redux'; import { resetWorkpad } from '../../../state/actions/workpad'; import { HomeApp as Component } from './home_app'; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ onLoad() { dispatch(resetWorkpad()); }, diff --git a/x-pack/plugins/canvas/public/apps/workpad/routes.js b/x-pack/plugins/canvas/public/apps/workpad/routes.js index 4e3920bf34f67..a330020b741ac 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/routes.js +++ b/x-pack/plugins/canvas/public/apps/workpad/routes.js @@ -25,7 +25,7 @@ export const routes = [ { name: 'createWorkpad', path: '/create', - action: dispatch => async ({ router }) => { + action: (dispatch) => async ({ router }) => { const newWorkpad = getDefaultWorkpad(); try { await workpadService.create(newWorkpad); diff --git a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js index f0a5325baf3c0..ac50cd3fb99b6 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js +++ b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js @@ -15,7 +15,7 @@ import { withElementsLoadedTelemetry } from './workpad_telemetry'; export { WORKPAD_CONTAINER_ID } from './workpad_app'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const appReady = getAppReady(state); return { @@ -25,7 +25,7 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ deselectElement(ev) { ev && ev.stopPropagation(); dispatch(selectToplevelNodes([])); diff --git a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx index 5f3f114092e61..47b461f22ad65 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx +++ b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx @@ -57,10 +57,10 @@ function areAllElementsInResolvedArgs(workpad: Workpad, resolvedArgs: ResolvedAr const resolvedArgsElements = Object.keys(resolvedArgs); const workpadElements = workpad.pages.reduce((reduction, page) => { - return [...reduction, ...page.elements.map(element => element.id)]; + return [...reduction, ...page.elements.map((element) => element.id)]; }, []); - return workpadElements.every(element => resolvedArgsElements.includes(element)); + return workpadElements.every((element) => resolvedArgsElements.includes(element)); } export const withUnconnectedElementsLoadedTelemetry =

( diff --git a/x-pack/plugins/canvas/public/components/app/app.js b/x-pack/plugins/canvas/public/components/app/app.js index 16484afc8620b..5eb62f4bab950 100644 --- a/x-pack/plugins/canvas/public/components/app/app.js +++ b/x-pack/plugins/canvas/public/components/app/app.js @@ -65,7 +65,7 @@ export class App extends React.PureComponent { loadingMessage={strings.getLoadingMessage()} onRouteChange={this.props.onRouteChange} onLoad={() => this.props.setAppReady(true)} - onError={err => this.props.setAppError(err)} + onError={(err) => this.props.setAppError(err)} />

); diff --git a/x-pack/plugins/canvas/public/components/app/index.js b/x-pack/plugins/canvas/public/components/app/index.js index 750132dadb97d..a1e3b9c09554a 100644 --- a/x-pack/plugins/canvas/public/components/app/index.js +++ b/x-pack/plugins/canvas/public/components/app/index.js @@ -12,7 +12,7 @@ import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; import { App as Component } from './app'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { // appReady could be an error object const appState = getAppReady(state); @@ -22,7 +22,7 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ setAppReady: () => async () => { try { // set app state to ready @@ -31,7 +31,7 @@ const mapDispatchToProps = dispatch => ({ dispatch(appError(e)); } }, - setAppError: payload => dispatch(appError(payload)), + setAppError: (payload) => dispatch(appError(payload)), }); const mergeProps = (stateProps, dispatchProps, ownProps) => { @@ -46,7 +46,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { export const App = compose( connect(mapStateToProps, mapDispatchToProps, mergeProps), withKibana, - withProps(props => ({ + withProps((props) => ({ onRouteChange: props.kibana.services.canvas.navLink.updatePath, })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx b/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx index 9c66043454585..c26fdb8c46d0f 100644 --- a/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx +++ b/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx @@ -45,7 +45,7 @@ export const ArgAddPopover = ({ options }: Props) => { button={button} > {({ closePopover }: PopoverChildrenProps) => - options.map(opt => ( + options.map((opt) => ( { +export const AdvancedFailureComponent = (props) => { const { onValueChange, defaultValue, @@ -26,7 +26,7 @@ export const AdvancedFailureComponent = props => { argId, } = props; - const valueChange = ev => { + const valueChange = (ev) => { ev.preventDefault(); resetErrorState(); // when setting a new value, attempt to reset the error state @@ -36,7 +36,7 @@ export const AdvancedFailureComponent = props => { } }; - const confirmReset = ev => { + const confirmReset = (ev) => { ev.preventDefault(); resetErrorState(); // when setting a new value, attempt to reset the error state onValueChange(fromExpression(defaultValue, 'argument')); @@ -61,7 +61,7 @@ export const AdvancedFailureComponent = props => {
- valueChange(e)} size="s" type="submit"> + valueChange(e)} size="s" type="submit"> {strings.getApplyButtonLabel()} {defaultValue && defaultValue.length && ( @@ -91,7 +91,7 @@ export const AdvancedFailure = compose( })), createStatefulPropHoc('argExpression', 'updateArgExpression'), withPropsOnChange(['argExpression'], ({ argExpression }) => ({ - valid: (function() { + valid: (function () { try { fromExpression(argExpression, 'argument'); return true; diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js index cff38431deb15..dfd99b18646a6 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js @@ -80,7 +80,7 @@ class ArgFormComponent extends PureComponent { }); }, error: hasError, - setLabel: label => this._isMounted && setLabel(label), + setLabel: (label) => this._isMounted && setLabel(label), resetErrorState: () => { resetErrorState(); this._isMounted && setRenderError(false); diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_label.js b/x-pack/plugins/canvas/public/components/arg_form/arg_label.js index 4324eed0892a5..fa0391952d151 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_label.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_label.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { EuiFormRow, EuiAccordion, EuiText, EuiToolTip, EuiIcon } from '@elastic/eui'; // This is what is being generated by render() from the Arg class. It is called in FunctionForm -export const ArgLabel = props => { +export const ArgLabel = (props) => { const { argId, className, label, help, expandable, children, simpleArg, initialIsOpen } = props; return ( diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js index 947c3741c735b..7cd30a8987739 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js @@ -47,7 +47,7 @@ class ArgTemplateFormComponent extends React.Component { _domNode = null; - _renderTemplate = domNode => { + _renderTemplate = (domNode) => { const { template, argumentProps, handlers } = this.props; if (template) { return template(domNode, argumentProps, handlers); @@ -72,7 +72,7 @@ class ArgTemplateFormComponent extends React.Component { return ( { + render={(domNode) => { this._domNode = domNode; this._renderTemplate(domNode); }} diff --git a/x-pack/plugins/canvas/public/components/arg_form/index.js b/x-pack/plugins/canvas/public/components/arg_form/index.js index 017ecae3103da..b6e30f9e52c60 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/index.js +++ b/x-pack/plugins/canvas/public/components/arg_form/index.js @@ -25,7 +25,7 @@ export const ArgForm = compose( } }, }), - connect(state => ({ workpad: getWorkpadInfo(state), assets: getAssets(state) })) + connect((state) => ({ workpad: getWorkpadInfo(state), assets: getAssets(state) })) )(Component); ArgForm.propTypes = { diff --git a/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js b/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js index 516ac729935e7..f9a855554db7d 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js +++ b/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js @@ -33,7 +33,7 @@ export class PendingArgValue extends React.PureComponent { setResolvedArgValue(null); } else { argResolver(argValue) - .then(val => setResolvedArgValue(val != null ? val : null)) + .then((val) => setResolvedArgValue(val != null ? val : null)) .catch(() => setResolvedArgValue(null)); // swallow error, it's not important } } diff --git a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx index 728f228d989fb..9a6147050bdbb 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx @@ -27,7 +27,7 @@ const MARKER: AssetType = { }; storiesOf('components/Assets/Asset', module) - .addDecorator(story =>
{story()}
) + .addDecorator((story) =>
{story()}
) .add('airplane', () => ( void; } -export const Asset: FunctionComponent = props => { +export const Asset: FunctionComponent = (props) => { const { asset, onCreate, onCopy, onDelete } = props; const createImage = ( diff --git a/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx b/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx index c27f0c002c3d1..cb177591fd650 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx @@ -104,7 +104,7 @@ export class AssetManager extends PureComponent { private handleFileUpload = (files: FileList | null) => { if (files == null) return; this.setState({ isLoading: true }); - Promise.all(Array.from(files).map(file => this.props.onAssetAdd(file))).finally(() => { + Promise.all(Array.from(files).map((file) => this.props.onAssetAdd(file))).finally(() => { this.setState({ isLoading: false }); }); }; diff --git a/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx b/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx index 8637db8e9f962..c02fc440abb0b 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx @@ -52,7 +52,7 @@ interface Props { onAssetDelete: (asset: AssetType) => void; } -export const AssetModal: FunctionComponent = props => { +export const AssetModal: FunctionComponent = (props) => { const { assetValues, isLoading, @@ -114,7 +114,7 @@ export const AssetModal: FunctionComponent = props => { {assetValues.length ? ( - {assetValues.map(asset => ( + {assetValues.map((asset) => ( { const [type, subtype] = get(file, 'type', '').split('/'); if (type === 'image' && VALID_IMAGE_TYPES.indexOf(subtype) >= 0) { - return encode(file).then(dataurl => { + return encode(file).then((dataurl) => { const dataurlType = 'dataurl'; const existingId = findExistingAsset(dataurlType, dataurl, assetValues); if (existingId) { diff --git a/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx b/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx index 0d7e90c500695..4489e877abf88 100644 --- a/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx +++ b/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx @@ -46,7 +46,7 @@ export class AssetPicker extends PureComponent { return ( - {assets.map(asset => ( + {assets.map((asset) => ( { + onKeyDown = (e) => { const { ESCAPE, TAB, ENTER, UP, DOWN, LEFT, RIGHT } = keyCodes; const { keyCode } = e; const { items } = this.props; @@ -222,14 +222,14 @@ export class Autocomplete extends React.Component {
(this.containerRef = ref)} + ref={(ref) => (this.containerRef = ref)} role="listbox" > {header} {items.map((item, i) => (
(this.itemRefs[i] = ref)} + ref={(ref) => (this.itemRefs[i] = ref)} className={ 'autocompleteItem' + (this.state.selectedIndex === i ? ' autocompleteItem--isActive' : '') diff --git a/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx b/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx index 005a2541cbc2e..672580416c286 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx @@ -22,7 +22,7 @@ class Interactive extends React.Component<{}, { hasButtons: boolean; value: stri hasButtons={this.state.hasButtons} onAddColor={action('onAddColor')} onRemoveColor={action('onRemoveColor')} - onChange={value => this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} />

diff --git a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx index c9db9a9ba3468..8855bffc5e771 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx +++ b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx @@ -75,7 +75,7 @@ export const ColorManager: FunctionComponent = ({ value={value} isInvalid={!validColor && value.length > 0} placeholder={strings.getCodePlaceholder()} - onChange={e => onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} /> {buttons} diff --git a/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx b/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx index 14cd5e6d13b4f..0aef14104030e 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx @@ -21,7 +21,7 @@ class Interactive extends React.Component<{}, { value: string }> { return ( this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} /> ); diff --git a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx index 90f3f8860b4ae..09bc08f9ae541 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx +++ b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx @@ -42,14 +42,14 @@ export const ColorPalette: FunctionComponent = ({ return null; } - colors = colors.filter(color => { + colors = colors.filter((color) => { return tinycolor(color).isValid(); }); return (

- {color => { + {(color) => { const match = tinycolor.equals(color, value); const icon = match ? ( diff --git a/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx b/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx index a2825b210ee33..0a7ed75ee728e 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx @@ -28,11 +28,11 @@ class Interactive extends React.Component<
this.setState({ colors: this.state.colors.concat(value) })} - onRemoveColor={value => - this.setState({ colors: this.state.colors.filter(color => color !== value) }) + onAddColor={(value) => this.setState({ colors: this.state.colors.concat(value) })} + onRemoveColor={(value) => + this.setState({ colors: this.state.colors.filter((color) => color !== value) }) } - onChange={value => this.setState({ value })} + onChange={(value) => this.setState({ value })} hasButtons={this.state.hasButtons} value={this.state.value} /> diff --git a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx index 2cd93b6f0e5c7..2bf17301b7b38 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx @@ -29,7 +29,7 @@ export const ColorPicker: FunctionComponent = ({ const tc = tinycolor(value); const isValidColor = tc.isValid(); - colors = colors.filter(color => { + colors = colors.filter((color) => { return tinycolor(color).isValid(); }); @@ -37,7 +37,7 @@ export const ColorPicker: FunctionComponent = ({ let canAdd = false; if (isValidColor) { - const match = colors.filter(color => tinycolor.equals(value, color)); + const match = colors.filter((color) => tinycolor.equals(value, color)); canRemove = match.length > 0; canAdd = match.length === 0; } diff --git a/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx b/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx index 83923d1f0da1f..63854b8045e93 100644 --- a/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx @@ -27,7 +27,7 @@ class Interactive extends React.Component<
this.setState({ value })} + onChange={(value) => this.setState({ value })} onAddColor={action('onAddColor')} onRemoveColor={action('onRemoveColor')} value={this.state.value} diff --git a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx index f4b0264911734..1be587c31528f 100644 --- a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx +++ b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx @@ -20,7 +20,7 @@ interface Props { className?: string; } -export const ConfirmModal: FunctionComponent = props => { +export const ConfirmModal: FunctionComponent = (props) => { const { isOpen, title, diff --git a/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx b/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx index 56bd0bf5e9f2a..8f73939de69a6 100644 --- a/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx +++ b/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx @@ -137,7 +137,7 @@ export class CustomElementModal extends PureComponent { + onChange={(e) => e.target.value.length <= MAX_NAME_LENGTH && this._handleChange('name', e.target.value) } @@ -154,7 +154,7 @@ export class CustomElementModal extends PureComponent { + onChange={(e) => e.target.value.length <= MAX_DESCRIPTION_LENGTH && this._handleChange('description', e.target.value) } diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js index 285b69f057cd8..de9d192e4608c 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js @@ -51,7 +51,7 @@ export class DatasourceComponent extends PureComponent { state = { defaultIndex: '' }; componentDidMount() { - getDefaultIndex().then(defaultIndex => this.setState({ defaultIndex })); + getDefaultIndex().then((defaultIndex) => this.setState({ defaultIndex })); } componentDidUpdate(prevProps) { @@ -71,7 +71,7 @@ export class DatasourceComponent extends PureComponent { type: 'function', }); - setSelectedDatasource = value => { + setSelectedDatasource = (value) => { const { datasource, resetArgs, @@ -88,7 +88,7 @@ export class DatasourceComponent extends PureComponent { // otherwise, clear the arguments, the form will update them updateArgs && updateArgs({}); } - selectDatasource && selectDatasource(datasources.find(d => d.name === value)); + selectDatasource && selectDatasource(datasources.find((d) => d.name === value)); setSelecting(false); }; diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js b/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js index 153a8a7ef75e6..528c37e46caeb 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js @@ -10,7 +10,7 @@ import { EuiCard, EuiIcon } from '@elastic/eui'; export const DatasourceSelector = ({ onSelect, datasources, current }) => (
- {datasources.map(d => ( + {datasources.map((d) => ( ({ +const mapStateToProps = (state) => ({ element: getSelectedElement(state), pageId: getSelectedPage(state), functionDefinitions: getServerFunctions(state), }); -const mapDispatchToProps = dispatch => ({ - dispatchArgumentAtIndex: props => arg => dispatch(setArgumentAtIndex({ ...props, arg })), - dispatchAstAtIndex: ({ index, element, pageId }) => ast => { +const mapDispatchToProps = (dispatch) => ({ + dispatchArgumentAtIndex: (props) => (arg) => dispatch(setArgumentAtIndex({ ...props, arg })), + dispatchAstAtIndex: ({ index, element, pageId }) => (ast) => { dispatch(flushContext(element.id)); dispatch(setAstAtIndex(index, ast, element, pageId)); }, @@ -32,8 +32,8 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { const { element, pageId, functionDefinitions } = stateProps; const { dispatchArgumentAtIndex, dispatchAstAtIndex } = dispatchProps; - const getDataTableFunctionsByName = name => - functionDefinitions.find(fn => fn.name === name && fn.type === 'datatable'); + const getDataTableFunctionsByName = (name) => + functionDefinitions.find((fn) => fn.name === name && fn.type === 'datatable'); // find the matching datasource from the expression AST const datasourceAst = get(element, 'ast.chain', []) diff --git a/x-pack/plugins/canvas/public/components/datatable/datatable.js b/x-pack/plugins/canvas/public/components/datatable/datatable.js index e0cd3378ff65c..2b7c7464f7b84 100644 --- a/x-pack/plugins/canvas/public/components/datatable/datatable.js +++ b/x-pack/plugins/canvas/public/components/datatable/datatable.js @@ -10,7 +10,7 @@ import PropTypes from 'prop-types'; import moment from 'moment'; import { Paginate } from '../paginate'; -const getIcon = type => { +const getIcon = (type) => { if (type === null) { return; } @@ -36,9 +36,9 @@ const getIcon = type => { return ; }; -const getColumnName = col => (typeof col === 'string' ? col : col.name); +const getColumnName = (col) => (typeof col === 'string' ? col : col.name); -const getColumnType = col => col.type || null; +const getColumnType = (col) => col.type || null; const getFormattedValue = (val, type) => { if (type === 'date') { @@ -56,7 +56,7 @@ export const Datatable = ({ datatable, perPage, paginate, showHeader }) => ( {!showHeader ? null : (
- {datatable.columns.map(col => ( + {datatable.columns.map((col) => ( {rows.map((row, i) => ( - {datatable.columns.map(col => ( + {datatable.columns.map((col) => ( diff --git a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js index 172792b429fcd..808008e5664d6 100644 --- a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js +++ b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js @@ -86,13 +86,13 @@ export class DomPreview extends React.Component { render() { return (
{ + ref={(container) => { this._container = container; }} className="dom-preview" >
{ + ref={(content) => { this._content = content; }} /> diff --git a/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx b/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx index efb28d34d719e..1ed3e0788c313 100644 --- a/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx +++ b/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx @@ -11,7 +11,7 @@ import { ElementCard } from '../element_card'; import { elasticLogo } from '../../../lib/elastic_logo'; storiesOf('components/Elements/ElementCard', module) - .addDecorator(story => ( + .addDecorator((story) => (
({ +const mapStateToProps = (state) => ({ elementStats: getElementStats(state), }); diff --git a/x-pack/plugins/canvas/public/components/element_content/index.js b/x-pack/plugins/canvas/public/components/element_content/index.js index 3d7cca95e10b7..a138c3acb8ec7 100644 --- a/x-pack/plugins/canvas/public/components/element_content/index.js +++ b/x-pack/plugins/canvas/public/components/element_content/index.js @@ -12,7 +12,7 @@ import { getSelectedPage, getPageById } from '../../state/selectors/workpad'; import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; import { ElementContent as Component } from './element_content'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ backgroundColor: getPageById(state, getSelectedPage(state)).style.background, }); diff --git a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js index ab023aef9520f..3429c40073443 100644 --- a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js +++ b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js @@ -91,7 +91,7 @@ export class ElementShareContainer extends React.PureComponent { data-shared-item={shouldTrackComplete ? this.state.renderComplete : undefined} data-render-complete={shouldTrackComplete ? this.state.renderComplete : undefined} className={this.props.className} - ref={ref => (this.sharedItemRef = ref)} + ref={(ref) => (this.sharedItemRef = ref)} > {this.props.children}
diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js index 56a8a148bf915..845fc5927d839 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { Positionable } from '../positionable'; import { ElementContent } from '../element_content'; -export const ElementWrapper = props => { +export const ElementWrapper = (props) => { const { renderable, transformMatrix, width, height, state, handlers } = props; return ( diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/index.js b/x-pack/plugins/canvas/public/components/element_wrapper/index.js index 85882377b7684..390c349ab2ee6 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/index.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/index.js @@ -59,14 +59,14 @@ export const ElementWrapper = compose( connectAdvanced(selectorFactory), withPropsOnChange( (props, nextProps) => !isEqual(props.element, nextProps.element), - props => { + (props) => { const { element, createHandlers } = props; const handlers = createHandlers(element); // this removes element and createHandlers from passed props return { handlers }; } ), - mapProps(props => { + mapProps((props) => { // remove element and createHandlers from props passed to component // eslint-disable-next-line no-unused-vars const { element, createHandlers, selectedPage, ...restProps } = props; diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js index 8ea90974e2c53..33e8eacd902dd 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js @@ -11,12 +11,12 @@ import { fetchEmbeddableRenderable, } from '../../../state/actions/embeddable'; -export const createHandlers = dispatch => { +export const createHandlers = (dispatch) => { let isComplete = false; let oldElement; let completeFn = () => {}; - return element => { + return (element) => { // reset isComplete when element changes if (!isEqual(oldElement, element)) { isComplete = false; diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx index 35eedde59a014..df9dad3e7f678 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx @@ -30,7 +30,7 @@ export class AddEmbeddableFlyout extends React.Component { const embeddableFactories = this.props.getEmbeddableFactories(); // Find the embeddable type from the saved object type - const found = Array.from(embeddableFactories).find(embeddableFactory => { + const found = Array.from(embeddableFactories).find((embeddableFactory) => { return Boolean( embeddableFactory.savedObjectMetaData && embeddableFactory.savedObjectMetaData.type === savedObjectType @@ -46,11 +46,11 @@ export class AddEmbeddableFlyout extends React.Component { const embeddableFactories = this.props.getEmbeddableFactories(); const availableSavedObjects = Array.from(embeddableFactories) - .filter(factory => { + .filter((factory) => { return this.props.availableEmbeddables.includes(factory.type); }) - .map(factory => factory.savedObjectMetaData) - .filter>(function( + .map((factory) => factory.savedObjectMetaData) + .filter>(function ( maybeSavedObjectMetaData ): maybeSavedObjectMetaData is SavedObjectMetaData<{}> { return maybeSavedObjectMetaData !== undefined; diff --git a/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx b/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx index e24ae57cbc606..134efe61c9dcb 100644 --- a/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx +++ b/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx @@ -27,7 +27,7 @@ interface ComponentProps extends Props { children: (props: Props) => ReactChildren; } -const ErrorBoundaryComponent: FunctionComponent = props => ( +const ErrorBoundaryComponent: FunctionComponent = (props) => ( {props.children({ error: props.error, @@ -68,7 +68,7 @@ export const errorBoundaryHoc = compose( this.props.setErrorInfo(errorInfo); }, }), - mapProps>(props => + mapProps>((props) => omit(props, ['setError', 'setErrorInfo']) ) ); diff --git a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js index 9e035db80b4d9..1f865f9b9c6b7 100644 --- a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js +++ b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js @@ -7,10 +7,10 @@ import React from 'react'; import PropTypes from 'prop-types'; -const getDisplayName = Comp => Comp.displayName || Comp.name || 'UnnamedComponent'; +const getDisplayName = (Comp) => Comp.displayName || Comp.name || 'UnnamedComponent'; export function createStatefulPropHoc(fieldname, updater = 'updateValue') { - return Comp => { + return (Comp) => { class WrappedControlledInput extends React.PureComponent { constructor(props) { super(props); @@ -24,7 +24,7 @@ export function createStatefulPropHoc(fieldname, updater = 'updateValue') { this.setState({ value: nextProps[fieldname] }); } - handleChange = ev => { + handleChange = (ev) => { if (ev.target) { this.setState({ value: ev.target.value }); } else { diff --git a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js index 11c8ab88a4cba..16c94a44299a4 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js @@ -11,14 +11,14 @@ import { get } from 'lodash'; export const ESFieldSelect = ({ value, fields = [], onChange, onFocus, onBlur }) => { const selectedOption = value ? [{ label: value }] : []; - const options = fields.map(field => ({ label: field })); + const options = fields.map((field) => ({ label: field })); return ( onChange(get(field, 'label', null))} - onSearchChange={searchValue => { + onSearchChange={(searchValue) => { // resets input when user starts typing if (searchValue) { onChange(null); diff --git a/x-pack/plugins/canvas/public/components/es_field_select/index.js b/x-pack/plugins/canvas/public/components/es_field_select/index.js index 2dc2484083241..e2e86a2a4aea3 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/index.js @@ -19,7 +19,7 @@ export const ESFieldSelect = compose( componentDidUpdate({ index }) { const { value, onChange, setFields } = this.props; if (this.props.index !== index) { - getFields(this.props.index).then(fields => { + getFields(this.props.index).then((fields) => { setFields(fields); }); } diff --git a/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js b/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js index ca2cac5a64793..0b067d94c8a9b 100644 --- a/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js +++ b/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js @@ -9,11 +9,11 @@ import PropTypes from 'prop-types'; import { EuiComboBox } from '@elastic/eui'; export const ESFieldsSelect = ({ selected, fields, onChange, onFocus, onBlur }) => { - const options = fields.map(value => ({ + const options = fields.map((value) => ({ label: value, })); - const selectedOptions = selected.map(value => ({ + const selectedOptions = selected.map((value) => ({ label: value, })); @@ -21,7 +21,7 @@ export const ESFieldsSelect = ({ selected, fields, onChange, onFocus, onBlur }) onChange(values.map(({ label }) => label))} + onChange={(values) => onChange(values.map(({ label }) => label))} className="canvasFieldsSelect" onFocus={onFocus} onBlur={onBlur} diff --git a/x-pack/plugins/canvas/public/components/es_fields_select/index.js b/x-pack/plugins/canvas/public/components/es_fields_select/index.js index aa607a9ebea4a..13b6f4558e6be 100644 --- a/x-pack/plugins/canvas/public/components/es_fields_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_fields_select/index.js @@ -21,7 +21,7 @@ export const ESFieldsSelect = compose( if (this.props.index !== index) { getFields(this.props.index).then((fields = []) => { setFields(fields); - onChange(selected.filter(option => fields.includes(option))); + onChange(selected.filter((option) => fields.includes(option))); }); } }, diff --git a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js index 8f1a4932a5e6c..9bd4966b91891 100644 --- a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js +++ b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js @@ -13,13 +13,13 @@ const defaultIndex = '_all'; export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBlur }) => { const selectedOption = value !== defaultIndex ? [{ label: value }] : []; - const options = indices.map(index => ({ label: index })); + const options = indices.map((index) => ({ label: index })); return ( onChange(get(index, 'label', defaultIndex))} - onSearchChange={searchValue => { + onSearchChange={(searchValue) => { // resets input when user starts typing if (searchValue) { onChange(defaultIndex); @@ -31,7 +31,7 @@ export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBl options={options} singleSelection={{ asPlainText: true }} isClearable={false} - onCreateOption={input => onChange(input || defaultIndex)} + onCreateOption={(input) => onChange(input || defaultIndex)} compressed /> ); diff --git a/x-pack/plugins/canvas/public/components/expression/expression.js b/x-pack/plugins/canvas/public/components/expression/expression.js index f2b7259f8f1f8..37cf1b821d9fd 100644 --- a/x-pack/plugins/canvas/public/components/expression/expression.js +++ b/x-pack/plugins/canvas/public/components/expression/expression.js @@ -28,7 +28,7 @@ const { useRef } = React; const shortcut = (ref, cmd, callback) => ( { + handler={(command) => { const isInputActive = ref.current && ref.current.editor && ref.current.editor.hasTextFocus(); if (isInputActive && command === cmd) { callback(); diff --git a/x-pack/plugins/canvas/public/components/expression/index.js b/x-pack/plugins/canvas/public/components/expression/index.js index c2b559fe03230..4480169dd037d 100644 --- a/x-pack/plugins/canvas/public/components/expression/index.js +++ b/x-pack/plugins/canvas/public/components/expression/index.js @@ -21,13 +21,13 @@ import { setExpression, flushContext } from '../../state/actions/elements'; import { ElementNotSelected } from './element_not_selected'; import { Expression as Component } from './expression'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ pageId: getSelectedPage(state), element: getSelectedElement(state), }); -const mapDispatchToProps = dispatch => ({ - setExpression: (elementId, pageId) => expression => { +const mapDispatchToProps = (dispatch) => ({ + setExpression: (elementId, pageId) => (expression) => { // destroy the context cache dispatch(flushContext(elementId)); @@ -82,14 +82,14 @@ export const Expression = compose( toggleCompactView: ({ isCompact, setCompact }) => () => { setCompact(!isCompact); }, - updateValue: ({ setFormState }) => expression => { + updateValue: ({ setFormState }) => (expression) => { setFormState({ expression, dirty: true, }); }, - setExpression: ({ setExpression, setFormState }) => exp => { - setFormState(prev => ({ + setExpression: ({ setExpression, setFormState }) => (exp) => { + setFormState((prev) => ({ ...prev, dirty: false, })); @@ -98,7 +98,7 @@ export const Expression = compose( }), expressionLifecycle, withPropsOnChange(['formState'], ({ formState }) => ({ - error: (function() { + error: (function () { try { // TODO: We should merge the advanced UI input and this into a single validated expression input. fromExpression(formState.expression); @@ -108,5 +108,5 @@ export const Expression = compose( } })(), })), - branch(props => !props.element, renderComponent(ElementNotSelected)) + branch((props) => !props.element, renderComponent(ElementNotSelected)) )(Component); diff --git a/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx b/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx index 2650b5ebb8fb3..993ee8bde2653 100644 --- a/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx +++ b/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx @@ -18,7 +18,7 @@ interface Props { onUpload: () => void; } -export const FileUpload: FunctionComponent = props => ( +export const FileUpload: FunctionComponent = (props) => ( ); diff --git a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx index 01685cf78d563..4340430829342 100644 --- a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx +++ b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx @@ -20,14 +20,14 @@ interface Props { value?: FontValue; } -export const FontPicker: FunctionComponent = props => { +export const FontPicker: FunctionComponent = (props) => { const { value, onSelect } = props; // While fonts are strongly-typed, we also support custom fonts someone might type in. // So let's cast the fonts and allow for additions. const displayedFonts: DisplayedFont[] = fonts; - if (value && !fonts.find(font => font.value === value)) { + if (value && !fonts.find((font) => font.value === value)) { const label = (value.indexOf(',') >= 0 ? value.split(',')[0] : value).replace(/['"]/g, ''); displayedFonts.push({ value, label }); displayedFonts.sort((a, b) => a.label.localeCompare(b.label)); @@ -36,7 +36,7 @@ export const FontPicker: FunctionComponent = props => { return ( ({ + options={displayedFonts.map((font) => ({ value: font.value, inputDisplay:
{font.label}
, }))} diff --git a/x-pack/plugins/canvas/public/components/fullscreen/index.js b/x-pack/plugins/canvas/public/components/fullscreen/index.js index 8087644b51655..f6404d4097699 100644 --- a/x-pack/plugins/canvas/public/components/fullscreen/index.js +++ b/x-pack/plugins/canvas/public/components/fullscreen/index.js @@ -8,7 +8,7 @@ import { connect } from 'react-redux'; import { getFullscreen } from '../../state/selectors/app'; import { Fullscreen as Component } from './fullscreen'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ isFullscreen: getFullscreen(state), }); diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form.js b/x-pack/plugins/canvas/public/components/function_form/function_form.js index 5c8b745d17bd7..8c9f8847d8eed 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form.js +++ b/x-pack/plugins/canvas/public/components/function_form/function_form.js @@ -22,7 +22,7 @@ function checkState(state) { // alternate render paths based on expression state const branches = [ // if no expressionType was provided, render the ArgTypeUnknown component - branch(props => !props.expressionType, renderComponent(FunctionUnknown)), + branch((props) => !props.expressionType, renderComponent(FunctionUnknown)), // if the expressionType is in a pending state, render ArgTypeContextPending branch(checkState('pending'), renderComponent(FunctionFormContextPending)), // if the expressionType is in an error state, render ArgTypeContextError diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form_component.js b/x-pack/plugins/canvas/public/components/function_form/function_form_component.js index a076cc8dd714c..8503acf21bc1c 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form_component.js +++ b/x-pack/plugins/canvas/public/components/function_form/function_form_component.js @@ -7,7 +7,7 @@ import React from 'react'; import PropTypes from 'prop-types'; -export const FunctionFormComponent = props => { +export const FunctionFormComponent = (props) => { const passedProps = { argResolver: props.argResolver, args: props.args, diff --git a/x-pack/plugins/canvas/public/components/function_form/index.js b/x-pack/plugins/canvas/public/components/function_form/index.js index 774214cf68cec..2b563c30bf50e 100644 --- a/x-pack/plugins/canvas/public/components/function_form/index.js +++ b/x-pack/plugins/canvas/public/components/function_form/index.js @@ -39,8 +39,8 @@ const mapDispatchToProps = (dispatch, { expressionIndex }) => ({ addArgumentValueAtIndex({ index: expressionIndex, element, pageId, argName, value: argValue }) ); }, - updateContext: element => () => dispatch(fetchContext(expressionIndex, element)), - setArgument: (element, pageId) => (argName, valueIndex) => value => { + updateContext: (element) => () => dispatch(fetchContext(expressionIndex, element)), + setArgument: (element, pageId) => (argName, valueIndex) => (value) => { dispatch( setArgumentAtIndex({ index: expressionIndex, diff --git a/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js b/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js index ae2e6404f0bb8..529b40b3dcbe5 100644 --- a/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js +++ b/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { FunctionForm } from '../function_form'; export const FunctionFormList = ({ functionFormItems }) => { - const argTypeComponents = functionFormItems.map(functionFormProps => { + const argTypeComponents = functionFormItems.map((functionFormProps) => { return ( { +const functionFormItems = withProps((props) => { const selectedElement = props.element; const FunctionFormChain = get(selectedElement, 'ast.chain', []); @@ -47,7 +47,7 @@ const functionFormItems = withProps(props => { args: argType.arguments, argType: argType.function, argTypeDef: argTypeDef, - argResolver: argAst => interpretAst(argAst, prevContext), + argResolver: (argAst) => interpretAst(argAst, prevContext), contextExpression: getExpression(prevContext), expressionIndex: i, // preserve the index in the AST nextArgType: nextArg && nextArg.function, diff --git a/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx b/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx index 94340888eafc8..42ff96c8cea15 100644 --- a/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx +++ b/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx @@ -12,17 +12,17 @@ import { ItemGrid } from '../item_grid'; storiesOf('components/ItemGrid', module) .add('simple grid', () => ( -
{item}
} /> +
{item}
} /> )) .add('icon grid', () => ( } + children={(item) => } /> )) .add('color dot grid', () => ( - {item => } + {(item) => } )) .add('complex grid', () => ( @@ -35,7 +35,7 @@ storiesOf('components/ItemGrid', module) ] as Array<{ color: string; icon: IconType }> } > - {item => ( + {(item) => ( diff --git a/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx b/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx index 1c94969292b59..02aa78b5dfe00 100644 --- a/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx +++ b/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx @@ -55,7 +55,9 @@ const getDescriptionListItems = (shortcuts: ShortcutMap[]): DescriptionListItem[ {getPrettyShortcut(shortcut) .split(/( )/g) - .map(key => (key === ' ' ? key : {key}))} + .map((key) => + key === ' ' ? key : {key} + )} ); return acc; diff --git a/x-pack/plugins/canvas/public/components/link/link.js b/x-pack/plugins/canvas/public/components/link/link.js index ce709243ceebf..d973164190592 100644 --- a/x-pack/plugins/canvas/public/components/link/link.js +++ b/x-pack/plugins/canvas/public/components/link/link.js @@ -12,7 +12,7 @@ import { ComponentStrings } from '../../../i18n'; const { Link: strings } = ComponentStrings; -const isModifiedEvent = ev => !!(ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey); +const isModifiedEvent = (ev) => !!(ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey); export class Link extends React.PureComponent { static propTypes = { @@ -27,7 +27,7 @@ export class Link extends React.PureComponent { router: PropTypes.object, }; - navigateTo = (name, params) => ev => { + navigateTo = (name, params) => (ev) => { if (this.props.onClick) { this.props.onClick(ev); } diff --git a/x-pack/plugins/canvas/public/components/page_config/index.js b/x-pack/plugins/canvas/public/components/page_config/index.js index a51e6b4b5d987..7770154c8e477 100644 --- a/x-pack/plugins/canvas/public/components/page_config/index.js +++ b/x-pack/plugins/canvas/public/components/page_config/index.js @@ -14,7 +14,7 @@ import { PageConfig as Component } from './page_config'; const { PageConfig: strings } = ComponentStrings; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const pageIndex = getSelectedPageIndex(state); const page = getPages(state)[pageIndex]; return { page, pageIndex }; @@ -25,7 +25,7 @@ const mapDispatchToProps = { stylePage, setPageTransition }; const mergeProps = (stateProps, dispatchProps) => { return { pageIndex: stateProps.pageIndex, - setBackground: background => { + setBackground: (background) => { const itsTheNewStyle = { ...stateProps.page.style, background }; dispatchProps.stylePage(stateProps.page.id, itsTheNewStyle); }, @@ -37,7 +37,7 @@ const mergeProps = (stateProps, dispatchProps) => { text: displayName, })) ), - setTransition: name => { + setTransition: (name) => { dispatchProps.setPageTransition(stateProps.page.id, { name }); }, }; diff --git a/x-pack/plugins/canvas/public/components/page_config/page_config.js b/x-pack/plugins/canvas/public/components/page_config/page_config.js index 583bf1427aab1..51a4762fca501 100644 --- a/x-pack/plugins/canvas/public/components/page_config/page_config.js +++ b/x-pack/plugins/canvas/public/components/page_config/page_config.js @@ -57,7 +57,7 @@ export const PageConfig = ({ value={transition ? transition.name : ''} options={transitions} compressed - onChange={e => setTransition(e.target.value)} + onChange={(e) => setTransition(e.target.value)} /> {transition ? ( diff --git a/x-pack/plugins/canvas/public/components/page_manager/index.js b/x-pack/plugins/canvas/public/components/page_manager/index.js index ef5de3feb575c..a198b7b8c3d8c 100644 --- a/x-pack/plugins/canvas/public/components/page_manager/index.js +++ b/x-pack/plugins/canvas/public/components/page_manager/index.js @@ -12,7 +12,7 @@ import { getSelectedPage, getWorkpad, getPages, isWriteable } from '../../state/ import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { PageManager as Component } from './page_manager'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { id, css } = getWorkpad(state); return { @@ -24,11 +24,11 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ addPage: () => dispatch(pageActions.addPage()), movePage: (id, position) => dispatch(pageActions.movePage(id, position)), - duplicatePage: id => dispatch(pageActions.duplicatePage(id)), - removePage: id => dispatch(pageActions.removePage(id)), + duplicatePage: (id) => dispatch(pageActions.duplicatePage(id)), + removePage: (id) => dispatch(pageActions.removePage(id)), }); export const PageManager = compose( diff --git a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js index 1abb17c2c2b33..3e2ff9dfe2b22 100644 --- a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js +++ b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js @@ -94,7 +94,7 @@ export class PageManager extends React.PureComponent { } }; - confirmDelete = pageId => { + confirmDelete = (pageId) => { this._isMounted && this.props.setDeleteId(pageId); }; @@ -133,13 +133,13 @@ export class PageManager extends React.PureComponent { return ( - {provided => ( + {(provided) => (
{ + ref={(el) => { if (page.id === selectedPage) { this.activePageRef = el; } @@ -194,12 +194,12 @@ export class PageManager extends React.PureComponent { - {provided => ( + {(provided) => (
{ + ref={(el) => { this.pageListRef = el; provided.innerRef(el); }} diff --git a/x-pack/plugins/canvas/public/components/page_preview/page_controls.js b/x-pack/plugins/canvas/public/components/page_preview/page_controls.js index 727794e72ee15..1251f441f1082 100644 --- a/x-pack/plugins/canvas/public/components/page_preview/page_controls.js +++ b/x-pack/plugins/canvas/public/components/page_preview/page_controls.js @@ -13,12 +13,12 @@ import { ComponentStrings } from '../../../i18n'; const { PagePreviewPageControls: strings } = ComponentStrings; export const PageControls = ({ pageId, onDelete, onDuplicate }) => { - const handleDuplicate = ev => { + const handleDuplicate = (ev) => { ev.preventDefault(); onDuplicate(pageId); }; - const handleDelete = ev => { + const handleDelete = (ev) => { ev.preventDefault(); onDelete(pageId); }; diff --git a/x-pack/plugins/canvas/public/components/paginate/paginate.js b/x-pack/plugins/canvas/public/components/paginate/paginate.js index 52e744ec769e8..8dfa616ed8d14 100644 --- a/x-pack/plugins/canvas/public/components/paginate/paginate.js +++ b/x-pack/plugins/canvas/public/components/paginate/paginate.js @@ -6,7 +6,7 @@ import PropTypes from 'prop-types'; -export const Paginate = props => { +export const Paginate = (props) => { return props.children({ rows: props.partialRows, perPage: props.perPage, @@ -14,7 +14,7 @@ export const Paginate = props => { totalPages: props.totalPages, nextPageEnabled: props.nextPageEnabled, prevPageEnabled: props.prevPageEnabled, - setPage: num => props.setPage(num), + setPage: (num) => props.setPage(num), nextPage: props.nextPage, prevPage: props.prevPage, }); diff --git a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js index e5808dd623530..ca2a499feb84c 100644 --- a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js +++ b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js @@ -13,7 +13,7 @@ import { PaletteSwatch } from '../palette_swatch'; import { palettes } from '../../../common/lib/palettes'; export const PalettePicker = ({ onChange, value, anchorPosition, ariaLabel }) => { - const button = handleClick => ( + const button = (handleClick) => ( diff --git a/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js b/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js index fcc34c8d85448..71d16260e00c7 100644 --- a/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js +++ b/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js @@ -11,7 +11,7 @@ export const PaletteSwatch = ({ colors, gradient }) => { let colorBoxes; if (!gradient) { - colorBoxes = colors.map(color => ( + colorBoxes = colors.map((color) => (
{ // Throw if there is more than one child React.Children.only(children); // This could probably be made nicer by having just one child - const wrappedChildren = React.Children.map(children, child => { + const wrappedChildren = React.Children.map(children, (child) => { const newStyle = { width, height, diff --git a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js index cb9912e717173..db393a8dde4f9 100644 --- a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js +++ b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js @@ -28,7 +28,7 @@ export class RenderToDom extends React.Component { render() { const { domNode, setDomNode, style } = this.props; - const linkRef = refNode => { + const linkRef = (refNode) => { if (!domNode && refNode) { // Initialize the domNode property. This should only happen once, even if config changes. setDomNode(refNode); diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/index.js b/x-pack/plugins/canvas/public/components/render_with_fn/index.js index 473aaaf9d1ac6..37c49624a3940 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/index.js +++ b/x-pack/plugins/canvas/public/components/render_with_fn/index.js @@ -20,7 +20,7 @@ export const RenderWithFn = compose( }) ), withKibana, - withProps(props => ({ + withProps((props) => ({ onError: props.kibana.services.canvas.notify.error, })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js index ce27e99256fc6..763cbd5e53eb1 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js +++ b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js @@ -94,7 +94,7 @@ export class RenderWithFn extends React.Component { } }; - _resetRenderTarget = domNode => { + _resetRenderTarget = (domNode) => { const { handlers } = this.props; if (!domNode) { @@ -122,7 +122,7 @@ export class RenderWithFn extends React.Component { return div; }; - _shouldFullRerender = prevProps => { + _shouldFullRerender = (prevProps) => { // required to stop re-renders on element move, anything that should // cause a re-render needs to be checked here // TODO: fix props passed in to remove this check @@ -146,7 +146,7 @@ export class RenderWithFn extends React.Component { > { + render={(domNode) => { this._domNode = domNode; this._callRenderFn(); }} diff --git a/x-pack/plugins/canvas/public/components/router/router.js b/x-pack/plugins/canvas/public/components/router/router.js index 40c9c469e5505..dd275b3949f34 100644 --- a/x-pack/plugins/canvas/public/components/router/router.js +++ b/x-pack/plugins/canvas/public/components/router/router.js @@ -43,7 +43,7 @@ export class Router extends React.PureComponent { let firstLoad = true; // when the component in the route changes, render it - router.onPathChange(route => { + router.onPathChange((route) => { const { pathname } = route.location; const { component } = route.meta; @@ -64,7 +64,7 @@ export class Router extends React.PureComponent { router .execute() .then(() => onLoad()) - .catch(err => onError(err)); + .catch((err) => onError(err)); } const appState = getAppState(); diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx index 5210210ebaa74..ec0304dd63726 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx @@ -10,7 +10,7 @@ import { action } from '@storybook/addon-actions'; import { ElementControls } from '../element_controls'; storiesOf('components/SavedElementsModal/ElementControls', module) - .addDecorator(story => ( + .addDecorator((story) => (
( + .addDecorator((story) => (
{} }: Props) => { {Object.keys(shapes) .sort() - .map(shapeKey => ( + .map((shapeKey) => ( onChange(shapeKey)}> diff --git a/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx b/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx index 389ee7791baba..4e3d8ae219d29 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx +++ b/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx @@ -20,7 +20,7 @@ class Interactive extends React.Component<{}, { value: string }> { return ( this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} /> ); diff --git a/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx b/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx index b5e44b4996537..b8d5882234899 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx +++ b/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx @@ -21,7 +21,7 @@ interface StateProps { element: PositionedElement | undefined; } -const renderIfElement: React.FunctionComponent = props => { +const renderIfElement: React.FunctionComponent = (props) => { if (props.element) { return ; } diff --git a/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js b/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js index f333705a1a3c6..a9b6b80b9ff01 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js +++ b/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js @@ -18,7 +18,7 @@ import { ElementSettings } from './element_settings'; const { SidebarContent: strings } = ComponentStrings; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ selectedToplevelNodes: getSelectedToplevelNodes(state), selectedElementId: getSelectedElementId(state), }); diff --git a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx index 11c66906a6ef6..5cd9133febc39 100644 --- a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx +++ b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx @@ -17,7 +17,7 @@ const handlers = { }; storiesOf('components/Sidebar/SidebarHeader', module) - .addDecorator(story =>
{story()}
) + .addDecorator((story) =>
{story()}
) .add('default', () => ) .add('with layer controls', () => ( diff --git a/x-pack/plugins/canvas/public/components/sidebar_header/index.js b/x-pack/plugins/canvas/public/components/sidebar_header/index.js index ac282962afb54..aa67de1f55506 100644 --- a/x-pack/plugins/canvas/public/components/sidebar_header/index.js +++ b/x-pack/plugins/canvas/public/components/sidebar_header/index.js @@ -23,33 +23,33 @@ import { SidebarHeader as Component } from './sidebar_header'; /* * TODO: this is all copied from interactive_workpad_page and workpad_shortcuts */ -const mapStateToProps = state => { +const mapStateToProps = (state) => { const pageId = getSelectedPage(state); const nodes = getNodes(state, pageId); const selectedToplevelNodes = getSelectedToplevelNodes(state); const selectedPrimaryShapeObjects = selectedToplevelNodes - .map(id => nodes.find(s => s.id === id)) - .filter(shape => shape); + .map((id) => nodes.find((s) => s.id === id)) + .filter((shape) => shape); const selectedPersistentPrimaryNodes = flatten( - selectedPrimaryShapeObjects.map(shape => - nodes.find(n => n.id === shape.id) // is it a leaf or a persisted group? + selectedPrimaryShapeObjects.map((shape) => + nodes.find((n) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter(s => s.parent === shape.id).map(s => s.id) + : nodes.filter((s) => s.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); return { pageId, - selectedNodes: selectedNodeIds.map(id => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id) => nodes.find((s) => s.id === id)), }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ insertNodes: (selectedNodes, pageId) => dispatch(insertNodes(selectedNodes, pageId)), removeNodes: (nodeIds, pageId) => dispatch(removeElements(nodeIds, pageId)), - selectToplevelNodes: nodes => - dispatch(selectToplevelNodes(nodes.filter(e => !e.position.parent).map(e => e.id))), + selectToplevelNodes: (nodes) => + dispatch(selectToplevelNodes(nodes.filter((e) => !e.position.parent).map((e) => e.id))), elementLayer: (pageId, elementId, movement) => { dispatch(elementLayer({ pageId, elementId, movement })); }, diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js index 179455e15b36e..48d52abb03125 100644 --- a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js +++ b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js @@ -85,9 +85,9 @@ export const TextStylePicker = ({ }); }; - const onAlignmentChange = optionId => doChange('align', optionId); + const onAlignmentChange = (optionId) => doChange('align', optionId); - const onStyleChange = optionId => { + const onStyleChange = (optionId) => { let prop; let value; @@ -106,14 +106,14 @@ export const TextStylePicker = ({
- doChange('family', value)} /> + doChange('family', value)} /> doChange('size', Number(e.target.value))} - options={fontSizes.map(size => ({ text: String(size), value: size }))} + onChange={(e) => doChange('size', Number(e.target.value))} + options={fontSizes.map((size) => ({ text: String(size), value: size }))} prepend="Size" /> @@ -125,7 +125,7 @@ export const TextStylePicker = ({ doChange('color', value)} + onChange={(value) => doChange('color', value)} colors={colors} ariaLabel={strings.getFontColorLabel()} /> diff --git a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx index 01aaeb2388d6c..e9669b3014889 100644 --- a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx +++ b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { ToolTipShortcut } from '../tool_tip_shortcut'; storiesOf('components/ToolTipShortcut', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('with shortcut', () => ) diff --git a/x-pack/plugins/canvas/public/components/toolbar/index.js b/x-pack/plugins/canvas/public/components/toolbar/index.js index 294a44ba0415a..16860063f8a45 100644 --- a/x-pack/plugins/canvas/public/components/toolbar/index.js +++ b/x-pack/plugins/canvas/public/components/toolbar/index.js @@ -19,7 +19,7 @@ import { import { Toolbar as Component } from './toolbar'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadName: getWorkpadName(state), workpadId: getWorkpad(state).id, totalPages: getWorkpad(state).pages.length, @@ -35,15 +35,15 @@ export const Toolbar = compose( router: PropTypes.object, }), withHandlers({ - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.totalPages); props.router.navigateTo('loadWorkpad', { id: props.workpadId, page: pageNumber }); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.router.navigateTo('loadWorkpad', { id: props.workpadId, page: pageNumber }); }, }), - withState('tray', 'setTray', props => props.tray), + withState('tray', 'setTray', (props) => props.tray), withState('showWorkpadManager', 'setShowWorkpadManager', false) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad/index.js b/x-pack/plugins/canvas/public/components/workpad/index.js index fca663f8532d8..72c4588e43c03 100644 --- a/x-pack/plugins/canvas/public/components/workpad/index.js +++ b/x-pack/plugins/canvas/public/components/workpad/index.js @@ -23,7 +23,7 @@ import { trackCanvasUiMetric, METRIC_TYPE } from '../../lib/ui_metric'; import { LAUNCHED_FULLSCREEN, LAUNCHED_FULLSCREEN_AUTOPLAY } from '../../../common/lib/constants'; import { Workpad as Component } from './workpad'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { width, height, id: workpadId, css: workpadCss } = getWorkpad(state); return { pages: getPages(state), @@ -51,7 +51,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { ...ownProps, ...stateProps, ...dispatchProps, - setFullscreen: value => { + setFullscreen: (value) => { dispatchProps.setFullscreen(value); if (value === true) { @@ -93,7 +93,7 @@ export const Workpad = compose( return { getAnimation }; }), withHandlers({ - onPageChange: props => pageNumber => { + onPageChange: (props) => (pageNumber) => { if (pageNumber === props.selectedPageNumber) { return; } @@ -108,11 +108,11 @@ export const Workpad = compose( }), withHandlers({ onTransitionEnd: ({ setTransition }) => () => setTransition(null), - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.pages.length); props.onPageChange(pageNumber); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.onPageChange(pageNumber); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_config/index.js b/x-pack/plugins/canvas/public/components/workpad_config/index.js index aa3bbdce97863..913cf7093e726 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_config/index.js @@ -12,7 +12,7 @@ import { getWorkpad } from '../../state/selectors/workpad'; import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { WorkpadConfig as Component } from './workpad_config'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const workpad = getWorkpad(state); return { @@ -26,9 +26,9 @@ const mapStateToProps = state => { }; const mapDispatchToProps = { - setSize: size => sizeWorkpad(size), - setName: name => setName(name), - setWorkpadCSS: css => setWorkpadCSS(css), + setSize: (size) => sizeWorkpad(size), + setName: (name) => setName(name), + setWorkpadCSS: (css) => setWorkpadCSS(css), }; export const WorkpadConfig = connect(mapStateToProps, mapDispatchToProps)(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js index 7dfc378432b57..45758c9965653 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js +++ b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js @@ -76,7 +76,7 @@ export class WorkpadConfig extends PureComponent { - setName(e.target.value)} /> + setName(e.target.value)} /> @@ -86,7 +86,7 @@ export class WorkpadConfig extends PureComponent { setSize({ width: Number(e.target.value), height: size.height })} + onChange={(e) => setSize({ width: Number(e.target.value), height: size.height })} value={size.width} /> @@ -107,7 +107,7 @@ export class WorkpadConfig extends PureComponent { setSize({ height: Number(e.target.value), width: size.width })} + onChange={(e) => setSize({ height: Number(e.target.value), width: size.width })} value={size.height} /> @@ -152,7 +152,7 @@ export class WorkpadConfig extends PureComponent { aria-label={strings.getGlobalCSSTooltip()} value={css} compressed - onChange={e => this.setState({ css: e.target.value })} + onChange={(e) => this.setState({ css: e.target.value })} rows={10} /> diff --git a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts index a8bb7177dbd24..5debb675af659 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts @@ -67,7 +67,7 @@ const mapStateToProps = (state: State) => { selectedPrimaryShapeObjects.map((shape: PositionedElement) => nodes.find((n: PositionedElement) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter((s: PositionedElement) => s.position.parent === shape.id).map(s => s.id) + : nodes.filter((s: PositionedElement) => s.position.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); @@ -75,7 +75,7 @@ const mapStateToProps = (state: State) => { return { pageId, selectedToplevelNodes, - selectedNodes: selectedNodeIds.map((id: string) => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id: string) => nodes.find((s) => s.id === id)), state, }; }; @@ -86,7 +86,9 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ removeNodes: (nodeIds: string[], pageId: string) => dispatch(removeElements(nodeIds, pageId)), selectToplevelNodes: (nodes: PositionedElement[]) => dispatch( - selectToplevelNodes(nodes.filter((e: PositionedElement) => !e.position.parent).map(e => e.id)) + selectToplevelNodes( + nodes.filter((e: PositionedElement) => !e.position.parent).map((e) => e.id) + ) ), elementLayer: (pageId: string, elementId: string, movement: number) => { dispatch(elementLayer({ pageId, elementId, movement })); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js b/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js index fc0bd4c74ba24..42396b87d2c73 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js @@ -27,7 +27,7 @@ import { FullscreenControl as Component } from './fullscreen_control'; // TODO: a lot of this is borrowed code from `/components/workpad/index.js`. // We should consider extracting the next/prev page logic into to a shared lib file. -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadId: getWorkpad(state).id, pages: getPages(state), selectedPageNumber: getSelectedPageIndex(state) + 1, @@ -35,12 +35,12 @@ const mapStateToProps = state => ({ autoplayEnabled: getAutoplay(state).enabled, }); -const mapDispatchToProps = dispatch => ({ - setFullscreen: value => { +const mapDispatchToProps = (dispatch) => ({ + setFullscreen: (value) => { dispatch(setFullscreen(value)); value && dispatch(selectToplevelNodes([])); }, - enableAutoplay: enabled => dispatch(enableAutoplay(enabled)), + enableAutoplay: (enabled) => dispatch(enableAutoplay(enabled)), fetchAllRenderables: () => dispatch(fetchAllRenderables()), }); @@ -49,7 +49,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { ...ownProps, ...stateProps, ...dispatchProps, - setFullscreen: value => { + setFullscreen: (value) => { dispatchProps.setFullscreen(value); if (value === true) { @@ -89,7 +89,7 @@ export const FullscreenControl = compose( return { getAnimation }; }), withHandlers({ - onPageChange: props => pageNumber => { + onPageChange: (props) => (pageNumber) => { if (pageNumber === props.selectedPageNumber) { return; } @@ -104,11 +104,11 @@ export const FullscreenControl = compose( }), withHandlers({ onTransitionEnd: ({ setTransition }) => () => setTransition(null), - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.pages.length); props.onPageChange(pageNumber); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.onPageChange(pageNumber); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts index 1ed39b62cccad..64712f0df8d6c 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts @@ -33,7 +33,7 @@ const { WorkpadHeaderShareMenu: strings } = ComponentStrings; const getUnsupportedRenderers = (state: State) => { const renderers: string[] = []; const expressions = getRenderedWorkpadExpressions(state); - expressions.forEach(expression => { + expressions.forEach((expression) => { if (!renderFunctionNames.includes(expression)) { renderers.push(expression); } @@ -71,7 +71,7 @@ export const ShareWebsiteFlyout = compose onCopy: () => { kibana.services.canvas.notify.info(strings.getCopyShareConfigMessage()); }, - onDownload: type => { + onDownload: (type) => { switch (type) { case 'share': downloadRenderedWorkpad(renderedWorkpad); @@ -83,7 +83,7 @@ export const ShareWebsiteFlyout = compose const basePath = kibana.services.http.basePath.get(); arrayBufferFetch .post(`${basePath}${API_ROUTE_SHAREABLE_ZIP}`, JSON.stringify(renderedWorkpad)) - .then(blob => downloadZippedRuntime(blob.data)) + .then((blob) => downloadZippedRuntime(blob.data)) .catch((err: Error) => { kibana.services.canvas.notify.error(err, { title: strings.getShareableZipErrorTitle(workpad.name), diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts index 9a8936ada6d1e..17fcc50334a8f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts @@ -46,7 +46,7 @@ export const ShareMenu = compose( withKibana, withProps( ({ workpad, pageCount, kibana }: Props & WithKibanaProps): ComponentProps => ({ - getExportUrl: type => { + getExportUrl: (type) => { if (type === 'pdf') { const pdfUrl = getPdfUrl(workpad, { pageCount }, kibana.services.http.basePath); return getAbsoluteUrl(pdfUrl); @@ -54,7 +54,7 @@ export const ShareMenu = compose( throw new Error(strings.getUnknownExportErrorMessage(type)); }, - onCopy: type => { + onCopy: (type) => { switch (type) { case 'pdf': kibana.services.canvas.notify.info(strings.getCopyPDFMessage()); @@ -66,7 +66,7 @@ export const ShareMenu = compose( throw new Error(strings.getUnknownExportErrorMessage(type)); } }, - onExport: type => { + onExport: (type) => { switch (type) { case 'pdf': return createPdf(workpad, { pageCount }, kibana.services.http.basePath) diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts index 6c7d7ddd0a793..63e7c26cebb04 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts @@ -12,7 +12,7 @@ import { fetch } from '../../../../common/lib/fetch'; import { IBasePath } from 'kibana/public'; const basePath = ({ - prepend: jest.fn().mockImplementation(s => `basepath/s/spacey/${s}`), + prepend: jest.fn().mockImplementation((s) => `basepath/s/spacey/${s}`), get: () => 'basepath/s/spacey', serverBasePath: `basepath`, } as unknown) as IBasePath; diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx index cfd599b1d9f3f..d2e76f0afb3e7 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx @@ -151,7 +151,7 @@ export const AutoRefreshControls = ({ refreshInterval, setRefresh, disableInterv
- setRefresh(value)} /> + setRefresh(value)} />
); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx index ab34f332dc126..cda5733cfcf47 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx @@ -30,7 +30,7 @@ export const CustomInterval = ({ gutterSize, buttonSize, onSubmit, defaultValue return ( { + onSubmit={(ev) => { ev.preventDefault(); if (!isInvalid && refreshInterval) { onSubmit(refreshInterval); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx index e63eed9f9df53..391a17c39523c 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx @@ -118,7 +118,7 @@ export const KioskControls = ({ autoplayInterval, onSetInterval }: Props) => { - onSetInterval(value)} /> + onSetInterval(value)} /> ); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx index b6f108cda37f6..af0a9ed460b8f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx @@ -180,7 +180,7 @@ export const ViewMenu: FunctionComponent = ({ content: ( setRefresh(val)} + setRefresh={(val) => setRefresh(val)} disableInterval={() => disableInterval()} /> ), diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/index.js b/x-pack/plugins/canvas/public/components/workpad_loader/index.js index 8b190338db49e..ab07d5d722405 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/index.js @@ -20,7 +20,7 @@ import { WorkpadLoader as Component } from './workpad_loader'; const { WorkpadLoader: strings } = ComponentStrings; const { WorkpadLoader: errors } = ErrorStrings; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadId: getWorkpad(state).id, canUserWrite: canUserWrite(state), }); @@ -37,7 +37,7 @@ export const WorkpadLoader = compose( })), withHandlers(({ kibana }) => ({ // Workpad creation via navigation - createWorkpad: props => async workpad => { + createWorkpad: (props) => async (workpad) => { // workpad data uploaded, create and load it if (workpad != null) { try { @@ -55,7 +55,7 @@ export const WorkpadLoader = compose( }, // Workpad search - findWorkpads: ({ setWorkpads }) => async text => { + findWorkpads: ({ setWorkpads }) => async (text) => { try { const workpads = await workpadService.find(text); setWorkpads(workpads); @@ -65,10 +65,10 @@ export const WorkpadLoader = compose( }, // Workpad import/export methods - downloadWorkpad: () => workpadId => downloadWorkpad(workpadId), + downloadWorkpad: () => (workpadId) => downloadWorkpad(workpadId), // Clone workpad given an id - cloneWorkpad: props => async workpadId => { + cloneWorkpad: (props) => async (workpadId) => { try { const workpad = await workpadService.get(workpadId); workpad.name = strings.getClonedWorkpadName(workpad.name); @@ -81,20 +81,20 @@ export const WorkpadLoader = compose( }, // Remove workpad given an array of id - removeWorkpads: props => async workpadIds => { + removeWorkpads: (props) => async (workpadIds) => { const { setWorkpads, workpads, workpadId: loadedWorkpad } = props; - const removeWorkpads = workpadIds.map(id => + const removeWorkpads = workpadIds.map((id) => workpadService .remove(id) .then(() => ({ id, err: null })) - .catch(err => ({ + .catch((err) => ({ id, err, })) ); - return Promise.all(removeWorkpads).then(results => { + return Promise.all(removeWorkpads).then((results) => { let redirectHome = false; const [passes, errored] = results.reduce( @@ -135,8 +135,8 @@ export const WorkpadLoader = compose( }); }, })), - withProps(props => ({ - formatDate: date => { + withProps((props) => ({ + formatDate: (date) => { const dateFormat = props.kibana.services.uiSettings.get('dateFormat'); return date && moment(date).format(dateFormat); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js index 41719e6d6b820..28cfac11e76bd 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js @@ -87,14 +87,14 @@ export class WorkpadLoader extends React.PureComponent { }; // create new workpad from uploaded JSON - onUpload = async workpad => { + onUpload = async (workpad) => { this.setState({ createPending: true }); await this.props.createWorkpad(workpad); this._isMounted && this.setState({ createPending: false }); }; // clone existing workpad - cloneWorkpad = async workpad => { + cloneWorkpad = async (workpad) => { this.setState({ createPending: true }); await this.props.cloneWorkpad(workpad.id); this._isMounted && this.setState({ createPending: false }); @@ -108,7 +108,7 @@ export class WorkpadLoader extends React.PureComponent { removeWorkpads = () => { const { selectedWorkpads } = this.state; - this.props.removeWorkpads(selectedWorkpads.map(({ id }) => id)).then(remainingIds => { + this.props.removeWorkpads(selectedWorkpads.map(({ id }) => id)).then((remainingIds) => { const remainingWorkpads = remainingIds.length > 0 ? selectedWorkpads.filter(({ id }) => remainingIds.includes(id)) @@ -127,7 +127,7 @@ export class WorkpadLoader extends React.PureComponent { this.state.selectedWorkpads.forEach(({ id }) => this.props.downloadWorkpad(id)); }; - onSelectionChange = selectedWorkpads => { + onSelectionChange = (selectedWorkpads) => { this.setState({ selectedWorkpads }); }; @@ -145,7 +145,7 @@ export class WorkpadLoader extends React.PureComponent { const actions = [ { - render: workpad => ( + render: (workpad) => ( @@ -202,7 +202,7 @@ export class WorkpadLoader extends React.PureComponent { sortable: true, dataType: 'date', width: '20%', - render: date => this.props.formatDate(date), + render: (date) => this.props.formatDate(date), }, { field: '@timestamp', @@ -210,7 +210,7 @@ export class WorkpadLoader extends React.PureComponent { sortable: true, dataType: 'date', width: '20%', - render: date => this.props.formatDate(date), + render: (date) => this.props.formatDate(date), }, { name: '', actions, width: '5%' }, ]; @@ -374,7 +374,7 @@ export class WorkpadLoader extends React.PureComponent { return ( - {pagination => ( + {(pagination) => ( @@ -387,7 +387,7 @@ export class WorkpadLoader extends React.PureComponent { )} { + onChange={(text) => { pagination.setPage(0); this.props.findWorkpads(text); }} diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js index c2d16949870ea..c72807681306f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js @@ -23,7 +23,7 @@ export class WorkpadSearch extends React.PureComponent { triggerChange = debounce(this.props.onChange, 150); - setSearchText = ev => { + setSearchText = (ev) => { const text = ev.target.value; this.setState({ searchText: text }); this.triggerChange(text); diff --git a/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js b/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js index 731656dd4e095..648ad161ca92a 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js @@ -14,7 +14,7 @@ import { matrixToAngle } from '../../lib/aeroelastic/matrix'; import { isGroupId, elementToShape } from './utils'; export * from './utils'; -const shapeToElement = shape => ({ +const shapeToElement = (shape) => ({ left: shape.transformMatrix[12] - shape.a, top: shape.transformMatrix[13] - shape.b, width: shape.a * 2, @@ -26,7 +26,7 @@ const shapeToElement = shape => ({ const globalPositionUpdates = (setMultiplePositions, { shapes, gestureEnd }, unsortedElements) => { const ascending = (a, b) => (a.id < b.id ? -1 : 1); - const relevant = s => s.type !== 'annotation' && s.subtype !== 'adHocGroup'; + const relevant = (s) => s.type !== 'annotation' && s.subtype !== 'adHocGroup'; const elements = unsortedElements.filter(relevant).sort(ascending); const repositionings = shapes .filter(relevant) @@ -62,26 +62,26 @@ const globalPositionUpdates = (setMultiplePositions, { shapes, gestureEnd }, uns return repositionings; }; -const dedupe = (d, i, a) => a.findIndex(s => s.id === d.id) === i; +const dedupe = (d, i, a) => a.findIndex((s) => s.id === d.id) === i; -const missingParentCheck = groups => { - const idMap = arrayToMap(groups.map(g => g.id)); - groups.forEach(g => { +const missingParentCheck = (groups) => { + const idMap = arrayToMap(groups.map((g) => g.id)); + groups.forEach((g) => { if (g.parent && !idMap[g.parent]) { g.parent = null; } }); }; -export const shapesForNodes = nodes => { +export const shapesForNodes = (nodes) => { const rawShapes = nodes .map(elementToShape) // filtering to eliminate residual element of a possible group that had been deleted in Redux - .filter((d, i, a) => !isGroupId(d.id) || a.find(s => s.parent === d.id)) + .filter((d, i, a) => !isGroupId(d.id) || a.find((s) => s.parent === d.id)) .filter(dedupe); missingParentCheck(rawShapes); const getLocalMatrix = getLocalTransformMatrix(rawShapes); - return rawShapes.map(s => ({ ...s, localTransformMatrix: getLocalMatrix(s) })); + return rawShapes.map((s) => ({ ...s, localTransformMatrix: getLocalMatrix(s) })); }; const updateGlobalPositionsInRedux = (setMultiplePositions, scene, unsortedElements) => { @@ -91,17 +91,17 @@ const updateGlobalPositionsInRedux = (setMultiplePositions, scene, unsortedEleme } }; -export const globalStateUpdater = (dispatch, globalState) => state => { +export const globalStateUpdater = (dispatch, globalState) => (state) => { const nextScene = state.currentScene; const page = getSelectedPage(globalState); const elements = getNodes(globalState, page); const shapes = nextScene.shapes; - const persistableGroups = shapes.filter(s => s.subtype === 'persistentGroup').filter(dedupe); - const persistedGroups = elements.filter(e => isGroupId(e.id)).filter(dedupe); + const persistableGroups = shapes.filter((s) => s.subtype === 'persistentGroup').filter(dedupe); + const persistedGroups = elements.filter((e) => isGroupId(e.id)).filter(dedupe); - persistableGroups.forEach(g => { + persistableGroups.forEach((g) => { if ( - !persistedGroups.find(p => { + !persistedGroups.find((p) => { if (!p.id) { throw new Error('Element has no id'); } @@ -123,12 +123,13 @@ export const globalStateUpdater = (dispatch, globalState) => state => { const elementsToRemove = persistedGroups.filter( // list elements for removal if they're not in the persistable set, or if there's no longer an associated element // the latter of which shouldn't happen, so it's belts and braces - p => - !persistableGroups.find(g => p.id === g.id) || !elements.find(e => e.position.parent === p.id) + (p) => + !persistableGroups.find((g) => p.id === g.id) || + !elements.find((e) => e.position.parent === p.id) ); updateGlobalPositionsInRedux( - positions => dispatch(setMultiplePositions(positions.map(p => ({ ...p, pageId: page })))), + (positions) => dispatch(setMultiplePositions(positions.map((p) => ({ ...p, pageId: page })))), nextScene, elements ); @@ -137,7 +138,7 @@ export const globalStateUpdater = (dispatch, globalState) => state => { // remove elements for groups that were ungrouped dispatch( removeElements( - elementsToRemove.map(e => e.id), + elementsToRemove.map((e) => e.id), page ) ); @@ -149,9 +150,9 @@ export const globalStateUpdater = (dispatch, globalState) => state => { dispatch( selectToplevelNodes( flatten( - selectedPrimaryShapes.map(n => - n.startsWith('group') && (shapes.find(s => s.id === n) || {}).subtype === 'adHocGroup' - ? shapes.filter(s => s.type !== 'annotation' && s.parent === n).map(s => s.id) + selectedPrimaryShapes.map((n) => + n.startsWith('group') && (shapes.find((s) => s.id === n) || {}).subtype === 'adHocGroup' + ? shapes.filter((s) => s.type !== 'annotation' && s.parent === n).map((s) => s.id) : [n] ) ) @@ -160,10 +161,10 @@ export const globalStateUpdater = (dispatch, globalState) => state => { } }; -export const crawlTree = shapes => shapeId => { - const rec = shapeId => [ +export const crawlTree = (shapes) => (shapeId) => { + const rec = (shapeId) => [ shapeId, - ...flatten(shapes.filter(s => s.position.parent === shapeId).map(s => rec(s.id))), + ...flatten(shapes.filter((s) => s.position.parent === shapeId).map((s) => rec(s.id))), ]; return rec(shapeId); }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/utils.js b/x-pack/plugins/canvas/public/components/workpad_page/utils.js index 04b1e02d422de..0289d96f91f0b 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/utils.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/utils.js @@ -6,9 +6,9 @@ import { multiply, rotateZ, translate } from '../../lib/aeroelastic/matrix'; -export const isGroupId = id => id.startsWith('group'); +export const isGroupId = (id) => id.startsWith('group'); -const headerData = id => +const headerData = (id) => isGroupId(id) ? { id, type: 'group', subtype: 'persistentGroup' } : { id, type: 'rectangleElement', subtype: '' }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js index 2d0f8ee5aa0aa..21f4a5b68b6c9 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js @@ -33,7 +33,7 @@ const setupHandler = (commit, canvasOrigin, zoomScale) => { commit('cursorPosition', {}); } }; - window.onmouseup = e => { + window.onmouseup = (e) => { e.stopPropagation(); const { clientX, clientY, altKey, metaKey, shiftKey, ctrlKey } = e; const { x, y } = localMousePosition(canvasOrigin, clientX, clientY, zoomScale); @@ -81,7 +81,7 @@ const handleMouseDown = (commit, e, canvasOrigin, zoomScale, allowDrag = true) = }; export const eventHandlers = { - onMouseDown: props => e => + onMouseDown: (props) => (e) => handleMouseDown( props.commit, e, @@ -89,8 +89,9 @@ export const eventHandlers = { props.zoomScale, props.canDragElement(e.target) ), - onMouseMove: props => e => handleMouseMove(props.commit, e, props.canvasOrigin, props.zoomScale), - onMouseLeave: props => e => handleMouseLeave(props.commit, e), - onWheel: props => e => handleMouseMove(props.commit, e, props.canvasOrigin), + onMouseMove: (props) => (e) => + handleMouseMove(props.commit, e, props.canvasOrigin, props.zoomScale), + onMouseLeave: (props) => (e) => handleMouseLeave(props.commit, e), + onWheel: (props) => (e) => handleMouseMove(props.commit, e, props.canvasOrigin), resetHandler: () => () => resetHandler(), }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js index 2500a412c0fac..41f78165a7394 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js @@ -76,7 +76,7 @@ function closest(s) { // If you interact with an embeddable panel, only the header should be draggable // This function will determine if an element is an embeddable body or not -const isEmbeddableBody = element => { +const isEmbeddableBody = (element) => { const hasClosest = typeof element.closest === 'function'; if (hasClosest) { @@ -94,7 +94,7 @@ const isEmbeddableBody = element => { // Some elements in an embeddable may be portaled out of the embeddable container. // We do not want clicks on those to trigger drags, etc, in the workpad. This function // will check to make sure the clicked item is actually in the container -const isInWorkpad = element => { +const isInWorkpad = (element) => { const hasClosest = typeof element.closest === 'function'; const workpadContainerSelector = '.canvasWorkpadContainer'; @@ -114,7 +114,7 @@ const componentLayoutState = ({ width, }) => { const shapes = shapesForNodes(elements); - const selectedShapes = selectedToplevelNodes.filter(e => shapes.find(s => s.id === e)); + const selectedShapes = selectedToplevelNodes.filter((e) => shapes.find((s) => s.id === e)); const newState = { primaryUpdate: null, currentScene: { @@ -145,13 +145,13 @@ const mapStateToProps = (state, ownProps) => { const selectedToplevelNodes = state.transient.selectedToplevelNodes; const nodes = getNodes(state, ownProps.pageId); const selectedPrimaryShapeObjects = selectedToplevelNodes - .map(id => nodes.find(s => s.id === id)) - .filter(shape => shape); + .map((id) => nodes.find((s) => s.id === id)) + .filter((shape) => shape); const selectedPersistentPrimaryNodes = flatten( - selectedPrimaryShapeObjects.map(shape => - nodes.find(n => n.id === shape.id) // is it a leaf or a persisted group? + selectedPrimaryShapeObjects.map((shape) => + nodes.find((n) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter(s => s.parent === shape.id).map(s => s.id) + : nodes.filter((s) => s.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); @@ -160,23 +160,25 @@ const mapStateToProps = (state, ownProps) => { isEditable: !getFullscreen(state) && isWriteable(state) && canUserWrite(state), elements: nodes, selectedToplevelNodes, - selectedNodes: selectedNodeIds.map(id => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id) => nodes.find((s) => s.id === id)), pageStyle: getPageById(state, ownProps.pageId).style, zoomScale: getZoomScale(state), }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ dispatch, insertNodes: (selectedNodes, pageId) => dispatch(insertNodes(selectedNodes, pageId)), removeNodes: (nodeIds, pageId) => dispatch(removeElements(nodeIds, pageId)), - selectToplevelNodes: nodes => - dispatch(selectToplevelNodes(nodes.filter(e => !e.position.parent).map(e => e.id))), + selectToplevelNodes: (nodes) => + dispatch(selectToplevelNodes(nodes.filter((e) => !e.position.parent).map((e) => e.id))), elementLayer: (pageId, elementId, movement) => dispatch(elementLayer({ pageId, elementId, movement })), - setMultiplePositions: pageId => repositionedNodes => + setMultiplePositions: (pageId) => (repositionedNodes) => dispatch( - setMultiplePositions(repositionedNodes.map(node => ({ ...node, pageId, elementId: node.id }))) + setMultiplePositions( + repositionedNodes.map((node) => ({ ...node, pageId, elementId: node.id })) + ) ), }); @@ -226,8 +228,8 @@ export const InteractivePage = compose( }; }), withProps(({ aeroStore, elements }) => { - const elementLookup = new Map(elements.map(element => [element.id, element])); - const elementsToRender = aeroStore.getCurrentState().currentScene.shapes.map(shape => { + const elementLookup = new Map(elements.map((element) => [element.id, element])); + const elementsToRender = aeroStore.getCurrentState().currentScene.shapes.map((shape) => { const element = elementLookup.get(shape.id); return element ? { ...shape, width: shape.a * 2, height: shape.b * 2, filter: element.filter } @@ -240,7 +242,7 @@ export const InteractivePage = compose( })), withProps((...props) => ({ ...props, - canDragElement: element => { + canDragElement: (element) => { return !isEmbeddableBody(element) && isInWorkpad(element); const hasClosest = typeof element.closest === 'function'; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js index 68f47f35c6fa1..152da323e89ea 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js @@ -71,7 +71,7 @@ export class InteractiveWorkpadPage extends PureComponent {
{ + ref={(node) => { if (!canvasOrigin && node && node.getBoundingClientRect) { saveCanvasOrigin(() => () => node.getBoundingClientRect()); } @@ -92,7 +92,7 @@ export class InteractiveWorkpadPage extends PureComponent { {shortcuts} {elements - .map(node => { + .map((node) => { if (node.type === 'annotation') { const props = { key: node.id, @@ -127,7 +127,7 @@ export class InteractiveWorkpadPage extends PureComponent { return ; } }) - .filter(element => !!element)} + .filter((element) => !!element)}
); } diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js index 9e8962755e00b..aa620b812f76d 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js @@ -25,8 +25,8 @@ export class StaticWorkpadPage extends PureComponent { style={{ ...pageStyle, ...animationStyle, height, width }} > {elements - .filter(node => !isGroupId(node.id)) - .map(element => ( + .filter((node) => !isGroupId(node.id)) + .map((element) => ( ))}
diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/index.js b/x-pack/plugins/canvas/public/components/workpad_templates/index.js index a17b77b74e499..73bcf017475b6 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_templates/index.js @@ -22,7 +22,7 @@ export const WorkpadTemplates = compose( withKibana, withHandlers(({ kibana }) => ({ // Clone workpad given an id - cloneWorkpad: props => workpad => { + cloneWorkpad: (props) => (workpad) => { workpad.id = getId('workpad'); workpad.name = `My Canvas Workpad - ${workpad.name}`; // Remove unneeded fields @@ -32,7 +32,7 @@ export const WorkpadTemplates = compose( return workpadService .create(workpad) .then(() => props.router.navigateTo('loadWorkpad', { id: workpad.id, page: 1 })) - .catch(err => + .catch((err) => kibana.services.canvas.notify.error(err, { title: `Couldn't clone workpad template` }) ); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js index a9a157f5675f8..80ee5a0396704 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js +++ b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js @@ -51,7 +51,7 @@ export class WorkpadTemplates extends React.PureComponent { onSearch = ({ queryText }) => this.setState(extractSearch(queryText)); - cloneTemplate = template => this.props.cloneWorkpad(template).then(() => this.props.onClose()); + cloneTemplate = (template) => this.props.cloneWorkpad(template).then(() => this.props.onClose()); renderWorkpadTable = ({ rows, pageNumber, totalPages, setPage }) => { const { sortField, sortDirection } = this.state; @@ -90,7 +90,7 @@ export class WorkpadTemplates extends React.PureComponent { sortable: false, dataType: 'string', width: '30%', - render: tags => , + render: (tags) => , }, ]; @@ -148,7 +148,7 @@ export class WorkpadTemplates extends React.PureComponent { const filteredTemplates = sortedTemplates.filter(({ name = '', help = '', tags = [] }) => { const tagMatch = filterTags.length - ? filterTags.every(filterTag => tags.indexOf(filterTag) > -1) + ? filterTags.every((filterTag) => tags.indexOf(filterTag) > -1) : true; const lowercaseSearch = searchTerm.toLowerCase(); @@ -162,7 +162,7 @@ export class WorkpadTemplates extends React.PureComponent { return ( - {pagination => ( + {(pagination) => ( {this.renderSearch()} diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx index 51a1608df67ae..5fdc88ed62406 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx @@ -27,7 +27,7 @@ const defaultValues: Arguments = { class Interactive extends React.Component<{}, Arguments> { public state = defaultValues; - _getArgValue: (arg: T) => Arguments[T] = arg => { + _getArgValue: (arg: T) => Arguments[T] = (arg) => { return this.state[arg]; }; @@ -50,18 +50,18 @@ class Interactive extends React.Component<{}, Arguments> { } } -const getArgValue: (arg: T) => Arguments[T] = arg => { +const getArgValue: (arg: T) => Arguments[T] = (arg) => { return defaultValues[arg]; }; storiesOf('arguments/ContainerStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended', () => ); storiesOf('arguments/ContainerStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('appearance form', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx index 71d95603cfebd..4ef17fbe87616 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx @@ -19,7 +19,7 @@ const defaultValues: Arguments = { class Interactive extends React.Component<{}, Arguments> { public state = defaultValues; - _getArgValue: (arg: T) => Arguments[T] = arg => { + _getArgValue: (arg: T) => Arguments[T] = (arg) => { return this.state[arg]; }; @@ -39,18 +39,18 @@ class Interactive extends React.Component<{}, Arguments> { } } -const getArgValue: (arg: T) => Arguments[T] = arg => { +const getArgValue: (arg: T) => Arguments[T] = (arg) => { return defaultValues[arg]; }; storiesOf('arguments/ContainerStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/ContainerStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple template', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx index 929eaeb02f3c7..c833ed3e99aa1 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx @@ -79,7 +79,7 @@ export const BorderForm: FunctionComponent = ({ namedChange('borderWidth')(Number(e.target.value))} + onChange={(e) => namedChange('borderWidth')(Number(e.target.value))} />
@@ -89,7 +89,7 @@ export const BorderForm: FunctionComponent = ({ ({ + options={Object.values(BorderStyle).map((style) => ({ value: style, inputDisplay:
, }))} @@ -103,7 +103,7 @@ export const BorderForm: FunctionComponent = ({ namedChange('borderRadius')(e.target.value)} + onChange={(e) => namedChange('borderRadius')(e.target.value)} /> diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx index cb7a5d606c7d9..3e002ead22d4b 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx @@ -27,7 +27,7 @@ export const SimpleTemplate: FunctionComponent = ({ getArgValue, setArgVa
setArgValue('backgroundColor', color)} + onChange={(color) => setArgValue('backgroundColor', color)} colors={workpad.colors} anchorPosition="leftCenter" ariaLabel={strings.getDisplayName()} diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js index 46a97f7c15d74..3e88d60b40d5f 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js @@ -14,7 +14,7 @@ import { ArgTypesStrings } from '../../../i18n'; const { Font: strings } = ArgTypesStrings; -export const FontArgInput = props => { +export const FontArgInput = (props) => { const { onValueChange, argValue, workpad } = props; const chain = get(argValue, 'chain.0', {}); const chainArgs = get(chain, 'arguments', {}); @@ -27,7 +27,7 @@ export const FontArgInput = props => { const newValue = set( argValue, ['chain', 0, 'arguments'], - mapValues(newSpec, v => [v]) + mapValues(newSpec, (v) => [v]) ); return onValueChange(newValue); } diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx index 7e00bd4f33a8a..4a300b3de8923 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx @@ -44,7 +44,7 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -61,14 +61,14 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio } storiesOf('arguments/SeriesStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .addDecorator(withKnobs) .add('extended', () => ); storiesOf('arguments/SeriesStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended: defaults', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx index 037b15d5c51e9..f9b175e84ec8e 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx @@ -35,7 +35,7 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -49,13 +49,13 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio } storiesOf('arguments/SeriesStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/SeriesStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple: no labels', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx index 615179a3f6f68..e0fe6e60c1dab 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx @@ -35,7 +35,7 @@ export interface Props { }; } -export const ExtendedTemplate: FunctionComponent = props => { +export const ExtendedTemplate: FunctionComponent = (props) => { const { typeInstance, onValueChange, labels, argValue } = props; const chain = get(argValue, 'chain.0', {}); const chainArgs = get(chain, 'arguments', {}); @@ -47,7 +47,7 @@ export const ExtendedTemplate: FunctionComponent = props => { } const fields = get(typeInstance, 'options.include', []); - const hasPropFields = fields.some(field => ['lines', 'bars', 'points'].indexOf(field) !== -1); + const hasPropFields = fields.some((field) => ['lines', 'bars', 'points'].indexOf(field) !== -1); const handleChange: (key: T, val: ChangeEvent) => void = ( argName, @@ -70,7 +70,7 @@ export const ExtendedTemplate: FunctionComponent = props => { ]; const labelOptions = [{ value: '', text: strings.getSelectSeriesOption() }]; - labels.sort().forEach(val => labelOptions.push({ value: val, text: val })); + labels.sort().forEach((val) => labelOptions.push({ value: val, text: val })); return (
@@ -81,7 +81,7 @@ export const ExtendedTemplate: FunctionComponent = props => { compressed value={selectedSeries} options={labelOptions} - onChange={ev => handleChange('label', ev)} + onChange={(ev) => handleChange('label', ev)} /> @@ -98,7 +98,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'lines.0', 0)} options={values} compressed - onChange={ev => handleChange('lines', ev)} + onChange={(ev) => handleChange('lines', ev)} /> @@ -110,7 +110,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'bars.0', 0)} options={values} compressed - onChange={ev => handleChange('bars', ev)} + onChange={(ev) => handleChange('bars', ev)} /> @@ -122,7 +122,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'points.0', 0)} options={values} compressed - onChange={ev => handleChange('points', ev)} + onChange={(ev) => handleChange('points', ev)} /> diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx index 226122cf0b25f..eb51492155a3b 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx @@ -32,7 +32,7 @@ interface Props { workpad: CanvasWorkpad; } -export const SimpleTemplate: FunctionComponent = props => { +export const SimpleTemplate: FunctionComponent = (props) => { const { typeInstance, argValue, onValueChange, labels, workpad } = props; const { name } = typeInstance; const chain = get(argValue, 'chain.0', {}); @@ -74,7 +74,7 @@ export const SimpleTemplate: FunctionComponent = props => { handleChange('color', val)} + onChange={(val) => handleChange('color', val)} value={color} ariaLabel={strings.getColorLabel()} /> diff --git a/x-pack/plugins/canvas/public/expression_types/datasource.js b/x-pack/plugins/canvas/public/expression_types/datasource.js index 0539486146136..ffcea83551914 100644 --- a/x-pack/plugins/canvas/public/expression_types/datasource.js +++ b/x-pack/plugins/canvas/public/expression_types/datasource.js @@ -41,7 +41,7 @@ class DatasourceWrapper extends React.PureComponent { render() { return ( { + render={(domNode) => { this.domNode = domNode; this.callRenderFn(); }} diff --git a/x-pack/plugins/canvas/public/expression_types/function_form.js b/x-pack/plugins/canvas/public/expression_types/function_form.js index 299b57e4854c1..7056f87bcfa05 100644 --- a/x-pack/plugins/canvas/public/expression_types/function_form.js +++ b/x-pack/plugins/canvas/public/expression_types/function_form.js @@ -80,16 +80,16 @@ export class FunctionForm extends BaseForm { const { args, argTypeDef } = data; // Don't instaniate these until render time, to give the registries a chance to populate. - const argInstances = this.args.map(argSpec => new Arg(argSpec)); + const argInstances = this.args.map((argSpec) => new Arg(argSpec)); if (!isPlainObject(args)) { throw new Error(`Form "${this.name}" expects "args" object`); } // get a mapping of arg values from the expression and from the renderable's schema - const argNames = uniq(argInstances.map(arg => arg.name).concat(Object.keys(args))); - const dataArgs = argNames.map(argName => { - const arg = argInstances.find(arg => arg.name === argName); + const argNames = uniq(argInstances.map((arg) => arg.name).concat(Object.keys(args))); + const dataArgs = argNames.map((argName) => { + const arg = argInstances.find((arg) => arg.name === argName); // if arg is not multi, only preserve the last value found // otherwise, leave the value alone (including if the arg is not defined) @@ -104,10 +104,10 @@ export class FunctionForm extends BaseForm { try { // allow a hook to override the data args - const resolvedDataArgs = dataArgs.map(d => ({ ...d, ...this.resolveArg(d, props) })); + const resolvedDataArgs = dataArgs.map((d) => ({ ...d, ...this.resolveArg(d, props) })); - const argumentForms = compact(resolvedDataArgs.map(d => this.renderArg(props, d))); - const addableArgs = compact(resolvedDataArgs.map(d => this.getAddableArg(props, d))); + const argumentForms = compact(resolvedDataArgs.map((d) => this.renderArg(props, d))); + const addableArgs = compact(resolvedDataArgs.map((d) => this.getAddableArg(props, d))); if (!addableArgs.length && !argumentForms.length) { return null; diff --git a/x-pack/plugins/canvas/public/expression_types/model.js b/x-pack/plugins/canvas/public/expression_types/model.js index 9ae71dfc0ac18..95c8b27a71048 100644 --- a/x-pack/plugins/canvas/public/expression_types/model.js +++ b/x-pack/plugins/canvas/public/expression_types/model.js @@ -48,7 +48,7 @@ export class Model extends FunctionForm { // if argument is missing from modelArgs, mark it as skipped const argName = get(dataArg, 'arg.name'); - const modelArg = modelArgs.find(modelArg => { + const modelArg = modelArgs.find((modelArg) => { if (Array.isArray(modelArg)) { return modelArg[0] === argName; } diff --git a/x-pack/plugins/canvas/public/functions/__tests__/asset.js b/x-pack/plugins/canvas/public/functions/__tests__/asset.js index 208af754e9105..c21faf9a2e227 100644 --- a/x-pack/plugins/canvas/public/functions/__tests__/asset.js +++ b/x-pack/plugins/canvas/public/functions/__tests__/asset.js @@ -17,7 +17,7 @@ describe.skip('asset', () => { const throwsErr = () => { return fn(null, { id: 'boo' }); }; - expect(throwsErr).to.throwException(err => { + expect(throwsErr).to.throwException((err) => { expect(err.message).to.be('Could not get the asset by ID: boo'); }); }); diff --git a/x-pack/plugins/canvas/public/functions/filters.ts b/x-pack/plugins/canvas/public/functions/filters.ts index 16d0bb0fff708..78cd742b44b26 100644 --- a/x-pack/plugins/canvas/public/functions/filters.ts +++ b/x-pack/plugins/canvas/public/functions/filters.ts @@ -37,7 +37,7 @@ function getFiltersByGroup(allFilters: string[], groups?: string[], ungrouped = return allFilters.filter((filter: string) => { const ast = fromExpression(filter); const expGroups = get(ast, 'chain[0].arguments.filterGroup', []); - return expGroups.length > 0 && expGroups.every(expGroup => groups.includes(expGroup)); + return expGroups.length > 0 && expGroups.every((expGroup) => groups.includes(expGroup)); }); } diff --git a/x-pack/plugins/canvas/public/functions/timelion.ts b/x-pack/plugins/canvas/public/functions/timelion.ts index 7e38e6e710b81..abb294d9cc110 100644 --- a/x-pack/plugins/canvas/public/functions/timelion.ts +++ b/x-pack/plugins/canvas/public/functions/timelion.ts @@ -94,7 +94,7 @@ export function timelionFunctionFactory(initialize: InitializeArguments): () => fn: (input, args): Promise => { // Timelion requires a time range. Use the time range from the timefilter element in the // workpad, if it exists. Otherwise fall back on the function args. - const timeFilter = input.and.find(and => and.filterType === 'time'); + const timeFilter = input.and.find((and) => and.filterType === 'time'); const range = timeFilter ? { min: timeFilter.from, max: timeFilter.to } : parseDateMath({ from: args.from, to: args.to }, args.timezone, initialize.timefilter); @@ -121,11 +121,15 @@ export function timelionFunctionFactory(initialize: InitializeArguments): () => method: 'POST', responseType: 'json', data: body, - }).then(resp => { + }).then((resp) => { const seriesList = resp.data.sheet[0].list; const rows = flatten( seriesList.map((series: { data: any[]; label: string }) => - series.data.map(row => ({ '@timestamp': row[0], value: row[1], label: series.label })) + series.data.map((row) => ({ + '@timestamp': row[0], + value: row[1], + label: series.label, + })) ) ) as DatatableRow[]; diff --git a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js index 82cb468be3c54..99d8305768240 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js @@ -130,16 +130,16 @@ describe.skip('historyProvider', () => { teardownFn(); }); - it('should call handler on state change', done => { - createOnceHandler(history, done, loc => { + it('should call handler on state change', (done) => { + createOnceHandler(history, done, (loc) => { expect(loc).to.be.a('object'); }); history.push({}); }); - it('should pass location object to handler', done => { - createOnceHandler(history, done, location => { + it('should pass location object to handler', (done) => { + createOnceHandler(history, done, (location) => { expect(location.pathname).to.be.a('string'); expect(location.hash).to.be.a('string'); expect(location.state).to.be.an('object'); @@ -149,7 +149,7 @@ describe.skip('historyProvider', () => { history.push(state); }); - it('should pass decompressed state to handler', done => { + it('should pass decompressed state to handler', (done) => { createOnceHandler(history, done, ({ state: curState }) => { expect(curState).to.eql(state); }); @@ -157,7 +157,7 @@ describe.skip('historyProvider', () => { history.push(state); }); - it('should pass in the previous location object to handler', done => { + it('should pass in the previous location object to handler', (done) => { createOnceHandler(history, done, (location, prevLocation) => { expect(prevLocation.pathname).to.be.a('string'); expect(prevLocation.hash).to.be.a('string'); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts b/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts index 38d5233b662cd..cb46a3d6be402 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts @@ -185,7 +185,7 @@ import { // typings:expect-error plain = undefined; // it's undefined // typings:expect-error - plain = a => a; // it's a function + plain = (a) => a; // it's a function // typings:expect-error plain = [new Date()]; // it's a time // typings:expect-error diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/common.js b/x-pack/plugins/canvas/public/lib/aeroelastic/common.js index 97f0e04ea6eb8..357c80488a08b 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/common.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/common.js @@ -8,10 +8,10 @@ import { select } from './select'; // serves as reminder that we start with the state // todo remove it as we add TS annotations (State) -const state = d => d; +const state = (d) => d; -const getScene = state => state.currentScene; +const getScene = (state) => state.currentScene; export const scene = select(getScene)(state); -const getPrimaryUpdate = state => state.primaryUpdate; +const getPrimaryUpdate = (state) => state.primaryUpdate; export const primaryUpdate = select(getPrimaryUpdate)(state); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js index 33cd95875302a..9b4ab8470da87 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js @@ -12,7 +12,7 @@ * @param {*[][]} arrays * @returns *[] */ -export const flatten = arrays => [].concat(...arrays); +export const flatten = (arrays) => [].concat(...arrays); /** * identity @@ -20,7 +20,7 @@ export const flatten = arrays => [].concat(...arrays); * @param d * @returns d */ -export const identity = d => d; +export const identity = (d) => d; /** * map @@ -32,7 +32,7 @@ export const identity = d => d; * @param {Function} fun * @returns {function(*): *} */ -export const map = fun => array => array.map(value => fun(value)); +export const map = (fun) => (array) => array.map((value) => fun(value)); /** * disjunctiveUnion @@ -44,8 +44,8 @@ export const map = fun => array => array.map(value => fun(value)); */ export const disjunctiveUnion = (keyFun, set1, set2) => set1 - .filter(s1 => !set2.find(s2 => keyFun(s2) === keyFun(s1))) - .concat(set2.filter(s2 => !set1.find(s1 => keyFun(s1) === keyFun(s2)))); + .filter((s1) => !set2.find((s2) => keyFun(s2) === keyFun(s1))) + .concat(set2.filter((s2) => !set1.find((s1) => keyFun(s1) === keyFun(s2)))); /** * @@ -70,16 +70,16 @@ export const shallowEqual = (a, b) => { return true; }; -export const not = fun => (...args) => !fun(...args); +export const not = (fun) => (...args) => !fun(...args); export const removeDuplicates = (idFun, a) => - a.filter((d, i) => a.findIndex(s => idFun(s) === idFun(d)) === i); + a.filter((d, i) => a.findIndex((s) => idFun(s) === idFun(d)) === i); -export const arrayToMap = a => Object.assign({}, ...a.map(d => ({ [d]: true }))); +export const arrayToMap = (a) => Object.assign({}, ...a.map((d) => ({ [d]: true }))); export const subMultitree = (pk, fk, elements, inputRoots) => { - const getSubgraphs = roots => { - const children = flatten(roots.map(r => elements.filter(e => fk(e) === pk(r)))); + const getSubgraphs = (roots) => { + const children = flatten(roots.map((r) => elements.filter((e) => fk(e) === pk(r)))); if (children.length) { return [...roots, ...getSubgraphs(children, elements)]; } else { diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js index de4510e385974..6c0ebc00c7899 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js @@ -26,7 +26,7 @@ import { dotProduct } from './matrix2d'; const cornerScreenPositions = (transformMatrix, a, b) => // for unknown perf gain, this could be cached per shape - [TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT].map(corner => + [TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT].map((corner) => mvMultiply(transformMatrix, componentProduct(corner, [a, b, 0, 1])) ); @@ -127,9 +127,9 @@ const shapesAtPoint = (shapes, x, y) => // viewer. But that's not the case. So we maximize the Z value to tell what's on top. export const shapesAt = (shapes, { x, y }) => shapesAtPoint(shapes, x, y) - .filter(shape => shape.inside) + .filter((shape) => shape.inside) .sort((shape1, shape2) => shape2.z - shape1.z || shape2.index - shape1.index) // stable sort: DOM insertion order!!! - .map(shape => shape.shape); // decreasing order, ie. from front (closest to viewer) to back + .map((shape) => shape.shape); // decreasing order, ie. from front (closest to viewer) to back const getExtremum = (transformMatrix, a, b) => normalize(mvMultiply(transformMatrix, [a, b, 0, 1])); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js index ba78db9dc670a..ede7affc850b6 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js @@ -25,20 +25,20 @@ const appleKeyboard = Boolean( * (we could turn gesture.js into a factory, with this state root - primaryUpdate - being passed...) */ -const primaryUpdate = state => state.primaryUpdate; +const primaryUpdate = (state) => state.primaryUpdate; -const gestureStatePrev = select(scene => scene.gestureState)(scene); +const gestureStatePrev = select((scene) => scene.gestureState)(scene); /** * Gestures - derived selectors for transient state */ // dispatch the various types of actions -const rawCursorPosition = select(action => +const rawCursorPosition = select((action) => action.type === 'cursorPosition' ? action.payload : null )(primaryUpdate); -const mouseButtonEvent = select(action => (action.type === 'mouseEvent' ? action.payload : null))( +const mouseButtonEvent = select((action) => (action.type === 'mouseEvent' ? action.payload : null))( primaryUpdate ); @@ -46,16 +46,16 @@ const keyFromMouse = select(({ type, payload: { altKey, metaKey, shiftKey, ctrlK type === 'cursorPosition' || type === 'mouseEvent' ? { altKey, metaKey, shiftKey, ctrlKey } : {} )(primaryUpdate); -export const metaHeld = select(appleKeyboard ? e => e.metaKey : e => e.altKey)(keyFromMouse); -export const optionHeld = select(appleKeyboard ? e => e.altKey : e => e.ctrlKey)(keyFromMouse); -export const shiftHeld = select(e => e.shiftKey)(keyFromMouse); +export const metaHeld = select(appleKeyboard ? (e) => e.metaKey : (e) => e.altKey)(keyFromMouse); +export const optionHeld = select(appleKeyboard ? (e) => e.altKey : (e) => e.ctrlKey)(keyFromMouse); +export const shiftHeld = select((e) => e.shiftKey)(keyFromMouse); export const cursorPosition = select(({ cursor }, position) => position || cursor)( gestureStatePrev, rawCursorPosition ); -export const mouseButton = select(next => { +export const mouseButton = select((next) => { if (!next) { return { down: false, up: false, uid: null }; } @@ -74,7 +74,7 @@ export const mouseIsDown = select(({ mouseIsDown }, next) => )(gestureStatePrev, mouseButtonEvent); export const gestureEnd = select( - action => + (action) => action && (action.type === 'actionEvent' || (action.type === 'mouseEvent' && action.payload.event === 'mouseUp')) @@ -128,9 +128,9 @@ const mouseButtonState = select( } )(gestureStatePrev, mouseIsDown, cursorPosition); -export const mouseDowned = select(state => state.buttonState === 'downed')(mouseButtonState); +export const mouseDowned = select((state) => state.buttonState === 'downed')(mouseButtonState); -export const dragging = select(state => state.buttonState === 'dragging')(mouseButtonState); +export const dragging = select((state) => state.buttonState === 'dragging')(mouseButtonState); export const dragVector = select(({ buttonState, downX, downY }, { x, y }) => ({ down: buttonState !== 'up', @@ -140,7 +140,7 @@ export const dragVector = select(({ buttonState, downX, downY }, { x, y }) => ({ y1: y, }))(mouseButtonState, cursorPosition); -export const actionEvent = select(action => +export const actionEvent = select((action) => action.type === 'actionEvent' ? action.payload : null )(primaryUpdate); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js b/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js index d3da1b5553958..c2c6f77fb167c 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js @@ -138,7 +138,7 @@ const shapeAABB = (shape, prevOuter) => return extend(prevInner, cornerPoint, cornerPoint); }, prevOuter); -const shapesAABB = shapes => +const shapesAABB = (shapes) => shapes.reduce( (prevOuter, shape) => extend(prevOuter, ...shapeAABB(shape, prevOuter)), identityAABB() @@ -167,7 +167,7 @@ export const draggingShape = ({ draggedShape, shapes }, hoveredShape, down, mous // the currently dragged shape is considered in-focus; if no dragging is going on, then the hovered shape export const getFocusedShape = (draggedShape, hoveredShape) => draggedShape || hoveredShape; // focusedShapes has updated position etc. information while focusedShape may have stale position -export const getAlterSnapGesture = metaHeld => (metaHeld ? ['relax'] : []); +export const getAlterSnapGesture = (metaHeld) => (metaHeld ? ['relax'] : []); const initialTransformTuple = { deltaX: 0, @@ -196,38 +196,38 @@ export const getMouseTransformState = (prev, dragging, { x0, y0, x1, y1 }) => { } }; -export const getMouseTransformGesture = tuple => +export const getMouseTransformGesture = (tuple) => [tuple] - .filter(tpl => tpl.transform) + .filter((tpl) => tpl.transform) .map(({ transform, cumulativeTransform }) => ({ transform, cumulativeTransform })); -export const getLocalTransformMatrix = shapes => shape => { +export const getLocalTransformMatrix = (shapes) => (shape) => { if (!shape.parent) { return shape.transformMatrix; } return multiply( - invert(shapes.find(s => s.id === shape.parent).transformMatrix), + invert(shapes.find((s) => s.id === shape.parent).transformMatrix), shape.transformMatrix ); }; export const getSelectedShapeObjects = (scene, shapes) => - (scene.selectedShapes || []).map(s => shapes.find(ss => ss.id === s)); + (scene.selectedShapes || []).map((s) => shapes.find((ss) => ss.id === s)); -const contentShape = allShapes => shape => +const contentShape = (allShapes) => (shape) => shape.type === 'annotation' - ? contentShape(allShapes)(allShapes.find(s => s.id === shape.parent)) + ? contentShape(allShapes)(allShapes.find((s) => s.id === shape.parent)) : shape; const getContentShapes = (allShapes, shapes) => { // fixme no need to export, why doesn't linter or highlighter complain? - const idMap = arrayToMap(allShapes.map(shape => shape.id)); - return shapes.filter(shape => idMap[shape.id]).map(contentShape(allShapes)); + const idMap = arrayToMap(allShapes.map((shape) => shape.id)); + return shapes.filter((shape) => idMap[shape.id]).map(contentShape(allShapes)); }; -const primaryShape = shape => (shape.type === 'annotation' ? shape.parent : shape.id); +const primaryShape = (shape) => (shape.type === 'annotation' ? shape.parent : shape.id); -const rotationManipulation = config => ({ +const rotationManipulation = (config) => ({ shape, directShape, cursorPosition: { x, y }, @@ -265,7 +265,7 @@ const minimumSize = (min, { a, b, baseAB }, vector) => { ]; }; -const centeredResizeManipulation = config => ({ gesture, shape, directShape }) => { +const centeredResizeManipulation = (config) => ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) if (!shape || !directShape) { @@ -293,7 +293,7 @@ const centeredResizeManipulation = config => ({ gesture, shape, directShape }) = }; }; -const asymmetricResizeManipulation = config => ({ gesture, shape, directShape }) => { +const asymmetricResizeManipulation = (config) => ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) if (!shape || !directShape) { @@ -333,7 +333,7 @@ const asymmetricResizeManipulation = config => ({ gesture, shape, directShape }) const directShapeTranslateManipulation = (cumulativeTransforms, directShapes) => { const shapes = directShapes - .map(shape => shape.type !== 'annotation' && shape.id) + .map((shape) => shape.type !== 'annotation' && shape.id) .filter(identity); return [{ cumulativeTransforms, shapes }]; }; @@ -347,13 +347,13 @@ const rotationAnnotationManipulation = ( alterSnapGesture ) => { const shapeIds = directShapes.map( - shape => + (shape) => shape.type === 'annotation' && shape.subtype === config.rotationHandleName && shape.parent ); - const shapes = shapeIds.map(id => id && allShapes.find(shape => shape.id === id)); + const shapes = shapeIds.map((id) => id && allShapes.find((shape) => shape.id === id)); const tuples = flatten( shapes.map((shape, i) => - directTransforms.map(transform => ({ + directTransforms.map((transform) => ({ transform, shape, directShape: directShapes[i], @@ -373,19 +373,19 @@ const resizeAnnotationManipulation = ( manipulator ) => { const shapeIds = directShapes.map( - shape => + (shape) => shape.type === 'annotation' && shape.subtype === config.resizeHandleName && shape.parent ); - const shapes = shapeIds.map(id => id && allShapes.find(shape => shape.id === id)); + const shapes = shapeIds.map((id) => id && allShapes.find((shape) => shape.id === id)); const tuples = flatten( shapes.map((shape, i) => - transformGestures.map(gesture => ({ gesture, shape, directShape: directShapes[i] })) + transformGestures.map((gesture) => ({ gesture, shape, directShape: directShapes[i] })) ) ); return tuples.map(manipulator); }; -const fromScreen = currentTransform => transform => { +const fromScreen = (currentTransform) => (transform) => { const isTranslate = transform[12] !== 0 || transform[13] !== 0; if (isTranslate) { const composite = compositeComponent(currentTransform); @@ -397,7 +397,7 @@ const fromScreen = currentTransform => transform => { } }; -const horizontalToIndex = horizontal => (horizontal ? 0 : 1); +const horizontalToIndex = (horizontal) => (horizontal ? 0 : 1); const anchorAABB = (aabb, anchorDirection, horizontal) => { const dimension = horizontalToIndex(horizontal); @@ -421,13 +421,13 @@ export const getAlignDistributeTransformIntents = ( } const group = selectedShapes[0]; - const children = shapes.filter(s => s.parent === group.id && s.type !== 'annotation'); + const children = shapes.filter((s) => s.parent === group.id && s.type !== 'annotation'); if (alignAction && children.length > 1) { const { controlledAnchor, horizontal } = alignAction; const groupBoundingBox = shapeAABB(group, identityAABB()); const groupAnchor = anchorAABB(groupBoundingBox, controlledAnchor, horizontal); - const results = children.map(c => { + const results = children.map((c) => { const childBoundingBox = shapeAABB(c, identityAABB()); const childAnchor = anchorAABB(childBoundingBox, controlledAnchor, horizontal); const delta = groupAnchor - childAnchor; @@ -443,16 +443,16 @@ export const getAlignDistributeTransformIntents = ( const groupBoundingBox = shapeAABB(group, identityAABB()); const groupAnchor = anchorAABB(groupBoundingBox, -1, horizontal); const dimension = horizontalToIndex(horizontal); - const childrenBoxes2D = children.map(c => shapeAABB(c, identityAABB())); - const childrenAnchors = childrenBoxes2D.map(childBoundingBox => + const childrenBoxes2D = children.map((c) => shapeAABB(c, identityAABB())); + const childrenAnchors = childrenBoxes2D.map((childBoundingBox) => anchorAABB(childBoundingBox, -1, horizontal) ); - const childrenBoxes1D = childrenBoxes2D.map(box2D => [ + const childrenBoxes1D = childrenBoxes2D.map((box2D) => [ box2D[0][dimension], box2D[1][dimension], ]); - const childrenCenters = childrenBoxes1D.map(box1D => (box1D[1] + box1D[0]) / 2); - const childrenSizes = childrenBoxes1D.map(box1D => box1D[1] - box1D[0]); + const childrenCenters = childrenBoxes1D.map((box1D) => (box1D[1] + box1D[0]) / 2); + const childrenSizes = childrenBoxes1D.map((box1D) => box1D[1] - box1D[0]); const totalChildrenSize = childrenSizes.reduce((a, b) => a + b, 0); const groupSize = horizontal ? 2 * A : 2 * B; const totalFreeSpace = groupSize - totalChildrenSize; @@ -488,14 +488,14 @@ export const getAlignDistributeTransformIntents = ( return []; }; -const shapeApplyLocalTransforms = intents => shape => { +const shapeApplyLocalTransforms = (intents) => (shape) => { const transformIntents = flatten( intents .map( - intent => + (intent) => intent.transforms && intent.transforms.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.transforms.map(fromScreen(shape.localTransformMatrix)) ) .filter(identity) @@ -503,10 +503,10 @@ const shapeApplyLocalTransforms = intents => shape => { const sizeIntents = flatten( intents .map( - intent => + (intent) => intent.sizes && intent.sizes.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.sizes ) .filter(identity) @@ -514,10 +514,10 @@ const shapeApplyLocalTransforms = intents => shape => { const cumulativeTransformIntents = flatten( intents .map( - intent => + (intent) => intent.cumulativeTransforms && intent.cumulativeTransforms.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.cumulativeTransforms.map(fromScreen(shape.localTransformMatrix)) ) .filter(identity) @@ -525,10 +525,10 @@ const shapeApplyLocalTransforms = intents => shape => { const cumulativeSizeIntents = flatten( intents .map( - intent => + (intent) => intent.cumulativeSizes && intent.cumulativeSizes.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.cumulativeSizes ) .filter(identity) @@ -581,7 +581,7 @@ const getUpstreamTransforms = (shapes, shape) => shape.parent ? getUpstreamTransforms( shapes, - shapes.find(s => s.id === shape.parent) + shapes.find((s) => s.id === shape.parent) ).concat([shape.localTransformMatrix]) : [shape.localTransformMatrix]; @@ -589,19 +589,19 @@ const getUpstreams = (shapes, shape) => shape.parent ? getUpstreams( shapes, - shapes.find(s => s.id === shape.parent) + shapes.find((s) => s.id === shape.parent) ).concat([shape]) : [shape]; -const snappedA = shape => shape.a + (shape.snapResizeVector ? shape.snapResizeVector[0] : 0); -const snappedB = shape => shape.b + (shape.snapResizeVector ? shape.snapResizeVector[1] : 0); +const snappedA = (shape) => shape.a + (shape.snapResizeVector ? shape.snapResizeVector[0] : 0); +const snappedB = (shape) => shape.b + (shape.snapResizeVector ? shape.snapResizeVector[1] : 0); const cascadeUnsnappedTransforms = (shapes, shape) => { if (!shape.parent) { return shape.localTransformMatrix; } // boost for common case of toplevel shape const upstreams = getUpstreams(shapes, shape); - const upstreamTransforms = upstreams.map(s => { + const upstreamTransforms = upstreams.map((s) => { return s.localTransformMatrix; }); const cascadedTransforms = reduceTransforms(upstreamTransforms); @@ -609,7 +609,7 @@ const cascadeUnsnappedTransforms = (shapes, shape) => { }; const cascadeTransforms = (shapes, shape) => { - const cascade = s => + const cascade = (s) => s.snapDeltaMatrix ? multiply(s.localTransformMatrix, s.snapDeltaMatrix) : s.localTransformMatrix; @@ -622,7 +622,7 @@ const cascadeTransforms = (shapes, shape) => { return cascadedTransforms; }; -const shapeCascadeProperties = shapes => shape => { +const shapeCascadeProperties = (shapes) => (shape) => { return { ...shape, transformMatrix: cascadeTransforms(shapes, shape), @@ -631,7 +631,7 @@ const shapeCascadeProperties = shapes => shape => { }; }; -export const cascadeProperties = shapes => shapes.map(shapeCascadeProperties(shapes)); +export const cascadeProperties = (shapes) => shapes.map(shapeCascadeProperties(shapes)); const alignmentGuides = (config, shapes, guidedShapes, draggedShape) => { const result = {}; @@ -747,8 +747,8 @@ const alignmentGuides = (config, shapes, guidedShapes, draggedShape) => { return Object.values(result); }; -const isHorizontal = constraint => constraint.dimension === 'horizontal'; -const isVertical = constraint => constraint.dimension === 'vertical'; +const isHorizontal = (constraint) => constraint.dimension === 'horizontal'; +const isVertical = (constraint) => constraint.dimension === 'vertical'; const closestConstraint = (prev = { distance: Infinity }, next) => next.distance < prev.distance ? { constraint: next, distance: next.distance } : prev; @@ -760,7 +760,7 @@ const directionalConstraint = (constraints, filterFun) => { }; const rotationAnnotation = (config, shapes, selectedShapes, shape, i) => { - const foundShape = shapes.find(s => shape.id === s.id); + const foundShape = shapes.find((s) => shape.id === s.id); if (!foundShape) { return false; } @@ -770,7 +770,7 @@ const rotationAnnotation = (config, shapes, selectedShapes, shape, i) => { config, shapes, selectedShapes, - shapes.find(s => foundShape.parent === s.id), + shapes.find((s) => foundShape.parent === s.id), i ); } @@ -857,11 +857,11 @@ const resizeEdgeAnnotations = (config, parent, a, b) => ([[x0, y0], [x1, y1]]) = }; }; -const groupedShape = properShape => shape => shape.parent === properShape.id; +const groupedShape = (properShape) => (shape) => shape.parent === properShape.id; const magic = (config, shape, shapes) => { const epsilon = config.rotationEpsilon; const integralOf = Math.PI * 2; - const isIntegerMultiple = s => { + const isIntegerMultiple = (s) => { const zRotation = matrixToAngle(s.localTransformMatrix); const ratio = zRotation / integralOf; return Math.abs(Math.round(ratio) - ratio) < epsilon; @@ -879,11 +879,11 @@ const magic = (config, shape, shapes) => { }; function resizeAnnotation(config, shapes, selectedShapes, shape) { - const foundShape = shapes.find(s => shape.id === s.id); + const foundShape = shapes.find((s) => shape.id === s.id); const properShape = foundShape && (foundShape.subtype === config.resizeHandleName - ? shapes.find(s => shape.parent === s.id) + ? shapes.find((s) => shape.parent === s.id) : foundShape); if (!foundShape) { return []; @@ -894,7 +894,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { const result = foundShape.interactive ? resizeAnnotationsFunction(config, { shapes, - selectedShapes: [shapes.find(s => shape.parent === s.id)], + selectedShapes: [shapes.find((s) => shape.parent === s.id)], }) : []; return result; @@ -904,7 +904,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { config, shapes, selectedShapes, - shapes.find(s => foundShape.parent === s.id) + shapes.find((s) => foundShape.parent === s.id) ); } @@ -917,7 +917,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { magic( config, properShape, - shapes.filter(s => s.type !== 'annotation') + shapes.filter((s) => s.type !== 'annotation') )); const resizeVertices = allowResize ? resizeVertexTuples : []; const resizePoints = resizeVertices.map(resizePointAnnotations(config, shape, a, b)); @@ -929,14 +929,14 @@ export function resizeAnnotationsFunction(config, { shapes, selectedShapes }) { const shapesToAnnotate = selectedShapes; return flatten( shapesToAnnotate - .map(shape => { + .map((shape) => { return resizeAnnotation(config, shapes, selectedShapes, shape); }) .filter(identity) ); } -const crystallizeConstraint = shape => { +const crystallizeConstraint = (shape) => { const result = { ...shape }; if (shape.snapDeltaMatrix) { result.localTransformMatrix = multiply(shape.localTransformMatrix, shape.snapDeltaMatrix); @@ -950,7 +950,9 @@ const crystallizeConstraint = shape => { return result; }; -const translateShapeSnap = (horizontalConstraint, verticalConstraint, draggedElement) => shape => { +const translateShapeSnap = (horizontalConstraint, verticalConstraint, draggedElement) => ( + shape +) => { const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; const snapOffsetX = constrainedX ? -horizontalConstraint.signedDistance : 0; @@ -983,7 +985,7 @@ const resizeShapeSnap = ( symmetric, horizontalPosition, verticalPosition -) => shape => { +) => (shape) => { const constrainedShape = draggedElement && shape.id === draggedElement.id; const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; @@ -1025,10 +1027,10 @@ const resizeShapeSnap = ( const dissolveGroups = (groupsToDissolve, shapes, selectedShapes) => { return { shapes: shapes - .filter(s => !groupsToDissolve.find(g => s.id === g.id)) - .map(shape => { + .filter((s) => !groupsToDissolve.find((g) => s.id === g.id)) + .map((shape) => { const preexistingGroupParent = groupsToDissolve.find( - groupShape => groupShape.id === shape.parent + (groupShape) => groupShape.id === shape.parent ); // if linked, dissociate from group parent return preexistingGroupParent @@ -1037,29 +1039,29 @@ const dissolveGroups = (groupsToDissolve, shapes, selectedShapes) => { parent: null, localTransformMatrix: multiply( // pulling preexistingGroupParent from `shapes` to get fresh matrices - shapes.find(s => s.id === preexistingGroupParent.id).localTransformMatrix, // reinstate the group offset onto the child + shapes.find((s) => s.id === preexistingGroupParent.id).localTransformMatrix, // reinstate the group offset onto the child shape.localTransformMatrix ), } : shape; }), - selectedShapes: selectedShapes.filter(s => !groupsToDissolve.find(g => g.id === s.id)), + selectedShapes: selectedShapes.filter((s) => !groupsToDissolve.find((g) => g.id === s.id)), }; }; -const hasNoParentWithin = shapes => shape => !shapes.some(g => shape.parent === g.id); +const hasNoParentWithin = (shapes) => (shape) => !shapes.some((g) => shape.parent === g.id); const asYetUngroupedShapes = (preexistingAdHocGroups, selectedShapes) => selectedShapes.filter(hasNoParentWithin(preexistingAdHocGroups)); -const idMatch = shape => s => s.id === shape.id; +const idMatch = (shape) => (s) => s.id === shape.id; -const idsMatch = selectedShapes => shape => selectedShapes.find(idMatch(shape)); +const idsMatch = (selectedShapes) => (shape) => selectedShapes.find(idMatch(shape)); const axisAlignedBoundingBoxShape = (config, shapesToBox) => { const axisAlignedBoundingBox = shapesAABB(shapesToBox); const { a, b, localTransformMatrix, rigTransform } = projectAABB(axisAlignedBoundingBox); - const id = getId(config.groupName, shapesToBox.map(s => s.id).join('|')); + const id = getId(config.groupName, shapesToBox.map((s) => s.id).join('|')); const aabbShape = { id, type: config.groupName, @@ -1073,7 +1075,7 @@ const axisAlignedBoundingBoxShape = (config, shapesToBox) => { return aabbShape; }; -const resetChild = s => { +const resetChild = (s) => { if (s.childBaseAB) { s.childBaseAB = null; s.baseLocalTransformMatrix = null; @@ -1089,14 +1091,14 @@ const childScaler = ({ a, b }, baseAB) => { return groupScale; }; -const resizeChild = groupScale => s => { +const resizeChild = (groupScale) => (s) => { const childBaseAB = s.childBaseAB || [s.a, s.b]; const impliedScale = scale(...childBaseAB, 1); const inverseImpliedScale = invert(impliedScale); const baseLocalTransformMatrix = s.baseLocalTransformMatrix || s.localTransformMatrix; const normalizedBaseLocalTransformMatrix = multiply(baseLocalTransformMatrix, impliedScale); const T = multiply(groupScale, normalizedBaseLocalTransformMatrix); - const backScaler = groupScale.map(d => Math.abs(d)); + const backScaler = groupScale.map((d) => Math.abs(d)); const inverseBackScaler = invert(backScaler); const abTuple = mvMultiply(multiply(backScaler, impliedScale), [1, 1, 1, 1]); s.localTransformMatrix = multiply(T, multiply(inverseImpliedScale, inverseBackScaler)); @@ -1113,14 +1115,14 @@ const resizeGroup = (shapes, rootElement) => { } const depths = {}; - const ancestorsLength = shape => (shape.parent ? ancestorsLength(idMap[shape.parent]) + 1 : 0); + const ancestorsLength = (shape) => (shape.parent ? ancestorsLength(idMap[shape.parent]) + 1 : 0); for (const shape of shapes) { depths[shape.id] = ancestorsLength(shape); } const resizedParents = { [rootElement.id]: rootElement }; const sortedShapes = shapes.slice().sort((a, b) => depths[a.id] - depths[b.id]); - const parentResized = s => Boolean(s.childBaseAB || s.baseAB); + const parentResized = (s) => Boolean(s.childBaseAB || s.baseAB); for (const shape of sortedShapes) { const parent = resizedParents[shape.parent]; if (parent) { @@ -1137,32 +1139,32 @@ const resizeGroup = (shapes, rootElement) => { const getLeafs = (descendCondition, allShapes, shapes) => removeDuplicates( - s => s.id, + (s) => s.id, flatten( - shapes.map(shape => - descendCondition(shape) ? allShapes.filter(s => s.parent === shape.id) : shape + shapes.map((shape) => + descendCondition(shape) ? allShapes.filter((s) => s.parent === shape.id) : shape ) ) ); const preserveCurrentGroups = (shapes, selectedShapes) => ({ shapes, selectedShapes }); -export const getConfiguration = scene => scene.configuration; +export const getConfiguration = (scene) => scene.configuration; -export const getShapes = scene => scene.shapes; +export const getShapes = (scene) => scene.shapes; export const getHoveredShapes = (config, shapes, cursorPosition) => shapesAt( shapes.filter( // second AND term excludes intra-group element hover (and therefore drag & drop), todo: remove this current limitation - s => + (s) => (s.type !== 'annotation' || s.interactive) && (config.intraGroupManipulation || !s.parent || s.type === 'annotation') ), cursorPosition ); -export const getHoveredShape = hoveredShapes => (hoveredShapes.length ? hoveredShapes[0] : null); +export const getHoveredShape = (hoveredShapes) => (hoveredShapes.length ? hoveredShapes[0] : null); const singleSelect = (prev, config, hoveredShapes, metaHeld, uid, _, boxHighlightedShapes) => { // cycle from top ie. from zero after the cursor position changed ie. !sameLocation @@ -1193,7 +1195,7 @@ const multiSelect = ( ) => { const shapes = hoveredShapes.length > 0 - ? disjunctiveUnion(shape => shape.id, selectedShapeObjects, hoveredShapes.slice(0, 1)) // ie. depthIndex of 0, if any + ? disjunctiveUnion((shape) => shape.id, selectedShapeObjects, hoveredShapes.slice(0, 1)) // ie. depthIndex of 0, if any : []; return { shapes, @@ -1205,16 +1207,16 @@ const multiSelect = ( }; export const getGroupingTuple = (config, shapes, selectedShapes) => { - const childOfGroup = shape => shape.parent && shape.parent.startsWith(config.groupName); - const isAdHocGroup = shape => + const childOfGroup = (shape) => shape.parent && shape.parent.startsWith(config.groupName); + const isAdHocGroup = (shape) => shape.type === config.groupName && shape.subtype === config.adHocGroupName; const preexistingAdHocGroups = shapes.filter(isAdHocGroup); const matcher = idsMatch(selectedShapes); - const selectedFn = shape => matcher(shape) && shape.type !== 'annotation'; + const selectedFn = (shape) => matcher(shape) && shape.type !== 'annotation'; const freshSelectedShapes = shapes.filter(selectedFn); const freshNonSelectedShapes = shapes.filter(not(selectedFn)); - const isGroup = shape => shape.type === config.groupName; - const isOrBelongsToGroup = shape => isGroup(shape) || childOfGroup(shape); + const isGroup = (shape) => shape.type === config.groupName; + const isOrBelongsToGroup = (shape) => isGroup(shape) || childOfGroup(shape); const someSelectedShapesAreGrouped = selectedShapes.some(isOrBelongsToGroup); const selectionOutsideGroup = !someSelectedShapesAreGrouped; return { @@ -1234,16 +1236,16 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) } = tuple; if (groupAction === 'group') { const selectedAdHocGroupsToPersist = selectedShapes.filter( - s => s.subtype === config.adHocGroupName + (s) => s.subtype === config.adHocGroupName ); return { - shapes: shapes.map(s => + shapes: shapes.map((s) => s.subtype === config.adHocGroupName ? { ...s, subtype: config.persistentGroupName } : s ), selectedShapes: selectedShapes - .filter(selected => selected.subtype !== config.adHocGroupName) + .filter((selected) => selected.subtype !== config.adHocGroupName) .concat( - selectedAdHocGroupsToPersist.map(shape => ({ + selectedAdHocGroupsToPersist.map((shape) => ({ ...shape, subtype: config.persistentGroupName, })) @@ -1253,7 +1255,7 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) if (groupAction === 'ungroup') { return dissolveGroups( - selectedShapes.filter(s => s.subtype === config.persistentGroupName), + selectedShapes.filter((s) => s.subtype === config.persistentGroupName), shapes, asYetUngroupedShapes(preexistingAdHocGroups, freshSelectedShapes) ); @@ -1277,10 +1279,10 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) ? { shapes: [ ...resizeGroup( - shapes.filter(s => s.type !== 'annotation'), + shapes.filter((s) => s.type !== 'annotation'), elements[0] ), - ...shapes.filter(s => s.type === 'annotation'), + ...shapes.filter((s) => s.type === 'annotation'), ], selectedShapes, } @@ -1294,21 +1296,21 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) // group together the multiple items const group = axisAlignedBoundingBoxShape(config, freshSelectedShapes); const selectedLeafShapes = getLeafs( - shape => shape.subtype === config.adHocGroupName, + (shape) => shape.subtype === config.adHocGroupName, shapes, freshSelectedShapes ); - const parentedSelectedShapes = selectedLeafShapes.map(shape => ({ + const parentedSelectedShapes = selectedLeafShapes.map((shape) => ({ ...shape, parent: group.id, localTransformMatrix: multiply(group.rigTransform, shape.transformMatrix), })); - const nonGroupGraphConstituent = s => - s.subtype !== config.adHocGroupName && !parentedSelectedShapes.find(ss => s.id === ss.id); - const dissociateFromParentIfAny = s => + const nonGroupGraphConstituent = (s) => + s.subtype !== config.adHocGroupName && !parentedSelectedShapes.find((ss) => s.id === ss.id); + const dissociateFromParentIfAny = (s) => s.parent && s.parent.startsWith(config.groupName) && - preexistingAdHocGroups.find(ahg => ahg.id === s.parent) + preexistingAdHocGroups.find((ahg) => ahg.id === s.parent) ? { ...s, parent: null } : s; const allTerminalShapes = parentedSelectedShapes.concat( @@ -1338,7 +1340,7 @@ export const getCursor = (config, shape, draggedPrimaryShape) => { } }; -export const getSelectedShapesPrev = scene => scene.selectionState; +export const getSelectedShapesPrev = (scene) => scene.selectionState; export const getSelectionStateFull = ( prev, @@ -1362,7 +1364,7 @@ export const getSelectionStateFull = ( up && prev.boxHighlightedShapes.length ? prev.shapes .concat(prev.boxHighlightedShapes) - .filter((d, i, a) => a.findIndex(dd => dd.id === d.id) === i) + .filter((d, i, a) => a.findIndex((dd) => dd.id === d.id) === i) : prev.shapes, down, uid, @@ -1382,7 +1384,7 @@ export const getSelectionStateFull = ( ); }; -export const getSelectedShapes = selectionTuple => selectionTuple.shapes; +export const getSelectedShapes = (selectionTuple) => selectionTuple.shapes; export const getSelectionState = ({ uid, depthIndex, down, metaHeld, boxHighlightedShapes }) => ({ uid, @@ -1392,7 +1394,7 @@ export const getSelectionState = ({ uid, depthIndex, down, metaHeld, boxHighligh boxHighlightedShapes, }); -export const getSelectedPrimaryShapeIds = shapes => shapes.map(primaryShape); +export const getSelectedPrimaryShapeIds = (shapes) => shapes.map(primaryShape); export const getResizeManipulator = (config, toggle) => (toggle ? centeredResizeManipulation : asymmetricResizeManipulation)(config); @@ -1407,12 +1409,12 @@ export const getTransformIntents = ( manipulator ) => [ ...directShapeTranslateManipulation( - transformGestures.map(g => g.cumulativeTransform), + transformGestures.map((g) => g.cumulativeTransform), directShapes ), ...rotationAnnotationManipulation( config, - transformGestures.map(g => g.transform), + transformGestures.map((g) => g.transform), directShapes, shapes, cursorPosition, @@ -1422,14 +1424,14 @@ export const getTransformIntents = ( ]; export const getDraggedPrimaryShape = (shapes, draggedShape) => - draggedShape && shapes.find(shape => shape.id === primaryShape(draggedShape)); + draggedShape && shapes.find((shape) => shape.id === primaryShape(draggedShape)); export const getAlignmentGuideAnnotations = (config, shapes, draggedPrimaryShape, draggedShape) => { const guidedShapes = draggedPrimaryShape - ? [shapes.find(s => s.id === draggedPrimaryShape.id)].filter(identity) + ? [shapes.find((s) => s.id === draggedPrimaryShape.id)].filter(identity) : []; return guidedShapes.length - ? alignmentGuides(config, shapes, guidedShapes, draggedShape).map(shape => ({ + ? alignmentGuides(config, shapes, guidedShapes, draggedShape).map((shape) => ({ ...shape, id: config.alignmentGuideName + '_' + shape.id, type: 'annotation', @@ -1441,7 +1443,7 @@ export const getAlignmentGuideAnnotations = (config, shapes, draggedPrimaryShape : []; }; -const borderAnnotation = (subtype, lift) => shape => ({ +const borderAnnotation = (subtype, lift) => (shape) => ({ ...shape, id: subtype + '_' + shape.id, type: 'annotation', @@ -1452,16 +1454,18 @@ const borderAnnotation = (subtype, lift) => shape => ({ }); export const getAdHocChildrenAnnotations = (config, { shapes }) => { - const adHocGroups = shapes.filter(s => s.subtype === config.adHocGroupName); + const adHocGroups = shapes.filter((s) => s.subtype === config.adHocGroupName); return shapes - .filter(s => s.type !== 'annotation' && s.parent && adHocGroups.find(p => p.id === s.parent)) + .filter( + (s) => s.type !== 'annotation' && s.parent && adHocGroups.find((p) => p.id === s.parent) + ) .map(borderAnnotation(config.getAdHocChildAnnotationName, config.hoverLift)); }; export const getHoverAnnotations = (config, shapes, selectedPrimaryShapeIds, draggedShape) => shapes .filter( - shape => + (shape) => shape && shape.type !== 'annotation' && selectedPrimaryShapeIds.indexOf(shape.id) === -1 && @@ -1481,7 +1485,7 @@ export const getSnappedShapes = ( alterSnapGesture, symmetricManipulation ) => { - const contentShapes = shapes.filter(shape => shape.type !== 'annotation'); + const contentShapes = shapes.filter((shape) => shape.type !== 'annotation'); const subtype = draggedShape && draggedShape.subtype; // snapping doesn't come into play if there's no dragging, or it's not a resize drag or translate drag on a // leaf element or a group element: @@ -1513,7 +1517,7 @@ export const getSnappedShapes = ( }; export const getConstrainedShapesWithPreexistingAnnotations = (snapped, transformed) => - snapped.concat(transformed.filter(s => s.type === 'annotation')); + snapped.concat(transformed.filter((s) => s.type === 'annotation')); export const getGroupAction = (action, mouseIsDown) => { const event = action && action.event; @@ -1567,14 +1571,16 @@ const distributions = { distributeVertically: { type: 'distributeVerticallyAction', horizontal: false }, }; -export const getAlignAction = action => alignments[action && action.event] || null; -export const getDistributeAction = action => distributions[action && action.event] || null; +export const getAlignAction = (action) => alignments[action && action.event] || null; +export const getDistributeAction = (action) => distributions[action && action.event] || null; export const getGroupedSelectedShapes = ({ selectedShapes }) => selectedShapes; -export const getGroupedSelectedPrimaryShapeIds = selectedShapes => selectedShapes.map(primaryShape); +export const getGroupedSelectedPrimaryShapeIds = (selectedShapes) => + selectedShapes.map(primaryShape); -export const getGroupedSelectedShapeIds = selectedShapes => selectedShapes.map(shape => shape.id); +export const getGroupedSelectedShapeIds = (selectedShapes) => + selectedShapes.map((shape) => shape.id); export const getRotationAnnotations = (config, { shapes, selectedShapes }) => { const shapesToAnnotate = selectedShapes; @@ -1598,7 +1604,7 @@ export const getDragboxHighlighted = (box, shapes) => { } const filter = insideAABB(box); return shapes.filter( - s => s.type !== 'annotation' && !s.parent && filter(s.transformMatrix, s.a, s.b) + (s) => s.type !== 'annotation' && !s.parent && filter(s.transformMatrix, s.a, s.b) ); }; @@ -1639,7 +1645,7 @@ export const getAnnotatedShapes = ( dragBoxAnnotation ); // remove preexisting annotations - const contentShapes = shapes.filter(shape => shape.type !== 'annotation'); + const contentShapes = shapes.filter((shape) => shape.type !== 'annotation'); return contentShapes.concat(annotations); // add current annotations }; // collection of shapes themselves diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts index a7dfa91bc3e11..ee8a2b21f3cef 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts @@ -10,5 +10,5 @@ export const select = (fun: PlainFun): Selector => (...fns: Resolve[]) => { let prevId: ActionId = NaN; let cache: Json = null; const old = (object: State): boolean => prevId === (prevId = object.primaryUpdate.payload.uid); - return (obj: State) => (old(obj) ? cache : (cache = fun(...fns.map(f => f(obj))))); + return (obj: State) => (old(obj) ? cache : (cache = fun(...fns.map((f) => f(obj))))); }; diff --git a/x-pack/plugins/canvas/public/lib/arg_helpers.js b/x-pack/plugins/canvas/public/lib/arg_helpers.js index b674e158f3e34..9e4c93ed5f274 100644 --- a/x-pack/plugins/canvas/public/lib/arg_helpers.js +++ b/x-pack/plugins/canvas/public/lib/arg_helpers.js @@ -19,7 +19,7 @@ import { getType } from '@kbn/interpreter/common'; const allowedTypes = ['string', 'number', 'boolean']; const badType = () => new Error(`Arg setting helpers only support ${allowedTypes.join(',')}`); -const isAllowed = type => includes(allowedTypes, type); +const isAllowed = (type) => includes(allowedTypes, type); export function validateArg(value) { const type = getType(value); @@ -33,7 +33,7 @@ export function getSimpleArg(name, args) { if (!args[name]) { return []; } - return args[name].map(astVal => { + return args[name].map((astVal) => { if (!isAllowed(getType(astVal))) { throw badType(); } diff --git a/x-pack/plugins/canvas/public/lib/build_bool_array.js b/x-pack/plugins/canvas/public/lib/build_bool_array.js index 2dc6447753526..f1cab93ceebbb 100644 --- a/x-pack/plugins/canvas/public/lib/build_bool_array.js +++ b/x-pack/plugins/canvas/public/lib/build_bool_array.js @@ -6,11 +6,11 @@ import { getESFilter } from './get_es_filter'; -const compact = arr => (Array.isArray(arr) ? arr.filter(val => Boolean(val)) : []); +const compact = (arr) => (Array.isArray(arr) ? arr.filter((val) => Boolean(val)) : []); export function buildBoolArray(canvasQueryFilterArray) { return compact( - canvasQueryFilterArray.map(clause => { + canvasQueryFilterArray.map((clause) => { try { return getESFilter(clause); } catch (e) { diff --git a/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts b/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts index 9aa7477523c9a..c847bfb6516bf 100644 --- a/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts +++ b/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts @@ -18,7 +18,7 @@ const TimeFilterType = 'time'; function getTimeRangeFromFilters(filters: ExpressionValueFilter[]): TimeRange | undefined { const timeFilter = filters.find( - filter => filter.filterType !== undefined && filter.filterType === TimeFilterType + (filter) => filter.filterType !== undefined && filter.filterType === TimeFilterType ); return timeFilter !== undefined && timeFilter.from !== undefined && timeFilter.to !== undefined @@ -30,7 +30,7 @@ function getTimeRangeFromFilters(filters: ExpressionValueFilter[]): TimeRange | } export function getQueryFilters(filters: ExpressionValueFilter[]): DataFilter[] { - const dataFilters = filters.map(filter => ({ ...filter, type: filter.filterType })); + const dataFilters = filters.map((filter) => ({ ...filter, type: filter.filterType })); return buildBoolArray(dataFilters).map(esFilters.buildQueryFilter); } diff --git a/x-pack/plugins/canvas/public/lib/clone_subgraphs.js b/x-pack/plugins/canvas/public/lib/clone_subgraphs.js index 101492657b47b..e4dfa1cefcaba 100644 --- a/x-pack/plugins/canvas/public/lib/clone_subgraphs.js +++ b/x-pack/plugins/canvas/public/lib/clone_subgraphs.js @@ -7,13 +7,13 @@ import { arrayToMap } from './aeroelastic/functional'; import { getId } from './get_id'; -export const cloneSubgraphs = nodes => { - const idMap = arrayToMap(nodes.map(n => n.id)); +export const cloneSubgraphs = (nodes) => { + const idMap = arrayToMap(nodes.map((n) => n.id)); // We simultaneously provide unique id values for all elements (across all pages) // AND ensure that parent-child relationships are retained (via matching id values within page) - Object.keys(idMap).forEach(key => (idMap[key] = getId(key.split('-')[0]))); // new group names to which we can map + Object.keys(idMap).forEach((key) => (idMap[key] = getId(key.split('-')[0]))); // new group names to which we can map // must return elements in the same order, for several reasons - const newNodes = nodes.map(element => ({ + const newNodes = nodes.map((element) => ({ ...element, id: idMap[element.id], position: { diff --git a/x-pack/plugins/canvas/public/lib/custom_element_service.ts b/x-pack/plugins/canvas/public/lib/custom_element_service.ts index 8952802dc2f2b..25c3b78a2746e 100644 --- a/x-pack/plugins/canvas/public/lib/custom_element_service.ts +++ b/x-pack/plugins/canvas/public/lib/custom_element_service.ts @@ -10,7 +10,7 @@ import { fetch } from '../../common/lib/fetch'; import { CustomElement } from '../../types'; import { platformService } from '../services'; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_CUSTOM_ELEMENT}`; }; diff --git a/x-pack/plugins/canvas/public/lib/doc_title.js b/x-pack/plugins/canvas/public/lib/doc_title.js index 3f75d18df14d2..ce31a58fa359c 100644 --- a/x-pack/plugins/canvas/public/lib/doc_title.js +++ b/x-pack/plugins/canvas/public/lib/doc_title.js @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const setDocTitle = title => (document.title = `${title} - Kibana`); +export const setDocTitle = (title) => (document.title = `${title} - Kibana`); diff --git a/x-pack/plugins/canvas/public/lib/element_handler_creators.ts b/x-pack/plugins/canvas/public/lib/element_handler_creators.ts index a8744b4820842..d280c62888df0 100644 --- a/x-pack/plugins/canvas/public/lib/element_handler_creators.ts +++ b/x-pack/plugins/canvas/public/lib/element_handler_creators.ts @@ -95,8 +95,9 @@ export const basicHandlerCreators = { ) .catch((error: Error) => notifyService.getService().warning(error, { - title: `Custom element '${customElement.displayName || - customElement.id}' was not saved`, + title: `Custom element '${ + customElement.displayName || customElement.id + }' was not saved`, }) ); } @@ -186,7 +187,7 @@ export const layerHandlerCreators = { export const positionHandlerCreators = { shiftUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top -= ELEMENT_SHIFT_OFFSET; return element; }) @@ -194,7 +195,7 @@ export const positionHandlerCreators = { }, shiftDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top += ELEMENT_SHIFT_OFFSET; return element; }) @@ -202,7 +203,7 @@ export const positionHandlerCreators = { }, shiftLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left -= ELEMENT_SHIFT_OFFSET; return element; }) @@ -210,7 +211,7 @@ export const positionHandlerCreators = { }, shiftRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left += ELEMENT_SHIFT_OFFSET; return element; }) @@ -218,7 +219,7 @@ export const positionHandlerCreators = { }, nudgeUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top -= ELEMENT_NUDGE_OFFSET; return element; }) @@ -226,7 +227,7 @@ export const positionHandlerCreators = { }, nudgeDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top += ELEMENT_NUDGE_OFFSET; return element; }) @@ -234,7 +235,7 @@ export const positionHandlerCreators = { }, nudgeLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left -= ELEMENT_NUDGE_OFFSET; return element; }) @@ -242,7 +243,7 @@ export const positionHandlerCreators = { }, nudgeRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left += ELEMENT_NUDGE_OFFSET; return element; }) diff --git a/x-pack/plugins/canvas/public/lib/es_service.ts b/x-pack/plugins/canvas/public/lib/es_service.ts index 184f4f3c8af7c..496751a874b21 100644 --- a/x-pack/plugins/canvas/public/lib/es_service.ts +++ b/x-pack/plugins/canvas/public/lib/es_service.ts @@ -15,16 +15,16 @@ import { platformService } from '../services'; const { esService: strings } = ErrorStrings; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return basePath + API_ROUTE; }; -const getSavedObjectsClient = function() { +const getSavedObjectsClient = function () { return platformService.getService().coreStart.savedObjects.client; }; -const getAdvancedSettings = function() { +const getAdvancedSettings = function () { return platformService.getService().coreStart.uiSettings; }; @@ -33,7 +33,7 @@ export const getFields = (index = '_all') => { .get(`${getApiPath()}/es_fields?index=${index}`) .then(({ data: mapping }: { data: object }) => Object.keys(mapping) - .filter(field => !field.startsWith('_')) // filters out meta fields + .filter((field) => !field.startsWith('_')) // filters out meta fields .sort() ) .catch((err: Error) => @@ -51,8 +51,8 @@ export const getIndices = () => searchFields: ['title'], perPage: 1000, }) - .then(resp => { - return resp.savedObjects.map(savedObject => { + .then((resp) => { + return resp.savedObjects.map((savedObject) => { return savedObject.attributes.title; }); }) @@ -66,8 +66,8 @@ export const getDefaultIndex = () => { return defaultIndexId ? getSavedObjectsClient() .get('index-pattern', defaultIndexId) - .then(defaultIndex => defaultIndex.attributes.title) - .catch(err => + .then((defaultIndex) => defaultIndex.attributes.title) + .catch((err) => notifyService .getService() .error(err, { title: strings.getDefaultIndexFetchErrorMessage() }) diff --git a/x-pack/plugins/canvas/public/lib/extract_search.js b/x-pack/plugins/canvas/public/lib/extract_search.js index 9ad0a6cd8f0c3..1d472b1c9dbb4 100644 --- a/x-pack/plugins/canvas/public/lib/extract_search.js +++ b/x-pack/plugins/canvas/public/lib/extract_search.js @@ -6,12 +6,12 @@ // EUI helper // extracts search text and array of selected tags from EuiSearchBar -export const extractSearch = queryText => { +export const extractSearch = (queryText) => { const filterTags = []; const searchTerms = []; const parts = queryText.split(' '); - parts.forEach(part => { + parts.forEach((part) => { if (part.indexOf(':') >= 0) { const [key, value] = part.split(':'); if (key === 'tag') { diff --git a/x-pack/plugins/canvas/public/lib/find_existing_asset.js b/x-pack/plugins/canvas/public/lib/find_existing_asset.js index 470d7797e6feb..2a6f48c31cd24 100644 --- a/x-pack/plugins/canvas/public/lib/find_existing_asset.js +++ b/x-pack/plugins/canvas/public/lib/find_existing_asset.js @@ -6,7 +6,7 @@ export const findExistingAsset = (type, content, assets) => { const existingId = Object.keys(assets).find( - assetId => assets[assetId].type === type && assets[assetId].value === content + (assetId) => assets[assetId].type === type && assets[assetId].value === content ); return existingId; }; diff --git a/x-pack/plugins/canvas/public/lib/find_expression_type.js b/x-pack/plugins/canvas/public/lib/find_expression_type.js index 2cd7c5efb74e9..4b09ba1ac8dd4 100644 --- a/x-pack/plugins/canvas/public/lib/find_expression_type.js +++ b/x-pack/plugins/canvas/public/lib/find_expression_type.js @@ -13,7 +13,7 @@ const expressionTypes = ['view', 'model', 'transform', 'datasource']; export function findExpressionType(name, type) { const checkTypes = expressionTypes.filter( - expressionType => type == null || expressionType === type + (expressionType) => type == null || expressionType === type ); const matches = checkTypes.reduce((acc, checkType) => { diff --git a/x-pack/plugins/canvas/public/lib/history_provider.js b/x-pack/plugins/canvas/public/lib/history_provider.js index 4ff9f0b9d4605..649f101126012 100644 --- a/x-pack/plugins/canvas/public/lib/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/history_provider.js @@ -125,7 +125,7 @@ function wrapHistoryInstance(history) { const prevLocationObj = locationFormat(prevLocation, action, wrappedHistory.parse); // execute all listeners - historyState.onChange.forEach(fn => fn.call(null, locationObj, prevLocationObj)); + historyState.onChange.forEach((fn) => fn.call(null, locationObj, prevLocationObj)); // track the updated location historyState.prevLocation = wrappedHistory.getLocation(); @@ -136,7 +136,7 @@ function wrapHistoryInstance(history) { let instances = new WeakMap(); -const getHistoryInstance = win => { +const getHistoryInstance = (win) => { // if no window object, use memory module if (typeof win === 'undefined' || !win.history) { return createMemoryHistory(); diff --git a/x-pack/plugins/canvas/public/lib/keymap.ts b/x-pack/plugins/canvas/public/lib/keymap.ts index 7976c8ed5c5da..7ca93f440087e 100644 --- a/x-pack/plugins/canvas/public/lib/keymap.ts +++ b/x-pack/plugins/canvas/public/lib/keymap.ts @@ -37,20 +37,20 @@ const getShortcuts = ( // handle shift modifier if (modifiers.includes('shift')) { - macShortcuts = macShortcuts.map(shortcut => `shift+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `shift+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `shift+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `shift+${shortcut}`); } // handle alt modifier if (modifiers.includes('alt') || modifiers.includes('option')) { - macShortcuts = macShortcuts.map(shortcut => `option+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `alt+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `option+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `alt+${shortcut}`); } // handle ctrl modifier if (modifiers.includes('ctrl') || modifiers.includes('command')) { - macShortcuts = macShortcuts.map(shortcut => `command+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `ctrl+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `command+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `ctrl+${shortcut}`); } return { diff --git a/x-pack/plugins/canvas/public/lib/load_expression_types.js b/x-pack/plugins/canvas/public/lib/load_expression_types.js index 82699eb5b88fa..23a14d079c091 100644 --- a/x-pack/plugins/canvas/public/lib/load_expression_types.js +++ b/x-pack/plugins/canvas/public/lib/load_expression_types.js @@ -9,5 +9,5 @@ import { argTypeRegistry } from '../expression_types'; export function loadExpressionTypes() { // register default args, arg types, and expression types - argTypeSpecs.forEach(expFn => argTypeRegistry.register(expFn)); + argTypeSpecs.forEach((expFn) => argTypeRegistry.register(expFn)); } diff --git a/x-pack/plugins/canvas/public/lib/load_transitions.js b/x-pack/plugins/canvas/public/lib/load_transitions.js index 915d63142bbf7..c4d91533435b8 100644 --- a/x-pack/plugins/canvas/public/lib/load_transitions.js +++ b/x-pack/plugins/canvas/public/lib/load_transitions.js @@ -8,5 +8,5 @@ import { transitions } from '../transitions'; import { transitionsRegistry } from './transitions_registry'; export function loadTransitions() { - transitions.forEach(spec => transitionsRegistry.register(spec)); + transitions.forEach((spec) => transitionsRegistry.register(spec)); } diff --git a/x-pack/plugins/canvas/public/lib/monaco_language_def.ts b/x-pack/plugins/canvas/public/lib/monaco_language_def.ts index 5dac7fcc9bc50..7bd9ea7b6ef9a 100644 --- a/x-pack/plugins/canvas/public/lib/monaco_language_def.ts +++ b/x-pack/plugins/canvas/public/lib/monaco_language_def.ts @@ -95,7 +95,7 @@ export const language: Language = { }; export function registerLanguage(functions: ExpressionFunction[]) { - language.keywords = functions.map(fn => fn.name); + language.keywords = functions.map((fn) => fn.name); monaco.languages.register({ id: LANGUAGE_ID }); monaco.languages.setMonarchTokensProvider(LANGUAGE_ID, language); diff --git a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js index fb67379550b1d..4b23ba0941e88 100644 --- a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js +++ b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js @@ -17,7 +17,7 @@ export function parseSingleFunctionChain(filterString) { throw new Error('Could not find function name in chain'); } - const args = mapValues(get(ast, 'chain[0].arguments'), val => { + const args = mapValues(get(ast, 'chain[0].arguments'), (val) => { // TODO Check for literals only return map(val, 'value'); }); diff --git a/x-pack/plugins/canvas/public/lib/router_provider.js b/x-pack/plugins/canvas/public/lib/router_provider.js index 42960baa00de1..b518241585a10 100644 --- a/x-pack/plugins/canvas/public/lib/router_provider.js +++ b/x-pack/plugins/canvas/public/lib/router_provider.js @@ -23,7 +23,7 @@ export function routerProvider(routes) { const componentListeners = []; // assume any string starting with a / is a path - const isPath = str => typeof str === 'string' && str.substr(0, 1) === '/'; + const isPath = (str) => typeof str === 'string' && str.substr(0, 1) === '/'; // helper to get the current state in history const getState = (name, params, state) => { @@ -36,7 +36,7 @@ export function routerProvider(routes) { // helper to append appState to a given url path const appendAppState = (path, appState = getCurrentAppState()) => { - const newUrl = modifyUrl(path, parts => { + const newUrl = modifyUrl(path, (parts) => { parts.query = assignAppState(parts.query, appState); }); @@ -78,7 +78,7 @@ export function routerProvider(routes) { history[method](currentState, newPath); }, onPathChange(fn) { - const execOnMatch = location => { + const execOnMatch = (location) => { const { pathname } = location; const match = this.match(pathname); diff --git a/x-pack/plugins/canvas/public/lib/run_interpreter.ts b/x-pack/plugins/canvas/public/lib/run_interpreter.ts index df338f40e08d9..bd00cad4fcbe7 100644 --- a/x-pack/plugins/canvas/public/lib/run_interpreter.ts +++ b/x-pack/plugins/canvas/public/lib/run_interpreter.ts @@ -12,7 +12,7 @@ import { CanvasStartDeps, CanvasSetupDeps } from '../plugin'; let expressionsStarting: Promise | undefined; -export const initInterpreter = function( +export const initInterpreter = function ( expressionsStart: CanvasStartDeps['expressions'], expressionsSetup: CanvasSetupDeps['expressions'] ) { @@ -29,7 +29,7 @@ async function startExpressions( return expressionsStart; } -export const resetInterpreter = function() { +export const resetInterpreter = function () { expressionsStarting = undefined; }; diff --git a/x-pack/plugins/canvas/public/lib/template.js b/x-pack/plugins/canvas/public/lib/template.js index b7bf4c608d18d..d548d707e7aa0 100644 --- a/x-pack/plugins/canvas/public/lib/template.js +++ b/x-pack/plugins/canvas/public/lib/template.js @@ -25,7 +25,7 @@ export function Template(config) { // Tags for categorizing the template this.tags = config.tags || []; - this.tags.forEach(tag => { + this.tags.forEach((tag) => { if (!tagsRegistry.get(tag)) { tagsRegistry.register(() => ({ name: tag, color: '#666666' })); } diff --git a/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx b/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx index f5059dfa04b95..17e2712c44b8d 100644 --- a/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx +++ b/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx @@ -16,7 +16,7 @@ interface Props { } export const templateFromReactComponent = (Component: ComponentType) => { - const WrappedComponent: FunctionComponent = props => ( + const WrappedComponent: FunctionComponent = (props) => ( {({ error }: { error: Error }) => { if (error) { diff --git a/x-pack/plugins/canvas/public/lib/window_error_handler.js b/x-pack/plugins/canvas/public/lib/window_error_handler.js index 75307816b4371..b4dd850b56c44 100644 --- a/x-pack/plugins/canvas/public/lib/window_error_handler.js +++ b/x-pack/plugins/canvas/public/lib/window_error_handler.js @@ -15,7 +15,7 @@ function showError(err) { const close = document.createElement('a'); close.textContent = 'close'; - close.onclick = ev => { + close.onclick = (ev) => { ev.preventDefault(); body.removeChild(notice); }; @@ -29,11 +29,7 @@ function showError(err) { if (err.stack) { const stack = document.createElement('pre'); - stack.textContent = err.stack - .split('\n') - .slice(0, 2) - .concat('...') - .join('\n'); + stack.textContent = err.stack.split('\n').slice(0, 2).concat('...').join('\n'); notice.appendChild(stack); } @@ -54,7 +50,7 @@ window.canvasInitErrorHandler = () => { console.log(message); const isKnownError = message.includes('ResizeObserver loop') || - Object.keys(knownErrors).find(errorName => { + Object.keys(knownErrors).find((errorName) => { return err.constructor.name === errorName || message.indexOf(errorName) >= 0; }); if (isKnownError) { diff --git a/x-pack/plugins/canvas/public/lib/workpad_service.js b/x-pack/plugins/canvas/public/lib/workpad_service.js index e6628399f53c2..1ac2aa222927b 100644 --- a/x-pack/plugins/canvas/public/lib/workpad_service.js +++ b/x-pack/plugins/canvas/public/lib/workpad_service.js @@ -30,7 +30,7 @@ const validKeys = [ 'width', ]; -const sanitizeWorkpad = function(workpad) { +const sanitizeWorkpad = function (workpad) { const workpadKeys = Object.keys(workpad); for (const key of workpadKeys) { @@ -42,17 +42,17 @@ const sanitizeWorkpad = function(workpad) { return workpad; }; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD}`; }; -const getApiPathStructures = function() { +const getApiPathStructures = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD_STRUCTURES}`; }; -const getApiPathAssets = function() { +const getApiPathAssets = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD_ASSETS}`; }; diff --git a/x-pack/plugins/canvas/public/plugin_api.ts b/x-pack/plugins/canvas/public/plugin_api.ts index 738b319d29c0b..4314c77456527 100644 --- a/x-pack/plugins/canvas/public/plugin_api.ts +++ b/x-pack/plugins/canvas/public/plugin_api.ts @@ -57,32 +57,32 @@ export function getPluginApi( const api: CanvasApi = { // Functions, types and renderers are registered directly to expression plugin - addFunctions: fns => { - fns.forEach(fn => { + addFunctions: (fns) => { + fns.forEach((fn) => { expressionsPluginSetup.registerFunction(fn); }); }, - addTypes: types => { - types.forEach(type => { + addTypes: (types) => { + types.forEach((type) => { expressionsPluginSetup.registerType(type as any); }); }, - addRenderers: renderers => { + addRenderers: (renderers) => { renderers.forEach((r: any) => { expressionsPluginSetup.registerRenderer(r); }); }, // All these others are local to canvas, and they will only register on start - addElements: elements => registries.elements.push(...elements), - addTransformUIs: transforms => registries.transformUIs.push(...transforms), - addDatasourceUIs: datasources => registries.datasourceUIs.push(...datasources), - addModelUIs: models => registries.modelUIs.push(...models), - addViewUIs: views => registries.viewUIs.push(...views), - addArgumentUIs: args => registries.argumentUIs.push(...args), - addTemplates: templates => registries.templates.push(...templates), - addTagUIs: tags => registries.tagUIs.push(...tags), - addTransitions: transitions => registries.transitions.push(...transitions), + addElements: (elements) => registries.elements.push(...elements), + addTransformUIs: (transforms) => registries.transformUIs.push(...transforms), + addDatasourceUIs: (datasources) => registries.datasourceUIs.push(...datasources), + addModelUIs: (models) => registries.modelUIs.push(...models), + addViewUIs: (views) => registries.viewUIs.push(...views), + addArgumentUIs: (args) => registries.argumentUIs.push(...args), + addTemplates: (templates) => registries.templates.push(...templates), + addTagUIs: (tags) => registries.tagUIs.push(...tags), + addTransitions: (transitions) => registries.transitions.push(...transitions), }; return { api, registries }; diff --git a/x-pack/plugins/canvas/public/state/actions/elements.js b/x-pack/plugins/canvas/public/state/actions/elements.js index 5ec8eb6137f2b..47fbc782f90d3 100644 --- a/x-pack/plugins/canvas/public/state/actions/elements.js +++ b/x-pack/plugins/canvas/public/state/actions/elements.js @@ -55,7 +55,7 @@ function getBareElement(el, includeId = false) { export const elementLayer = createAction('elementLayer'); -export const setMultiplePositions = createAction('setMultiplePosition', repositionedElements => ({ +export const setMultiplePositions = createAction('setMultiplePosition', (repositionedElements) => ({ repositionedElements, })); @@ -103,7 +103,7 @@ export const fetchContext = createThunk( chain: astChain, }, prevContextValue - ).then(value => { + ).then((value) => { dispatch( args.setValue({ path: contextPath, @@ -122,17 +122,17 @@ const fetchRenderableWithContextFn = ({ dispatch }, element, ast, context) => { }) ); - const getAction = renderable => + const getAction = (renderable) => args.setValue({ path: argumentPath, value: renderable, }); return runInterpreter(ast, context, { castToRender: true }) - .then(renderable => { + .then((renderable) => { dispatch(getAction(renderable)); }) - .catch(err => { + .catch((err) => { services.notify.getService().error(err); dispatch(getAction(err)); }); @@ -162,25 +162,25 @@ export const fetchAllRenderables = createThunk( function fetchElementsOnPages(pages) { const elements = []; - pages.forEach(page => { - page.elements.forEach(element => { + pages.forEach((page) => { + page.elements.forEach((element) => { elements.push(element); }); }); - const renderablePromises = elements.map(element => { + const renderablePromises = elements.map((element) => { const ast = element.ast || safeElementFromExpression(element.expression); const argumentPath = [element.id, 'expressionRenderable']; return runInterpreter(ast, null, { castToRender: true }) - .then(renderable => ({ path: argumentPath, value: renderable })) - .catch(err => { + .then((renderable) => ({ path: argumentPath, value: renderable })) + .catch((err) => { services.notify.getService().error(err); return { path: argumentPath, value: err }; }); }); - return Promise.all(renderablePromises).then(renderables => { + return Promise.all(renderablePromises).then((renderables) => { dispatch(args.setValues(renderables)); }); } @@ -203,17 +203,17 @@ export const insertNodes = createThunk('insertNodes', ({ dispatch, type }, eleme const _insertNodes = createAction(type); const newElements = elements.map(cloneDeep); // move the root element so users can see that it was added - newElements.forEach(newElement => { + newElements.forEach((newElement) => { newElement.position.top = newElement.position.top + 10; newElement.position.left = newElement.position.left + 10; }); dispatch(_insertNodes({ pageId, elements: newElements })); // refresh all elements just once per `insertNodes call` if there's a filter on any, otherwise just render the new element - if (elements.some(element => element.filter)) { + if (elements.some((element) => element.filter)) { dispatch(fetchAllRenderables()); } else { - newElements.forEach(newElement => dispatch(fetchRenderable(newElement))); + newElements.forEach((newElement) => dispatch(fetchRenderable(newElement))); } }); @@ -224,15 +224,17 @@ export const removeElements = createThunk( // todo consider doing the group membership collation in aeroelastic, or the Redux reducer, when adding templates const allElements = getNodes(state, pageId); - const allRoots = rootElementIds.map(id => allElements.find(e => id === e.id)).filter(d => d); + const allRoots = rootElementIds + .map((id) => allElements.find((e) => id === e.id)) + .filter((d) => d); const elementIds = subMultitree( - e => e.id, - e => e.position.parent, + (e) => e.id, + (e) => e.position.parent, allElements, allRoots - ).map(e => e.id); + ).map((e) => e.id); - const shouldRefresh = elementIds.some(elementId => { + const shouldRefresh = elementIds.some((elementId) => { const element = getNodeById(state, elementId, pageId); const filterIsApplied = element.filter && element.filter.length > 0; return filterIsApplied; @@ -275,7 +277,7 @@ function setExpressionFn({ dispatch, getState }, expression, elementId, pageId, // TODO: find a way to extract a list of filter renderers from the functions registry if ( updatedElement.filter && - !['dropdownControl', 'timefilterControl', 'exactly'].some(filter => + !['dropdownControl', 'timefilterControl', 'exactly'].some((filter) => updatedElement.expression.includes(filter) ) ) { diff --git a/x-pack/plugins/canvas/public/state/actions/embeddable.ts b/x-pack/plugins/canvas/public/state/actions/embeddable.ts index 3604d7e3c2141..e2cf588ec20a9 100644 --- a/x-pack/plugins/canvas/public/state/actions/embeddable.ts +++ b/x-pack/plugins/canvas/public/state/actions/embeddable.ts @@ -24,12 +24,12 @@ export const updateEmbeddableExpression = createAction State }, elementId: string) => { - const pageWithElement = getState().persistent.workpad.pages.find(page => { - return page.elements.find(element => element.id === elementId) !== undefined; + const pageWithElement = getState().persistent.workpad.pages.find((page) => { + return page.elements.find((element) => element.id === elementId) !== undefined; }); if (pageWithElement) { - const element = pageWithElement.elements.find(el => el.id === elementId); + const element = pageWithElement.elements.find((el) => el.id === elementId); dispatch(fetchRenderable(element)); } } diff --git a/x-pack/plugins/canvas/public/state/initial_state.js b/x-pack/plugins/canvas/public/state/initial_state.js index bfa68b33908e0..13021893e72e8 100644 --- a/x-pack/plugins/canvas/public/state/initial_state.js +++ b/x-pack/plugins/canvas/public/state/initial_state.js @@ -8,7 +8,7 @@ import { get } from 'lodash'; import { platformService } from '../services'; import { getDefaultWorkpad } from './defaults'; -export const getInitialState = path => { +export const getInitialState = (path) => { const state = { app: {}, // Kibana stuff in here assets: {}, // assets end up here diff --git a/x-pack/plugins/canvas/public/state/middleware/app_ready.js b/x-pack/plugins/canvas/public/state/middleware/app_ready.js index a86f67b5e1cc4..0b2fce4227197 100644 --- a/x-pack/plugins/canvas/public/state/middleware/app_ready.js +++ b/x-pack/plugins/canvas/public/state/middleware/app_ready.js @@ -7,7 +7,7 @@ import { isAppReady } from '../selectors/app'; import { appReady as readyAction } from '../actions/app'; -export const appReady = ({ dispatch, getState }) => next => action => { +export const appReady = ({ dispatch, getState }) => (next) => (action) => { // execute the action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js b/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js index b949e7025acbf..864e61b5a8f96 100644 --- a/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js +++ b/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js @@ -7,7 +7,7 @@ import { getWorkpad } from '../selectors/workpad'; import { getBaseBreadcrumb, getWorkpadBreadcrumb, setBreadcrumb } from '../../lib/breadcrumbs'; -export const breadcrumbs = ({ getState }) => next => action => { +export const breadcrumbs = ({ getState }) => (next) => (action) => { // capture the current workpad const currentWorkpad = getWorkpad(getState()); diff --git a/x-pack/plugins/canvas/public/state/middleware/element_stats.js b/x-pack/plugins/canvas/public/state/middleware/element_stats.js index 17ab9393734e0..1c19f26102996 100644 --- a/x-pack/plugins/canvas/public/state/middleware/element_stats.js +++ b/x-pack/plugins/canvas/public/state/middleware/element_stats.js @@ -7,7 +7,7 @@ import { setElementStats } from '../actions/transient'; import { getAllElements, getElementCounts, getElementStats } from '../selectors/workpad'; -export const elementStats = ({ dispatch, getState }) => next => action => { +export const elementStats = ({ dispatch, getState }) => (next) => (action) => { // execute the action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/es_persist.js b/x-pack/plugins/canvas/public/state/middleware/es_persist.js index a197cdf893244..e0db595552198 100644 --- a/x-pack/plugins/canvas/public/state/middleware/es_persist.js +++ b/x-pack/plugins/canvas/public/state/middleware/es_persist.js @@ -40,9 +40,9 @@ export const esPersistMiddleware = ({ getState }) => { setRefreshInterval, // used to set refresh time interval which is a transient value ...Object.values(resolvedArgsActions), // no resolved args affect persisted values ...Object.values(transientActions), // no transient actions cause persisted state changes - ].map(a => a.toString()); + ].map((a) => a.toString()); - return next => action => { + return (next) => (action) => { // if the action is in the skipped list, do not persist if (skippedActions.indexOf(action.type) >= 0) { return next(action); @@ -58,7 +58,7 @@ export const esPersistMiddleware = ({ getState }) => { return; } - const notifyError = err => { + const notifyError = (err) => { const statusCode = err.response && err.response.status; switch (statusCode) { case 400: diff --git a/x-pack/plugins/canvas/public/state/middleware/fullscreen.js b/x-pack/plugins/canvas/public/state/middleware/fullscreen.js index 92ac35173b196..dfaf0a5e87b32 100644 --- a/x-pack/plugins/canvas/public/state/middleware/fullscreen.js +++ b/x-pack/plugins/canvas/public/state/middleware/fullscreen.js @@ -9,7 +9,7 @@ import { setFullscreen as setAppStateFullscreen } from '../../lib/app_state'; import { setFullscreen as setFullscreenAction } from '../actions/transient'; import { getFullscreen } from '../selectors/app'; -export const fullscreen = ({ getState }) => next => action => { +export const fullscreen = ({ getState }) => (next) => (action) => { // execute the default action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/history.js b/x-pack/plugins/canvas/public/state/middleware/history.js index 206c86e93de91..28eb12e4b68da 100644 --- a/x-pack/plugins/canvas/public/state/middleware/history.js +++ b/x-pack/plugins/canvas/public/state/middleware/history.js @@ -22,8 +22,8 @@ function getHistoryState(state) { export const historyMiddleware = ({ dispatch, getState }) => { // iterate over routes, injecting redux to action handlers - const reduxInject = routes => { - return routes.map(route => { + const reduxInject = (routes) => { + return routes.map((route) => { if (route.children) { return { ...route, @@ -96,7 +96,7 @@ export const historyMiddleware = ({ dispatch, getState }) => { } }); - return next => action => { + return (next) => (action) => { const oldState = getState(); // deal with history actions diff --git a/x-pack/plugins/canvas/public/state/middleware/resolved_args.js b/x-pack/plugins/canvas/public/state/middleware/resolved_args.js index 7dd0404cd5a19..d47a320392039 100644 --- a/x-pack/plugins/canvas/public/state/middleware/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/middleware/resolved_args.js @@ -11,17 +11,17 @@ import { clearValues } from '../actions/resolved_args'; * This middleware is responsible for keeping the resolved_args collection in transient state * synced with the elements represented by the workpad. */ -export const resolvedArgs = ({ dispatch, getState }) => next => action => { +export const resolvedArgs = ({ dispatch, getState }) => (next) => (action) => { // Get the Element IDs that are present before the action. - const startElementIds = getAllElements(getState()).map(element => element.id); + const startElementIds = getAllElements(getState()).map((element) => element.id); // execute the action next(action); // Get the Element IDs after the action... - const resolvedElementIds = getAllElements(getState()).map(element => element.id); + const resolvedElementIds = getAllElements(getState()).map((element) => element.id); // ...and get a list of IDs that are no longer present. - const deadIds = startElementIds.filter(id => !resolvedElementIds.includes(id)); + const deadIds = startElementIds.filter((id) => !resolvedElementIds.includes(id)); // If we have some dead elements, we need to clear them from resolved_args collection // in transient state. diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts b/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts index 700905213f54c..1fdfcacaa2244 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts @@ -14,7 +14,7 @@ import { routerProvider } from '../../lib/router_provider'; import { setAutoplayInterval } from '../../lib/app_state'; import { createTimeInterval } from '../../lib/time_interval'; -export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => next => { +export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => (next) => { let playTimeout: number | undefined; let displayInterval = 0; @@ -62,7 +62,7 @@ export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => next => } } - return action => { + return (action) => { next(action); const isFullscreen = getFullscreen(getState()); diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts index f638c42ec2de0..54ebec0dfbbb6 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts @@ -16,7 +16,7 @@ import { getRefreshInterval } from '../selectors/workpad'; import { setRefreshInterval as setAppStateRefreshInterval } from '../../lib/app_state'; import { createTimeInterval } from '../../lib/time_interval'; -export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => next => { +export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => (next) => { let refreshTimeout: number | undefined; let refreshInterval = 0; @@ -52,7 +52,7 @@ export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => } } - return action => { + return (action) => { const previousRefreshInterval = getRefreshInterval(getState()); next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_update.js b/x-pack/plugins/canvas/public/state/middleware/workpad_update.js index 76d699c68a19d..88c5b502b3bad 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_update.js +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_update.js @@ -11,7 +11,7 @@ import { getWorkpadName, isWriteable } from '../selectors/workpad'; import { getWindow } from '../../lib/get_window'; import { setDocTitle } from '../../lib/doc_title'; -export const workpadUpdate = ({ dispatch, getState }) => next => action => { +export const workpadUpdate = ({ dispatch, getState }) => (next) => (action) => { const oldIsWriteable = isWriteable(getState()); const oldName = getWorkpadName(getState()); diff --git a/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js b/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js index b95186cdce99e..1e734c8261e4d 100644 --- a/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js +++ b/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js @@ -4,6 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export const actionCreator = type => { +export const actionCreator = (type) => { return (payload, error = null, meta = null) => ({ type, payload, error, meta }); }; diff --git a/x-pack/plugins/canvas/public/state/reducers/app.js b/x-pack/plugins/canvas/public/state/reducers/app.js index 8027bac4e1b09..18c8ba995ac69 100644 --- a/x-pack/plugins/canvas/public/state/reducers/app.js +++ b/x-pack/plugins/canvas/public/state/reducers/app.js @@ -9,7 +9,7 @@ import { appReady, appError } from '../actions/app'; export const appReducer = handleActions( { - [appReady]: appState => ({ ...appState, ready: true }), + [appReady]: (appState) => ({ ...appState, ready: true }), [appError]: (appState, { payload }) => ({ ...appState, ready: payload }), }, {} diff --git a/x-pack/plugins/canvas/public/state/reducers/elements.js b/x-pack/plugins/canvas/public/state/reducers/elements.js index 630694a860aad..5d6bba1ab7406 100644 --- a/x-pack/plugins/canvas/public/state/reducers/elements.js +++ b/x-pack/plugins/canvas/public/state/reducers/elements.js @@ -11,28 +11,28 @@ import * as actions from '../actions/elements'; const { assign, push, del, set } = immutable; -const getLocation = type => (type === 'group' ? 'groups' : 'elements'); +const getLocation = (type) => (type === 'group' ? 'groups' : 'elements'); const firstOccurrence = (element, index, array) => array.indexOf(element) === index; const getLocationFromIds = (workpadState, pageId, nodeId) => { - const page = workpadState.pages.find(p => p.id === pageId); + const page = workpadState.pages.find((p) => p.id === pageId); const groups = page == null ? [] : page.groups || []; - return groups.find(e => e.id === nodeId) ? 'groups' : 'elements'; + return groups.find((e) => e.id === nodeId) ? 'groups' : 'elements'; }; function getPageIndexById(workpadState, pageId) { - return get(workpadState, 'pages', []).findIndex(page => page.id === pageId); + return get(workpadState, 'pages', []).findIndex((page) => page.id === pageId); } function getNodeIndexById(page, nodeId, location) { - return page[location].findIndex(node => node.id === nodeId); + return page[location].findIndex((node) => node.id === nodeId); } export function assignNodeProperties(workpadState, pageId, nodeId, props) { const pageIndex = getPageIndexById(workpadState, pageId); const location = getLocationFromIds(workpadState, pageId, nodeId); const nodesPath = `pages.${pageIndex}.${location}`; - const nodeIndex = get(workpadState, nodesPath, []).findIndex(node => node.id === nodeId); + const nodeIndex = get(workpadState, nodesPath, []).findIndex((node) => node.id === nodeId); if (pageIndex === -1 || nodeIndex === -1) { return workpadState; @@ -47,7 +47,7 @@ function moveNodeLayer(workpadState, pageId, nodeId, movement, location) { const nodes = get(workpadState, ['pages', pageIndex, location]); const from = nodeIndex; - const to = (function() { + const to = (function () { if (movement < Infinity && movement > -Infinity) { return nodeIndex + movement; } @@ -88,8 +88,8 @@ const trimElement = ({ id, position, expression, filter }) => ({ }); const getPageWithElementId = (workpad, elementId) => { - const matchingPage = workpad.pages.find(page => - page.elements.map(element => element.id).includes(elementId) + const matchingPage = workpad.pages.find((page) => + page.elements.map((element) => element.id).includes(elementId) ); if (matchingPage) { @@ -131,7 +131,7 @@ export const elementsReducer = handleActions( if ( // don't add a group that is already persisted workpadState.pages[pageIndex][getLocation(element.position.type)].find( - e => e.id === element.id + (e) => e.id === element.id ) ) { return workpadState; @@ -165,7 +165,7 @@ export const elementsReducer = handleActions( const nodeIndices = elementIds .filter(firstOccurrence) - .map(nodeId => { + .map((nodeId) => { const location = getLocationFromIds(workpadState, pageId, nodeId); return { location, diff --git a/x-pack/plugins/canvas/public/state/reducers/embeddable.ts b/x-pack/plugins/canvas/public/state/reducers/embeddable.ts index 9969c38cfa767..8642239fa10d3 100644 --- a/x-pack/plugins/canvas/public/state/reducers/embeddable.ts +++ b/x-pack/plugins/canvas/public/state/reducers/embeddable.ts @@ -29,15 +29,15 @@ export const embeddableReducer = handleActions< const { elementId, embeddableExpression } = payload; // Find the element - const pageWithElement = workpadState.pages.find(page => { - return page.elements.find(element => element.id === elementId) !== undefined; + const pageWithElement = workpadState.pages.find((page) => { + return page.elements.find((element) => element.id === elementId) !== undefined; }); if (!pageWithElement) { return workpadState; } - const element = pageWithElement.elements.find(elem => elem.id === elementId); + const element = pageWithElement.elements.find((elem) => elem.id === elementId); if (!element) { return workpadState; @@ -48,7 +48,7 @@ export const embeddableReducer = handleActions< const searchForFunction = newAst.chain[0].function; // Find the first matching function in the existing ASt - const existingAstFunction = existingAst.chain.find(f => f.function === searchForFunction); + const existingAstFunction = existingAst.chain.find((f) => f.function === searchForFunction); if (!existingAstFunction) { return workpadState; diff --git a/x-pack/plugins/canvas/public/state/reducers/pages.js b/x-pack/plugins/canvas/public/state/reducers/pages.js index 50a28475ef5bc..afcca8f54b5aa 100644 --- a/x-pack/plugins/canvas/public/state/reducers/pages.js +++ b/x-pack/plugins/canvas/public/state/reducers/pages.js @@ -22,7 +22,7 @@ const setPageIndex = (workpadState, index) => : set(workpadState, 'page', index); function getPageIndexById(workpadState, id) { - return workpadState.pages.findIndex(page => page.id === id); + return workpadState.pages.findIndex((page) => page.id === id); } function addPage(workpadState, payload, srcIndex = workpadState.pages.length - 1) { @@ -39,8 +39,8 @@ function clonePage(page) { return { ...page, id: getId('page'), - groups: newNodes.filter(n => isGroupId(n.id)), - elements: newNodes.filter(n => !isGroupId(n.id)), + groups: newNodes.filter((n) => isGroupId(n.id)), + elements: newNodes.filter((n) => !isGroupId(n.id)), }; } @@ -59,7 +59,7 @@ export const pagesReducer = handleActions( }, [actions.duplicatePage]: (workpadState, { payload }) => { - const srcPage = workpadState.pages.find(page => page.id === payload); + const srcPage = workpadState.pages.find((page) => page.id === payload); // if the page id is invalid, don't change the state if (!srcPage) { @@ -103,7 +103,7 @@ export const pagesReducer = handleActions( // adjust the selected page index and return the new state const selectedId = workpadState.pages[workpadState.page].id; - const newSelectedIndex = newState.pages.findIndex(page => page.id === selectedId); + const newSelectedIndex = newState.pages.findIndex((page) => page.id === selectedId); newState = set(newState, 'page', newSelectedIndex); // changes to the page require navigation @@ -144,12 +144,12 @@ export const pagesReducer = handleActions( }, [actions.stylePage]: (workpadState, { payload }) => { - const pageIndex = workpadState.pages.findIndex(page => page.id === payload.pageId); + const pageIndex = workpadState.pages.findIndex((page) => page.id === payload.pageId); return set(workpadState, `pages.${pageIndex}.style`, payload.style); }, [actions.setPageTransition]: (workpadState, { payload }) => { - const pageIndex = workpadState.pages.findIndex(page => page.id === payload.pageId); + const pageIndex = workpadState.pages.findIndex((page) => page.id === payload.pageId); return set(workpadState, `pages.${pageIndex}.transition`, payload.transition); }, }, diff --git a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js index fa0be7702765d..0b020069aa8bc 100644 --- a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js @@ -102,11 +102,11 @@ export const resolvedArgsReducer = handleActions( }, transientState); }, - [actions.inFlightActive]: transientState => { + [actions.inFlightActive]: (transientState) => { return set(transientState, 'inFlight', true); }, - [actions.inFlightComplete]: transientState => { + [actions.inFlightComplete]: (transientState) => { return set(transientState, 'inFlight', false); }, diff --git a/x-pack/plugins/canvas/public/state/reducers/transient.js b/x-pack/plugins/canvas/public/state/reducers/transient.js index 0b89dfd3c9564..c6a4466eeb145 100644 --- a/x-pack/plugins/canvas/public/state/reducers/transient.js +++ b/x-pack/plugins/canvas/public/state/reducers/transient.js @@ -18,14 +18,14 @@ export const transientReducer = handleActions( { // clear all the resolved args when restoring the history // TODO: we shouldn't need to reset the resolved args for history - [restoreHistory]: transientState => set(transientState, 'resolvedArgs', {}), + [restoreHistory]: (transientState) => set(transientState, 'resolvedArgs', {}), [removeElements]: (transientState, { payload: { elementIds } }) => { const { selectedToplevelNodes } = transientState; return del( { ...transientState, - selectedToplevelNodes: selectedToplevelNodes.filter(n => elementIds.indexOf(n) < 0), + selectedToplevelNodes: selectedToplevelNodes.filter((n) => elementIds.indexOf(n) < 0), }, ['resolvedArgs', elementIds] ); @@ -57,15 +57,15 @@ export const transientReducer = handleActions( }; }, - [pageActions.setPage]: transientState => { + [pageActions.setPage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, - [pageActions.addPage]: transientState => { + [pageActions.addPage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, - [pageActions.duplicatePage]: transientState => { + [pageActions.duplicatePage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, diff --git a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js b/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js index cf22a2c81c35f..5fdc662c592cc 100644 --- a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js +++ b/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js @@ -175,7 +175,7 @@ describe('workpad selectors', () => { it('returns all elements on the page', () => { const { elements } = state.persistent.workpad.pages[0]; - const expected = elements.map(element => ({ + const expected = elements.map((element) => ({ ...element, ast: asts[element.id], })); diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index ae5c0fee52062..4b3431e59a34e 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -74,12 +74,12 @@ export function getPages(state: State): State['persistent']['workpad']['pages'] export function getPageById(state: State, id: string): CanvasPage | undefined { const pages = getPages(state); - return pages.find(page => page.id === id); + return pages.find((page) => page.id === id); } export function getPageIndexById(state: State, id: string): number { const pages = getPages(state); - return pages.findIndex(page => page.id === id); + return pages.findIndex((page) => page.id === id); } export function getWorkpadName(state: State): string { @@ -151,7 +151,7 @@ export function getElementCounts(state: State) { .filter( (maybeResolvedArg): maybeResolvedArg is ResolvedArgType => maybeResolvedArg !== undefined ) - .forEach(resolvedArg => { + .forEach((resolvedArg) => { const { expressionRenderable } = resolvedArg; if (!expressionRenderable) { @@ -224,7 +224,7 @@ function extractFilterGroups( if (fn === 'filters') { // we have a filter function, extract groups from args return groups.concat( - buildGroupValues(args, argValue => { + buildGroupValues(args, (argValue) => { // this only handles simple values if (argValue !== null && typeof argValue !== 'object') { return argValue; @@ -234,7 +234,7 @@ function extractFilterGroups( } else { // dig into other functions, looking for filters function return groups.concat( - buildGroupValues(args, argValue => { + buildGroupValues(args, (argValue) => { // recursively collect filter groups if (argValue !== null && typeof argValue === 'object' && argValue.type === 'expression') { return extractFilterGroups(argValue); @@ -268,7 +268,7 @@ export function getGlobalFilterGroups(state: State) { | ExpressionAstFunction | ExpressionAstExpression; const groups = extractFilterGroups(expressionAst); - groups.forEach(group => { + groups.forEach((group) => { if (!acc.includes(String(group))) { acc.push(String(group)); } @@ -318,7 +318,7 @@ export function getElements( // due to https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this once it's been in the wild a bit if (!withAst) { - return elements.map(el => omit(el, ['ast'])); + return elements.map((el) => omit(el, ['ast'])); } return elements.map(appendAst); @@ -354,7 +354,7 @@ export function getNodesForPage(page: CanvasPage, withAst: boolean): CanvasEleme // due to https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this once it's been in the wild a bit if (!withAst) { - return elements.map(el => omit(el, ['ast'])); + return elements.map((el) => omit(el, ['ast'])); } return elements.map(appendAst); @@ -384,7 +384,7 @@ export function getElementById( id: string | null, pageId?: string ): PositionedElement | undefined { - const element = getElements(state, pageId, true).find(el => el.id === id); + const element = getElements(state, pageId, true).find((el) => el.id === id); if (element) { return appendAst(element); } @@ -396,7 +396,7 @@ export function getNodeById( pageId: string ): PositionedElement | undefined { // do we need to pass a truthy empty array instead of `true`? - const group = getNodes(state, pageId, true).find(el => el.id === id); + const group = getNodes(state, pageId, true).find((el) => el.id === id); if (group) { return appendAst(group); } @@ -437,11 +437,11 @@ export function getAutoplay(state: State): State['transient']['autoplay'] { export function getRenderedWorkpad(state: State) { const currentPages = getPages(state); const args = state.transient.resolvedArgs; - const renderedPages = currentPages.map(page => { + const renderedPages = currentPages.map((page) => { const { elements, ...rest } = page; return { ...rest, - elements: elements.map(element => { + elements: elements.map((element) => { const { id, position } = element; const arg = args[id]; if (!arg) { @@ -470,8 +470,8 @@ export function getRenderedWorkpadExpressions(state: State) { const { pages } = workpad; const expressions: string[] = []; - pages.forEach(page => - page.elements.forEach(element => { + pages.forEach((page) => + page.elements.forEach((element) => { if (element && element.expressionRenderable) { const { value } = element.expressionRenderable; if (value) { diff --git a/x-pack/plugins/canvas/public/state/store.js b/x-pack/plugins/canvas/public/state/store.js index 891f30ca4114f..4995db0ae84a5 100644 --- a/x-pack/plugins/canvas/public/state/store.js +++ b/x-pack/plugins/canvas/public/state/store.js @@ -29,7 +29,7 @@ export function createStore(initialState) { export function destroyStore() { if (store) { // Replace reducer so that anything that gets fired after navigating away doesn't really do anything - store.replaceReducer(state => state); + store.replaceReducer((state) => state); } store = undefined; } diff --git a/x-pack/plugins/canvas/scripts/_helpers.js b/x-pack/plugins/canvas/scripts/_helpers.js index 0f4b07d988308..7f386edc49117 100644 --- a/x-pack/plugins/canvas/scripts/_helpers.js +++ b/x-pack/plugins/canvas/scripts/_helpers.js @@ -6,19 +6,19 @@ const { resolve } = require('path'); -exports.runGulpTask = function(name) { +exports.runGulpTask = function (name) { process.chdir(resolve(__dirname, '../../..')); process.argv.splice(1, 1, require.resolve('gulp/bin/gulp'), name); require('gulp/bin/gulp'); }; -exports.runKibanaScript = function(name, args = []) { +exports.runKibanaScript = function (name, args = []) { process.chdir(resolve(__dirname, '../../../..')); process.argv.splice(2, 0, ...args); require('../../../../scripts/' + name); // eslint-disable-line import/no-dynamic-require }; -exports.runXPackScript = function(name, args = []) { +exports.runXPackScript = function (name, args = []) { process.chdir(resolve(__dirname, '../../..')); process.argv.splice(2, 0, ...args); require('../../../scripts/' + name); // eslint-disable-line import/no-dynamic-require diff --git a/x-pack/plugins/canvas/server/collectors/collector.ts b/x-pack/plugins/canvas/server/collectors/collector.ts index 88e5e43dc2af1..e266e9826a47d 100644 --- a/x-pack/plugins/canvas/server/collectors/collector.ts +++ b/x-pack/plugins/canvas/server/collectors/collector.ts @@ -35,7 +35,7 @@ export function registerCanvasUsageCollector( isReady: () => true, fetch: async (callCluster: CallCluster) => { const collectorResults = await Promise.all( - collectors.map(collector => collector(kibanaIndex, callCluster)) + collectors.map((collector) => collector(kibanaIndex, callCluster)) ); return collectorResults.reduce( diff --git a/x-pack/plugins/canvas/server/collectors/collector_helpers.ts b/x-pack/plugins/canvas/server/collectors/collector_helpers.ts index 73de691dae05f..a6b04661f3da1 100644 --- a/x-pack/plugins/canvas/server/collectors/collector_helpers.ts +++ b/x-pack/plugins/canvas/server/collectors/collector_helpers.ts @@ -27,8 +27,8 @@ export function collectFns(ast: ExpressionAstNode, cb: (functionName: string) => cb(cFunction); // recurse the arguments and update the set along the way - Object.keys(cArguments).forEach(argName => { - cArguments[argName].forEach(subAst => { + Object.keys(cArguments).forEach((argName) => { + cArguments[argName].forEach((subAst) => { if (subAst != null) { collectFns(subAst, cb); } diff --git a/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts b/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts index f09bb704b09e3..ae65eb42bb20d 100644 --- a/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts +++ b/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts @@ -10,7 +10,7 @@ import { TelemetryCustomElementDocument } from '../../types'; function mockCustomElement(...nodeExpressions: string[]): TelemetryCustomElementDocument { return { content: JSON.stringify({ - selectedNodes: nodeExpressions.map(expression => ({ + selectedNodes: nodeExpressions.map((expression) => ({ expression, })), }), diff --git a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts index ae71600d24e4b..3ada8e7b4efdc 100644 --- a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts +++ b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts @@ -60,7 +60,7 @@ export function summarizeCustomElements( const functionSet = new Set(); const parsedContents: TelemetryCustomElement[] = customElements - .map(element => element.content) + .map((element) => element.content) .map(parseJsonOrNull) .filter(isCustomElement); @@ -76,8 +76,8 @@ export function summarizeCustomElements( let totalElements = 0; - parsedContents.map(contents => { - contents.selectedNodes.map(node => { + parsedContents.map((contents) => { + contents.selectedNodes.map((node) => { const ast = parseExpression(node.expression); collectFns(ast, (cFunction: string) => { functionSet.add(cFunction); @@ -114,7 +114,7 @@ const customElementCollector: TelemetryCollector = async function customElementC const esResponse = await callCluster('search', customElementParams); if (get(esResponse, 'hits.hits.length') > 0) { - const customElements = esResponse.hits.hits.map(hit => hit._source[CUSTOM_ELEMENT_TYPE]); + const customElements = esResponse.hits.hits.map((hit) => hit._source[CUSTOM_ELEMENT_TYPE]); return summarizeCustomElements(customElements); } diff --git a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts index b14a35ded4781..3d394afaeba50 100644 --- a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts +++ b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts @@ -59,7 +59,7 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr } // make a summary of info about each workpad - const workpadsInfo = workpadDocs.map(workpad => { + const workpadsInfo = workpadDocs.map((workpad) => { let pages = { count: 0 }; try { pages = { count: workpad.pages.length }; @@ -72,9 +72,9 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr [] ); const functionCounts = workpad.pages.reduce((accum, page) => { - return page.elements.map(element => { + return page.elements.map((element) => { const ast = parseExpression(element.expression); - collectFns(ast, cFunction => { + collectFns(ast, (cFunction) => { functionSet.add(cFunction); }); return ast.chain.length; // get the number of parts in the expression @@ -159,7 +159,7 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr }; } -const workpadCollector: TelemetryCollector = async function(kibanaIndex, callCluster) { +const workpadCollector: TelemetryCollector = async function (kibanaIndex, callCluster) { const searchParams: SearchParams = { size: 10000, // elasticsearch index.max_result_window default value index: kibanaIndex, @@ -171,7 +171,7 @@ const workpadCollector: TelemetryCollector = async function(kibanaIndex, callClu const esResponse = await callCluster('search', searchParams); if (get(esResponse, 'hits.hits.length') > 0) { - const workpads = esResponse.hits.hits.map(hit => hit._source[CANVAS_TYPE]); + const workpads = esResponse.hits.hits.map((hit) => hit._source[CANVAS_TYPE]); return summarizeWorkpads(workpads); } diff --git a/x-pack/plugins/canvas/server/lib/build_bool_array.js b/x-pack/plugins/canvas/server/lib/build_bool_array.js index 2dc6447753526..f1cab93ceebbb 100644 --- a/x-pack/plugins/canvas/server/lib/build_bool_array.js +++ b/x-pack/plugins/canvas/server/lib/build_bool_array.js @@ -6,11 +6,11 @@ import { getESFilter } from './get_es_filter'; -const compact = arr => (Array.isArray(arr) ? arr.filter(val => Boolean(val)) : []); +const compact = (arr) => (Array.isArray(arr) ? arr.filter((val) => Boolean(val)) : []); export function buildBoolArray(canvasQueryFilterArray) { return compact( - canvasQueryFilterArray.map(clause => { + canvasQueryFilterArray.map((clause) => { try { return getESFilter(clause); } catch (e) { diff --git a/x-pack/plugins/canvas/server/lib/format_response.js b/x-pack/plugins/canvas/server/lib/format_response.js index d52e2819465fe..a317ca8be56f8 100644 --- a/x-pack/plugins/canvas/server/lib/format_response.js +++ b/x-pack/plugins/canvas/server/lib/format_response.js @@ -5,7 +5,7 @@ */ import boom from 'boom'; -export const formatResponse = esErrors => resp => { +export const formatResponse = (esErrors) => (resp) => { if (resp.isBoom) { return resp; } // can't wrap it if it's already a boom error diff --git a/x-pack/plugins/canvas/server/lib/normalize_type.js b/x-pack/plugins/canvas/server/lib/normalize_type.js index 07f1cac0f7819..fda2fbe631646 100644 --- a/x-pack/plugins/canvas/server/lib/normalize_type.js +++ b/x-pack/plugins/canvas/server/lib/normalize_type.js @@ -24,7 +24,7 @@ export function normalizeType(type) { null: ['null'], }; - const normalizedType = Object.keys(normalTypes).find(t => normalTypes[t].includes(type)); + const normalizedType = Object.keys(normalTypes).find((t) => normalTypes[t].includes(type)); if (normalizedType) { return normalizedType; diff --git a/x-pack/plugins/canvas/server/lib/query_es_sql.js b/x-pack/plugins/canvas/server/lib/query_es_sql.js index f7907e2cffb26..442703b00ea3a 100644 --- a/x-pack/plugins/canvas/server/lib/query_es_sql.js +++ b/x-pack/plugins/canvas/server/lib/query_es_sql.js @@ -24,12 +24,12 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone }, }, }) - .then(res => { + .then((res) => { const columns = res.columns.map(({ name, type }) => { return { name: sanitizeName(name), type: normalizeType(type) }; }); const columnNames = map(columns, 'name'); - const rows = res.rows.map(row => zipObject(columnNames, row)); + const rows = res.rows.map((row) => zipObject(columnNames, row)); if (!!res.cursor) { elasticsearchClient('transport.request', { @@ -38,7 +38,7 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone body: { cursor: res.cursor, }, - }).catch(e => { + }).catch((e) => { throw new Error(`Unexpected error from Elasticsearch: ${e.message}`); }); } @@ -49,7 +49,7 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone rows, }; }) - .catch(e => { + .catch((e) => { if (e.message.indexOf('parsing_exception') > -1) { throw new Error( `Couldn't parse Elasticsearch SQL query. You may need to add double quotes to names containing special characters. Check your query and try again. Error: ${e.message}` diff --git a/x-pack/plugins/canvas/server/lib/sanitize_name.js b/x-pack/plugins/canvas/server/lib/sanitize_name.js index 623b64ca04ae8..295315c3ceb2e 100644 --- a/x-pack/plugins/canvas/server/lib/sanitize_name.js +++ b/x-pack/plugins/canvas/server/lib/sanitize_name.js @@ -7,7 +7,7 @@ export function sanitizeName(name) { // blacklisted characters const blacklist = ['(', ')']; - const pattern = blacklist.map(v => escapeRegExp(v)).join('|'); + const pattern = blacklist.map((v) => escapeRegExp(v)).join('|'); const regex = new RegExp(pattern, 'g'); return name.replace(regex, '_'); } diff --git a/x-pack/plugins/canvas/server/routes/catch_error_handler.ts b/x-pack/plugins/canvas/server/routes/catch_error_handler.ts index 4717d8762ffe2..6c684449be5ca 100644 --- a/x-pack/plugins/canvas/server/routes/catch_error_handler.ts +++ b/x-pack/plugins/canvas/server/routes/catch_error_handler.ts @@ -8,7 +8,7 @@ import { RequestHandler } from 'src/core/server'; export const catchErrorHandler: ( fn: RequestHandler -) => RequestHandler = fn => { +) => RequestHandler = (fn) => { return async (context, request, response) => { try { return await fn(context, request, response); diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts index 964618adf165d..bd5f226bda57c 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts @@ -50,7 +50,7 @@ export function initializeFindCustomElementsRoute(deps: RouteInitializerDeps) { return response.ok({ body: { total: customElements.total, - customElements: customElements.saved_objects.map(hit => ({ + customElements: customElements.saved_objects.map((hit) => ({ id: hit.id, ...hit.attributes, })), diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts index 5ebf20095bf3e..e13b19610213e 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts +++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts @@ -36,8 +36,8 @@ export function initializeESFieldsRoute(deps: RouteInitializerDeps) { fields: fields || '*', }; - const esFields = await callAsCurrentUser('fieldCaps', config).then(resp => { - return mapValues(resp.fields, types => { + const esFields = await callAsCurrentUser('fieldCaps', config).then((resp) => { + return mapValues(resp.fields, (types) => { if (keys(types).length > 1) { return 'conflict'; } diff --git a/x-pack/plugins/canvas/server/routes/workpad/find.ts b/x-pack/plugins/canvas/server/routes/workpad/find.ts index ec5c068a1fa24..b17d5d7d4bb39 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/find.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/find.ts @@ -41,7 +41,7 @@ export function initializeFindWorkpadsRoute(deps: RouteInitializerDeps) { return response.ok({ body: { total: workpads.total, - workpads: workpads.saved_objects.map(hit => ({ id: hit.id, ...hit.attributes })), + workpads: workpads.saved_objects.map((hit) => ({ id: hit.id, ...hit.attributes })), }, }); } catch (error) { diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.ts b/x-pack/plugins/canvas/server/routes/workpad/get.ts index 7dc1252063e90..e4c0d162782f0 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/get.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/get.ts @@ -34,7 +34,7 @@ export function initializeGetWorkpadRoute(deps: RouteInitializerDeps) { workpad.attributes.pages && workpad.attributes.pages.length ) { - workpad.attributes.pages.forEach(page => { + workpad.attributes.pages.forEach((page) => { const elements = (page.elements || []).filter( ({ id: pageId }) => !pageId.startsWith('group') ); diff --git a/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts b/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts index 6eda02ef41722..f58111000859a 100644 --- a/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts +++ b/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts @@ -19,7 +19,7 @@ export function loadSampleData( // @ts-ignore: Untyped local function updateCanvasWorkpadTimestamps(savedObjects) { // @ts-ignore: Untyped local - return savedObjects.map(savedObject => { + return savedObjects.map((savedObject) => { if (savedObject.type === 'canvas-workpad') { savedObject.attributes['@timestamp'] = nowTimestamp; savedObject.attributes['@created'] = nowTimestamp; diff --git a/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts b/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts index 893a73d7b5913..306224ce05bbf 100644 --- a/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts +++ b/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts @@ -6,7 +6,7 @@ import { SavedObjectMigrationFn } from 'src/core/server'; -export const removeAttributesId: SavedObjectMigrationFn = doc => { +export const removeAttributesId: SavedObjectMigrationFn = (doc) => { if (typeof doc.attributes === 'object' && doc.attributes !== null) { delete (doc.attributes as any).id; } diff --git a/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js b/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js index 051082107a2e6..6792568583617 100644 --- a/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js +++ b/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js @@ -27,12 +27,12 @@ const renderers = [ * Mock all of the render functions to return a `div` containing * a predictable string. */ -export const renderFunctions = renderers.map(fn => () => ({ +export const renderFunctions = renderers.map((fn) => () => ({ name: fn, displayName: fn, help: fn, reuseDomNode: true, - render: domNode => { + render: (domNode) => { ReactDOM.render(
{fn} mock
, domNode); }, })); diff --git a/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx b/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx index a55c87c2d74a2..d99c9b190f83d 100644 --- a/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx @@ -14,7 +14,7 @@ jest.mock('../../supported_renderers'); describe('Canvas Shareable Workpad API', () => { // Mock the AJAX load of the workpad. - beforeEach(function() { + beforeEach(function () { // @ts-ignore Applying a global in Jest is alright. global.fetch = jest.fn().mockImplementation(() => { const p = new Promise((resolve, _reject) => { diff --git a/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx b/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx index 11289d3c37970..96acee401d52d 100644 --- a/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx @@ -63,7 +63,7 @@ const VALID_ATTRIBUTES = ['url', 'page', 'height', 'width', 'autoplay', 'interva // Collect and then remove valid data attributes. const getAttributes = (element: Element, attributes: string[]) => { const result: { [key: string]: string } = {}; - attributes.forEach(attribute => { + attributes.forEach((attribute) => { const key = `${PREFIX}-${attribute}`; const value = element.getAttribute(key); @@ -150,7 +150,7 @@ const updateArea = async (area: Element) => { export const share = () => { const shareAreas = document.querySelectorAll(`[${SHAREABLE}]`); const validAreas = Array.from(shareAreas).filter( - area => area.getAttribute(SHAREABLE) === 'canvas' + (area) => area.getAttribute(SHAREABLE) === 'canvas' ); validAreas.forEach(updateArea); diff --git a/x-pack/plugins/canvas/shareable_runtime/components/app.tsx b/x-pack/plugins/canvas/shareable_runtime/components/app.tsx index 1779ec4846cb7..fdc64d32cf8e5 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/app.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/app.tsx @@ -29,7 +29,7 @@ interface Props { export const App: FC = ({ workpad, stage }) => { const renderers: { [key: string]: RendererSpec } = {}; - renderFunctions.forEach(fn => { + renderFunctions.forEach((fn) => { const func = fn(); renderers[func.name] = func; }); diff --git a/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx b/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx index 7d7067da09ee6..b1eb9af6fc4a1 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx @@ -66,8 +66,9 @@ export const CanvasComponent = ({ const { height: stageHeight, width: stageWidth, page } = stage; const { height: workpadHeight, width: workpadWidth } = workpad; const ratio = Math.max(workpadWidth / stageWidth, workpadHeight / stageHeight); - const transform = `scale3d(${stageHeight / (stageHeight * ratio)}, ${stageWidth / - (stageWidth * ratio)}, 1)`; + const transform = `scale3d(${stageHeight / (stageHeight * ratio)}, ${ + stageWidth / (stageWidth * ratio) + }, 1)`; const pageStyle = { height: workpadHeight, diff --git a/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx b/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx index 66515eb3421d5..34dacc7956253 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx @@ -77,9 +77,7 @@ describe('', () => { expect(takeMountedSnapshot(portal(wrapper))).toMatchSnapshot(); // Click the Hide Toolbar switch - portal(wrapper) - .find('button[data-test-subj="hideToolbarSwitch"]') - .simulate('click'); + portal(wrapper).find('button[data-test-subj="hideToolbarSwitch"]').simulate('click'); portal(wrapper).update(); diff --git a/x-pack/plugins/canvas/shareable_runtime/index.ts b/x-pack/plugins/canvas/shareable_runtime/index.ts index 8b29b23c4442f..11ada0a468cb2 100644 --- a/x-pack/plugins/canvas/shareable_runtime/index.ts +++ b/x-pack/plugins/canvas/shareable_runtime/index.ts @@ -15,7 +15,7 @@ const css = require.context( true, /\.\/plugins\/(?!canvas).*light\.css/ ); -css.keys().forEach(filename => { +css.keys().forEach((filename) => { css(filename); }); @@ -24,4 +24,4 @@ const uiStyles = require.context( false, /[\/\\](?!mixins|variables|_|\.|bootstrap_(light|dark))[^\/\\]+\.less/ ); -uiStyles.keys().forEach(key => uiStyles(key)); +uiStyles.keys().forEach((key) => uiStyles(key)); diff --git a/x-pack/plugins/canvas/shareable_runtime/postcss.config.js b/x-pack/plugins/canvas/shareable_runtime/postcss.config.js index 2e83c8b33e26e..10baaddfc9b05 100644 --- a/x-pack/plugins/canvas/shareable_runtime/postcss.config.js +++ b/x-pack/plugins/canvas/shareable_runtime/postcss.config.js @@ -12,7 +12,7 @@ module.exports = { plugins: [ prefixer({ prefix: '.kbnCanvas', - transform: function(prefix, selector, prefixedSelector) { + transform: function (prefix, selector, prefixedSelector) { if (selector === 'body' || selector === 'html') { return prefix; } else { diff --git a/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js b/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js index 526bf3c9d6fb9..6238aaf5c2fe4 100644 --- a/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js +++ b/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js @@ -43,4 +43,4 @@ export const renderFunctions = [ text, ]; -export const renderFunctionNames = renderFunctions.map(fn => fn.name); +export const renderFunctionNames = renderFunctions.map((fn) => fn.name); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/context.tsx b/x-pack/plugins/canvas/shareable_runtime/test/context.tsx index 9361655d4af6e..b9738359ba5b5 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/context.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/test/context.tsx @@ -59,7 +59,7 @@ export const Context = ({ }: Props) => { const renderers: { [key: string]: RendererSpec } = {}; - renderFunctions.forEach(rendererFn => { + renderFunctions.forEach((rendererFn) => { const renderer = rendererFn(); renderers[renderer.name] = renderer; }); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts b/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts index 1c5b78929aaa5..360b9fdce51a1 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts @@ -8,7 +8,7 @@ import { ReactWrapper } from 'enzyme'; import { getSettingsTrigger, getPortal, getContextMenuItems } from './selectors'; import { waitFor } from './utils'; -export const openSettings = async function(wrapper: ReactWrapper) { +export const openSettings = async function (wrapper: ReactWrapper) { getSettingsTrigger(wrapper).simulate('click'); try { @@ -16,19 +16,15 @@ export const openSettings = async function(wrapper: ReactWrapper) { await waitFor(() => { wrapper.update(); - return getPortal(wrapper) - .find('EuiPanel') - .exists(); + return getPortal(wrapper).find('EuiPanel').exists(); }); } catch (e) { throw new Error('Settings Panel did not open in given time'); } }; -export const selectMenuItem = async function(wrapper: ReactWrapper, menuItemIndex: number) { - getContextMenuItems(wrapper) - .at(menuItemIndex) - .simulate('click'); +export const selectMenuItem = async function (wrapper: ReactWrapper, menuItemIndex: number) { + getContextMenuItems(wrapper).at(menuItemIndex).simulate('click'); try { // When the menu item is clicked, wait for all of the context menus to be there diff --git a/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts b/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts index 852c4ec9aadac..8068ccbbab83a 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts @@ -19,22 +19,16 @@ export const getToolbarPanel = (wrapper: ReactWrapper) => wrapper.find('ToolbarSettings > ToolbarSettingsComponent'); export const getToolbarCheckbox = (wrapper: ReactWrapper) => - getToolbarPanel(wrapper) - .find('EuiSwitch') - .find('button'); + getToolbarPanel(wrapper).find('EuiSwitch').find('button'); export const getAutoplayPanel = (wrapper: ReactWrapper) => wrapper.find('AutoplaySettings > AutoplaySettingsComponent'); export const getAutoplayCheckbox = (wrapper: ReactWrapper) => - getAutoplayPanel(wrapper) - .find('EuiSwitch') - .find('button'); + getAutoplayPanel(wrapper).find('EuiSwitch').find('button'); export const getAutoplayTextField = (wrapper: ReactWrapper) => - getAutoplayPanel(wrapper) - .find('EuiFieldText') - .find('input[type="text"]'); + getAutoplayPanel(wrapper).find('EuiFieldText').find('input[type="text"]'); export const getAutoplaySubmit = (wrapper: ReactWrapper) => getAutoplayPanel(wrapper).find('EuiButton'); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/utils.ts b/x-pack/plugins/canvas/shareable_runtime/test/utils.ts index 4e18f2af1b06a..fe3c1be9ba154 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/utils.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/utils.ts @@ -8,7 +8,7 @@ import { ReactWrapper } from 'enzyme'; import { Component } from 'react'; export const tick = (ms = 0) => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, ms); }); diff --git a/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js b/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js index 3571448c11aa9..ca8d1c10d870f 100644 --- a/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js +++ b/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export const downloadWorkpad = async workpadId => console.log(`Download workpad ${workpadId}`); +export const downloadWorkpad = async (workpadId) => console.log(`Download workpad ${workpadId}`); -export const downloadRenderedWorkpad = async renderedWorkpad => +export const downloadRenderedWorkpad = async (renderedWorkpad) => console.log(`Download workpad ${renderedWorkpad.id}`); -export const downloadRuntime = async basePath => console.log(`Download run time at ${basePath}`); +export const downloadRuntime = async (basePath) => console.log(`Download run time at ${basePath}`); -export const downloadZippedRuntime = async data => console.log(`Downloading data ${data}`); +export const downloadZippedRuntime = async (data) => console.log(`Downloading data ${data}`); diff --git a/x-pack/plugins/canvas/tasks/mocks/uiNotify.js b/x-pack/plugins/canvas/tasks/mocks/uiNotify.js index ad313bc69da45..d29e66e8287eb 100644 --- a/x-pack/plugins/canvas/tasks/mocks/uiNotify.js +++ b/x-pack/plugins/canvas/tasks/mocks/uiNotify.js @@ -5,9 +5,9 @@ */ const notifierProto = { - error: msg => `error: ${msg}`, - warning: msg => `warning: ${msg}`, - info: msg => `info: ${msg}`, + error: (msg) => `error: ${msg}`, + warning: (msg) => `warning: ${msg}`, + info: (msg) => `info: ${msg}`, }; export class Notifier { diff --git a/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js b/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js index 480a750e0a9ce..4df51dd284933 100644 --- a/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js +++ b/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const formatMsg = str => str; +export const formatMsg = (str) => str; diff --git a/x-pack/plugins/case/common/api/saved_object.ts b/x-pack/plugins/case/common/api/saved_object.ts index fac8edd0ebea1..73fe767dd717e 100644 --- a/x-pack/plugins/case/common/api/saved_object.ts +++ b/x-pack/plugins/case/common/api/saved_object.ts @@ -12,7 +12,7 @@ export const NumberFromString = new rt.Type( 'NumberFromString', rt.number.is, (u, c) => - either.chain(rt.string.validate(u, c), s => { + either.chain(rt.string.validate(u, c), (s) => { const n = +s; return isNaN(n) ? rt.failure(u, c, 'cannot parse to a number') : rt.success(n); }), diff --git a/x-pack/plugins/case/server/plugin.ts b/x-pack/plugins/case/server/plugin.ts index 670e6ec797a9f..9cf045da3e700 100644 --- a/x-pack/plugins/case/server/plugin.ts +++ b/x-pack/plugins/case/server/plugin.ts @@ -21,7 +21,7 @@ import { import { CaseConfigureService, CaseService, CaseUserActionService } from './services'; function createConfig$(context: PluginInitializerContext) { - return context.config.create().pipe(map(config => config)); + return context.config.create().pipe(map((config) => config)); } export interface PluginsSetup { @@ -36,9 +36,7 @@ export class CasePlugin { } public async setup(core: CoreSetup, plugins: PluginsSetup) { - const config = await createConfig$(this.initializerContext) - .pipe(first()) - .toPromise(); + const config = await createConfig$(this.initializerContext).pipe(first()).toPromise(); if (!config.enabled) { return; diff --git a/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts b/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts index e83dafc68ee69..eade232593c8e 100644 --- a/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts +++ b/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts @@ -31,13 +31,13 @@ export const createMockSavedObjectsRepository = ({ return { saved_objects: objects.map(({ id, type }) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - const result = caseCommentSavedObject.filter(s => s.id === id); + const result = caseCommentSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result; } - const result = caseSavedObject.filter(s => s.id === id); + const result = caseSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } @@ -49,11 +49,11 @@ export const createMockSavedObjectsRepository = ({ return { saved_objects: objects.map(({ id, type, attributes }) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - if (!caseCommentSavedObject.find(s => s.id === id)) { + if (!caseCommentSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } else if (type === CASE_SAVED_OBJECT) { - if (!caseSavedObject.find(s => s.id === id)) { + if (!caseSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } @@ -70,20 +70,20 @@ export const createMockSavedObjectsRepository = ({ }), get: jest.fn((type, id) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - const result = caseCommentSavedObject.filter(s => s.id === id); + const result = caseCommentSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result[0]; } - const result = caseSavedObject.filter(s => s.id === id); + const result = caseSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result[0]; }), - find: jest.fn(findArgs => { + find: jest.fn((findArgs) => { if (findArgs.hasReference && findArgs.hasReference.id === 'bad-guy') { throw SavedObjectsErrorHelpers.createBadRequestError('Error thrown for testing'); } @@ -169,7 +169,7 @@ export const createMockSavedObjectsRepository = ({ }), update: jest.fn((type, id, attributes) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - if (!caseCommentSavedObject.find(s => s.id === id)) { + if (!caseCommentSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } caseCommentSavedObject = [ @@ -183,7 +183,7 @@ export const createMockSavedObjectsRepository = ({ }, ]; } else if (type === CASE_SAVED_OBJECT) { - if (!caseSavedObject.find(s => s.id === id)) { + if (!caseSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } @@ -207,14 +207,14 @@ export const createMockSavedObjectsRepository = ({ }; }), delete: jest.fn((type: string, id: string) => { - let result = caseSavedObject.filter(s => s.id === id); + let result = caseSavedObject.filter((s) => s.id === id); if (type === CASE_COMMENT_SAVED_OBJECT) { - result = caseCommentSavedObject.filter(s => s.id === id); + result = caseCommentSavedObject.filter((s) => s.id === id); } if (type === CASE_CONFIGURE_SAVED_OBJECT) { - result = caseConfigureSavedObject.filter(s => s.id === id); + result = caseConfigureSavedObject.filter((s) => s.id === id); } if (type === CASE_COMMENT_SAVED_OBJECT && id === 'bad-guy') { diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts b/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts index e9bcb9690ebd8..e06b3a33dfc72 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts @@ -32,7 +32,7 @@ export function initDeleteAllCommentsApi({ caseService, router, userActionServic caseId: request.params.case_id, }); await Promise.all( - comments.saved_objects.map(comment => + comments.saved_objects.map((comment) => caseService.deleteComment({ client, commentId: comment.id, @@ -42,7 +42,7 @@ export function initDeleteAllCommentsApi({ caseService, router, userActionServic await userActionService.postUserActions({ client, - actions: comments.saved_objects.map(comment => + actions: comments.saved_objects.map((comment) => buildCommentUserActionItem({ action: 'delete', actionAt: deleteDate, diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts b/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts index 72ef400415d0f..df08af025df03 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts @@ -39,7 +39,7 @@ export function initDeleteCommentApi({ caseService, router, userActionService }: throw Boom.notFound(`This comment ${request.params.comment_id} does not exist anymore.`); } - const caseRef = myComment.references.find(c => c.type === CASE_SAVED_OBJECT); + const caseRef = myComment.references.find((c) => c.type === CASE_SAVED_OBJECT); if (caseRef == null || (caseRef != null && caseRef.id !== request.params.case_id)) { throw Boom.notFound( `This comment ${request.params.comment_id} does not exist in ${request.params.case_id}).` diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts b/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts index b5a7d6367ea4b..24a03b217ab7c 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts @@ -41,7 +41,7 @@ describe('GET comment', () => { const response = await routeHandler(theContext, request, kibanaResponseFactory); expect(response.status).toEqual(200); - const myPayload = mockCaseComments.find(s => s.id === 'mock-comment-1'); + const myPayload = mockCaseComments.find((s) => s.id === 'mock-comment-1'); expect(myPayload).not.toBeUndefined(); if (myPayload != null) { expect(response.payload).toEqual(flattenCommentSavedObject(myPayload)); diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts b/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts index 90661a7d3897d..1aca27bbf1853 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts @@ -57,7 +57,7 @@ export function initPatchCommentApi({ throw Boom.notFound(`This comment ${query.id} does not exist anymore.`); } - const caseRef = myComment.references.find(c => c.type === CASE_SAVED_OBJECT); + const caseRef = myComment.references.find((c) => c.type === CASE_SAVED_OBJECT); if (caseRef == null || (caseRef != null && caseRef.id !== caseId)) { throw Boom.notFound(`This comment ${query.id} does not exist in ${caseId}).`); } diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts index 09692ff73b94b..d7a01ef069867 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts @@ -39,7 +39,7 @@ describe('GET connectors', () => { const res = await routeHandler(context, req, kibanaResponseFactory); expect(res.status).toEqual(200); expect(res.payload).toEqual( - getActions().filter(action => action.actionTypeId === '.servicenow') + getActions().filter((action) => action.actionTypeId === '.servicenow') ); }); diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts index 43167d56de015..d86e1777e920d 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts @@ -31,7 +31,7 @@ export function initCaseConfigureGetActionConnector({ caseService, router }: Rou throw Boom.notFound('Action client have not been found'); } - const results = (await actionsClient.getAll()).filter(action => + const results = (await actionsClient.getAll()).filter((action) => SUPPORTED_CONNECTORS.includes(action.actionTypeId) ); return response.ok({ body: results }); diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts b/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts index 5c1693e728c37..a49a6c9ec5b76 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts @@ -38,7 +38,7 @@ export function initPostCaseConfigure({ caseConfigureService, caseService, route if (myCaseConfigure.saved_objects.length > 0) { await Promise.all( - myCaseConfigure.saved_objects.map(cc => + myCaseConfigure.saved_objects.map((cc) => caseConfigureService.delete({ client, caseConfigureId: cc.id }) ) ); diff --git a/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts b/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts index 20591637a6c23..9f57663c85f6f 100644 --- a/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts @@ -25,7 +25,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R try { const client = context.core.savedObjects.client; await Promise.all( - request.query.ids.map(id => + request.query.ids.map((id) => caseService.deleteCase({ client, caseId: id, @@ -33,7 +33,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R ) ); const comments = await Promise.all( - request.query.ids.map(id => + request.query.ids.map((id) => caseService.getAllCaseComments({ client, caseId: id, @@ -41,9 +41,9 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R ) ); - if (comments.some(c => c.saved_objects.length > 0)) { + if (comments.some((c) => c.saved_objects.length > 0)) { await Promise.all( - comments.map(c => + comments.map((c) => Promise.all( c.saved_objects.map(({ id }) => caseService.deleteComment({ @@ -60,7 +60,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R await userActionService.postUserActions({ client, - actions: request.query.ids.map(id => + actions: request.query.ids.map((id) => buildCaseUserActionItem({ action: 'create', actionAt: deleteDate, diff --git a/x-pack/plugins/case/server/routes/api/cases/find_cases.ts b/x-pack/plugins/case/server/routes/api/cases/find_cases.ts index cbe26ebe2f642..db57315388c5e 100644 --- a/x-pack/plugins/case/server/routes/api/cases/find_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/find_cases.ts @@ -19,7 +19,7 @@ import { CASES_URL } from '../../../../common/constants'; import { getConnectorId } from './helpers'; const combineFilters = (filters: string[], operator: 'OR' | 'AND'): string => - filters?.filter(i => i !== '').join(` ${operator} `); + filters?.filter((i) => i !== '').join(` ${operator} `); const getStatusFilter = (status: 'open' | 'closed', appendFilter?: string) => `${CASE_SAVED_OBJECT}.attributes.status: ${status}${ @@ -35,7 +35,7 @@ const buildFilter = ( ? Array.isArray(filters) ? // Be aware of the surrounding parenthesis (as string inside literal) around filters. `(${filters - .map(filter => `${CASE_SAVED_OBJECT}.attributes.${field}: ${filter}`) + .map((filter) => `${CASE_SAVED_OBJECT}.attributes.${field}: ${filter}`) ?.join(` ${operator} `)})` : `${CASE_SAVED_OBJECT}.attributes.${field}: ${filters}` : ''; @@ -102,7 +102,7 @@ export function initFindCasesApi({ caseService, caseConfigureService, router }: caseConfigureService.find({ client }), ]); const totalCommentsFindByCases = await Promise.all( - cases.saved_objects.map(c => + cases.saved_objects.map((c) => caseService.getAllCaseComments({ client, caseId: c.id, @@ -119,8 +119,8 @@ export function initFindCasesApi({ caseService, caseConfigureService, router }: (acc, itemFind) => { if (itemFind.saved_objects.length > 0) { const caseId = - itemFind.saved_objects[0].references.find(r => r.type === CASE_SAVED_OBJECT)?.id ?? - null; + itemFind.saved_objects[0].references.find((r) => r.type === CASE_SAVED_OBJECT) + ?.id ?? null; if (caseId != null) { return [...acc, { caseId, totalComments: itemFind.total }]; } diff --git a/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts b/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts index 6c0b5bdff418d..ed291c2cbf726 100644 --- a/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts @@ -45,7 +45,7 @@ describe('GET case', () => { ); const response = await routeHandler(theContext, request, kibanaResponseFactory); - const savedObject = (mockCases.find(s => s.id === 'mock-id-1') as unknown) as SavedObject< + const savedObject = (mockCases.find((s) => s.id === 'mock-id-1') as unknown) as SavedObject< CaseAttributes >; expect(response.status).toEqual(200); diff --git a/x-pack/plugins/case/server/routes/api/cases/helpers.ts b/x-pack/plugins/case/server/routes/api/cases/helpers.ts index b02bc0b4e10a2..78b108b00d4a7 100644 --- a/x-pack/plugins/case/server/routes/api/cases/helpers.ts +++ b/x-pack/plugins/case/server/routes/api/cases/helpers.ts @@ -24,12 +24,12 @@ export const compareArrays = ({ addedItems: [], deletedItems: [], }; - originalValue.forEach(origVal => { + originalValue.forEach((origVal) => { if (!updatedValue.includes(origVal)) { result.deletedItems = [...result.deletedItems, origVal]; } }); - updatedValue.forEach(updatedVal => { + updatedValue.forEach((updatedVal) => { if (!originalValue.includes(updatedVal)) { result.addedItems = [...result.addedItems, updatedVal]; } diff --git a/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts b/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts index 6d2a5f943cea9..0c722cf56ada3 100644 --- a/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts @@ -46,15 +46,15 @@ export function initPatchCasesApi({ const [myCases, myCaseConfigure] = await Promise.all([ caseService.getCases({ client, - caseIds: query.cases.map(q => q.id), + caseIds: query.cases.map((q) => q.id), }), caseConfigureService.find({ client }), ]); const caseConfigureConnectorId = getConnectorId(myCaseConfigure); let nonExistingCases: CasePatchRequest[] = []; - const conflictedCases = query.cases.filter(q => { - const myCase = myCases.saved_objects.find(c => c.id === q.id); + const conflictedCases = query.cases.filter((q) => { + const myCase = myCases.saved_objects.find((c) => c.id === q.id); if (myCase && myCase.error) { nonExistingCases = [...nonExistingCases, q]; @@ -65,24 +65,24 @@ export function initPatchCasesApi({ if (nonExistingCases.length > 0) { throw Boom.notFound( `These cases ${nonExistingCases - .map(c => c.id) + .map((c) => c.id) .join(', ')} do not exist. Please check you have the correct ids.` ); } if (conflictedCases.length > 0) { throw Boom.conflict( `These cases ${conflictedCases - .map(c => c.id) + .map((c) => c.id) .join(', ')} has been updated. Please refresh before saving additional updates.` ); } - const updateCases: CasePatchRequest[] = query.cases.map(thisCase => { - const currentCase = myCases.saved_objects.find(c => c.id === thisCase.id); + const updateCases: CasePatchRequest[] = query.cases.map((thisCase) => { + const currentCase = myCases.saved_objects.find((c) => c.id === thisCase.id); return currentCase != null ? getCaseToUpdate(currentCase.attributes, thisCase) : { id: thisCase.id, version: thisCase.version }; }); - const updateFilterCases = updateCases.filter(updateCase => { + const updateFilterCases = updateCases.filter((updateCase) => { const { id, version, ...updateCaseAttributes } = updateCase; return Object.keys(updateCaseAttributes).length > 0; }); @@ -91,7 +91,7 @@ export function initPatchCasesApi({ const updatedDt = new Date().toISOString(); const updatedCases = await caseService.patchCases({ client, - cases: updateFilterCases.map(thisCase => { + cases: updateFilterCases.map((thisCase) => { const { id: caseId, version, ...updateCaseAttributes } = thisCase; let closedInfo = {}; if (updateCaseAttributes.status && updateCaseAttributes.status === 'closed') { @@ -119,11 +119,11 @@ export function initPatchCasesApi({ }); const returnUpdatedCase = myCases.saved_objects - .filter(myCase => - updatedCases.saved_objects.some(updatedCase => updatedCase.id === myCase.id) + .filter((myCase) => + updatedCases.saved_objects.some((updatedCase) => updatedCase.id === myCase.id) ) - .map(myCase => { - const updatedCase = updatedCases.saved_objects.find(c => c.id === myCase.id); + .map((myCase) => { + const updatedCase = updatedCases.saved_objects.find((c) => c.id === myCase.id); return flattenCaseSavedObject({ savedObject: { ...myCase, diff --git a/x-pack/plugins/case/server/routes/api/cases/push_case.ts b/x-pack/plugins/case/server/routes/api/cases/push_case.ts index 871e78495c5dd..3379bbd318d5b 100644 --- a/x-pack/plugins/case/server/routes/api/cases/push_case.ts +++ b/x-pack/plugins/case/server/routes/api/cases/push_case.ts @@ -100,7 +100,7 @@ export function initPushCaseUserActionApi({ connector_id: myCase.attributes.connector_id ?? caseConfigureConnectorId, }; - if (!connectors.some(connector => connector.id === updateConnectorId.connector_id)) { + if (!connectors.some((connector) => connector.id === updateConnectorId.connector_id)) { throw Boom.notFound('Connector not found or set to none'); } @@ -127,8 +127,8 @@ export function initPushCaseUserActionApi({ caseService.patchComments({ client, comments: comments.saved_objects - .filter(comment => comment.attributes.pushed_at == null) - .map(comment => ({ + .filter((comment) => comment.attributes.pushed_at == null) + .map((comment) => ({ commentId: comment.id, updatedAttributes: { pushed_at: pushedDate, @@ -174,9 +174,9 @@ export function initPushCaseUserActionApi({ attributes: { ...myCase.attributes, ...updatedCase?.attributes }, references: myCase.references, }, - comments: comments.saved_objects.map(origComment => { + comments: comments.saved_objects.map((origComment) => { const updatedComment = updatedComments.saved_objects.find( - c => c.id === origComment.id + (c) => c.id === origComment.id ); return { ...origComment, diff --git a/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts b/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts index c90979f60d23f..eb51582900252 100644 --- a/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts +++ b/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts @@ -31,11 +31,12 @@ export function initGetAllUserActionsApi({ userActionService, router }: RouteDep }); return response.ok({ body: CaseUserActionsResponseRt.encode( - userActions.saved_objects.map(ua => ({ + userActions.saved_objects.map((ua) => ({ ...ua.attributes, action_id: ua.id, - case_id: ua.references.find(r => r.type === CASE_SAVED_OBJECT)?.id ?? '', - comment_id: ua.references.find(r => r.type === CASE_COMMENT_SAVED_OBJECT)?.id ?? null, + case_id: ua.references.find((r) => r.type === CASE_SAVED_OBJECT)?.id ?? '', + comment_id: + ua.references.find((r) => r.type === CASE_COMMENT_SAVED_OBJECT)?.id ?? null, })) ), }); diff --git a/x-pack/plugins/case/server/routes/api/utils.ts b/x-pack/plugins/case/server/routes/api/utils.ts index b65205734d569..fb199442f9425 100644 --- a/x-pack/plugins/case/server/routes/api/utils.ts +++ b/x-pack/plugins/case/server/routes/api/utils.ts @@ -111,7 +111,7 @@ export const flattenCaseSavedObjects = ( flattenCaseSavedObject({ savedObject, totalComment: - totalCommentByCase.find(tc => tc.caseId === savedObject.id)?.totalComments ?? 0, + totalCommentByCase.find((tc) => tc.caseId === savedObject.id)?.totalComments ?? 0, caseConfigureConnectorId, }), ]; diff --git a/x-pack/plugins/case/server/services/index.ts b/x-pack/plugins/case/server/services/index.ts index cdc5fd21a8138..2ca3e4e9ec223 100644 --- a/x-pack/plugins/case/server/services/index.ts +++ b/x-pack/plugins/case/server/services/index.ts @@ -150,7 +150,7 @@ export class CaseService { try { this.log.debug(`Attempting to GET cases ${caseIds.join(', ')}`); return await client.bulkGet( - caseIds.map(caseId => ({ type: CASE_SAVED_OBJECT, id: caseId })) + caseIds.map((caseId) => ({ type: CASE_SAVED_OBJECT, id: caseId })) ); } catch (error) { this.log.debug(`Error on GET cases ${caseIds.join(', ')}: ${error}`); @@ -264,9 +264,9 @@ export class CaseService { }, patchCases: async ({ client, cases }: PatchCasesArgs) => { try { - this.log.debug(`Attempting to UPDATE case ${cases.map(c => c.caseId).join(', ')}`); + this.log.debug(`Attempting to UPDATE case ${cases.map((c) => c.caseId).join(', ')}`); return await client.bulkUpdate( - cases.map(c => ({ + cases.map((c) => ({ type: CASE_SAVED_OBJECT, id: c.caseId, attributes: c.updatedAttributes, @@ -274,7 +274,7 @@ export class CaseService { })) ); } catch (error) { - this.log.debug(`Error on UPDATE case ${cases.map(c => c.caseId).join(', ')}: ${error}`); + this.log.debug(`Error on UPDATE case ${cases.map((c) => c.caseId).join(', ')}: ${error}`); throw error; } }, @@ -297,10 +297,10 @@ export class CaseService { patchComments: async ({ client, comments }: PatchComments) => { try { this.log.debug( - `Attempting to UPDATE comments ${comments.map(c => c.commentId).join(', ')}` + `Attempting to UPDATE comments ${comments.map((c) => c.commentId).join(', ')}` ); return await client.bulkUpdate( - comments.map(c => ({ + comments.map((c) => ({ type: CASE_COMMENT_SAVED_OBJECT, id: c.commentId, attributes: c.updatedAttributes, @@ -309,7 +309,7 @@ export class CaseService { ); } catch (error) { this.log.debug( - `Error on UPDATE comments ${comments.map(c => c.commentId).join(', ')}: ${error}` + `Error on UPDATE comments ${comments.map((c) => c.commentId).join(', ')}: ${error}` ); throw error; } diff --git a/x-pack/plugins/case/server/services/reporters/read_reporters.ts b/x-pack/plugins/case/server/services/reporters/read_reporters.ts index 4af5b41fc4dd4..2d09dbf7b9890 100644 --- a/x-pack/plugins/case/server/services/reporters/read_reporters.ts +++ b/x-pack/plugins/case/server/services/reporters/read_reporters.ts @@ -16,7 +16,7 @@ export const convertToReporters = (caseObjects: Array item.username === caseObj.attributes.created_by.username) + !accum.some((item) => item.username === caseObj.attributes.created_by.username) ) { return [...accum, caseObj.attributes.created_by]; } else { diff --git a/x-pack/plugins/case/server/services/user_actions/helpers.ts b/x-pack/plugins/case/server/services/user_actions/helpers.ts index af50b3b394325..228b42b4c638f 100644 --- a/x-pack/plugins/case/server/services/user_actions/helpers.ts +++ b/x-pack/plugins/case/server/services/user_actions/helpers.ts @@ -138,11 +138,11 @@ export const buildCaseUserActions = ({ updatedCases: Array>; }): UserActionItem[] => updatedCases.reduce((acc, updatedItem) => { - const originalItem = originalCases.find(oItem => oItem.id === updatedItem.id); + const originalItem = originalCases.find((oItem) => oItem.id === updatedItem.id); if (originalItem != null) { let userActions: UserActionItem[] = []; const updatedFields = Object.keys(updatedItem.attributes) as UserActionField; - updatedFields.forEach(field => { + updatedFields.forEach((field) => { if (userActionFieldsAllowed.includes(field)) { const origValue = get(originalItem, ['attributes', field]); const updatedValue = get(updatedItem, ['attributes', field]); diff --git a/x-pack/plugins/case/server/services/user_actions/index.ts b/x-pack/plugins/case/server/services/user_actions/index.ts index 0e9babf9d81af..476a151498c34 100644 --- a/x-pack/plugins/case/server/services/user_actions/index.ts +++ b/x-pack/plugins/case/server/services/user_actions/index.ts @@ -66,7 +66,7 @@ export class CaseUserActionService { try { this.log.debug(`Attempting to POST a new case user action`); return await client.bulkCreate( - actions.map(action => ({ type: CASE_USER_ACTION_SAVED_OBJECT, ...action })) + actions.map((action) => ({ type: CASE_USER_ACTION_SAVED_OBJECT, ...action })) ); } catch (error) { this.log.debug(`Error on POST a new case user action: ${error}`); diff --git a/x-pack/plugins/console_extensions/server/plugin.ts b/x-pack/plugins/console_extensions/server/plugin.ts index 2a08c258f4bbd..8e95d618b30ab 100644 --- a/x-pack/plugins/console_extensions/server/plugin.ts +++ b/x-pack/plugins/console_extensions/server/plugin.ts @@ -32,7 +32,7 @@ export class ConsoleExtensionsServerPlugin implements Plugin addProcessorDefinition(processor)); + processors.forEach((processor) => addProcessorDefinition(processor)); this.log.debug('Added processor definition extensions.'); } } diff --git a/x-pack/plugins/cross_cluster_replication/common/services/utils.ts b/x-pack/plugins/cross_cluster_replication/common/services/utils.ts index dda6732254cc3..7171c50e52f88 100644 --- a/x-pack/plugins/cross_cluster_replication/common/services/utils.ts +++ b/x-pack/plugins/cross_cluster_replication/common/services/utils.ts @@ -11,7 +11,7 @@ export const arrify = (val: any): any[] => (Array.isArray(val) ? val : [val]); * @param {number} time Time in millisecond to wait */ export const wait = (time = 1000) => (data: any): Promise => { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => resolve(data), time); }); }; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js index db1430d157183..728a9921ea903 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js @@ -195,7 +195,7 @@ describe('Create Auto-follow pattern', () => { }); test('should not allow invalid characters', () => { - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setComboBoxValue('indexPatternInput', `with${char}space`); expect(form.getErrorsMessages()).toContain( `Remove the character ${char} from the index pattern.` diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js index 0a7eaf647b020..0da241c4c1357 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js @@ -274,11 +274,7 @@ describe('', () => { test('should have a "settings" section', () => { actions.clickAutoFollowPatternAt(0); - expect( - find('settingsSection') - .find('h3') - .text() - ).toEqual('Settings'); + expect(find('settingsSection').find('h3').text()).toEqual('Settings'); expect(exists('settingsValues')).toBe(true); }); @@ -369,7 +365,7 @@ describe('', () => { expect(exists('autoFollowPatternDetail.errors')).toBe(true); expect(exists('autoFollowPatternDetail.titleErrors')).toBe(true); - expect(find('autoFollowPatternDetail.recentError').map(error => error.text())).toEqual([ + expect(find('autoFollowPatternDetail.recentError').map((error) => error.text())).toEqual([ 'April 16th, 2020 8:00:00 PM: bar', ]); }); diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js index 4c99339e16952..f5305f43e7f8c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js @@ -120,7 +120,7 @@ describe('Create Follower index', () => { test('should not allow invalid characters', () => { actions.clickSaveForm(); // Make all errors visible - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setInputValue('leaderIndexInput', `with${char}`); expect(form.getErrorsMessages()).toContain( `Remove the characters ${char} from your leader index.` @@ -149,7 +149,7 @@ describe('Create Follower index', () => { test('should not allow invalid characters', () => { actions.clickSaveForm(); // Make all errors visible - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setInputValue('followerIndexInput', `with${char}`); expect(form.getErrorsMessages()).toContain( `Remove the characters ${char} from your name.` @@ -235,7 +235,7 @@ describe('Create Follower index', () => { }; test('should have a toggle to activate advanced settings', () => { - const expectDoesNotExist = testSubject => { + const expectDoesNotExist = (testSubject) => { try { expect(exists(testSubject)).toBe(false); } catch { @@ -243,7 +243,7 @@ describe('Create Follower index', () => { } }; - const expectDoesExist = testSubject => { + const expectDoesExist = (testSubject) => { try { expect(exists(testSubject)).toBe(true); } catch { diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js index ad9f2db2ce91c..e96beda7243d6 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js @@ -190,7 +190,7 @@ describe('', () => { expect(contextMenu.length).toBe(1); const contextMenuButtons = contextMenu.find('button'); - const buttonsLabel = contextMenuButtons.map(btn => btn.text()); + const buttonsLabel = contextMenuButtons.map((btn) => btn.text()); expect(buttonsLabel).toEqual([ 'Pause replication', @@ -206,7 +206,7 @@ describe('', () => { const contextMenu = find('contextMenu'); const contextMenuButtons = contextMenu.find('button'); - const buttonsLabel = contextMenuButtons.map(btn => btn.text()); + const buttonsLabel = contextMenuButtons.map((btn) => btn.text()); expect(buttonsLabel).toEqual([ 'Resume replication', 'Edit follower index', @@ -250,7 +250,7 @@ describe('', () => { const buttonLabels = component .find('.euiContextMenuPanel') .find('.euiContextMenuItem') - .map(button => button.text()); + .map((button) => button.text()); expect(buttonLabels).toEqual([ 'Pause replication', @@ -266,7 +266,7 @@ describe('', () => { const buttonLabels = component .find('.euiContextMenuPanel') .find('.euiContextMenuItem') - .map(button => button.text()); + .map((button) => button.text()); expect(buttonLabels).toEqual([ 'Resume replication', @@ -326,11 +326,7 @@ describe('', () => { test('should have a "settings" section', () => { actions.clickFollowerIndexAt(0); - expect( - find('followerIndexDetail.settingsSection') - .find('h3') - .text() - ).toEqual('Settings'); + expect(find('followerIndexDetail.settingsSection').find('h3').text()).toEqual('Settings'); expect(exists('followerIndexDetail.settingsValues')).toBe(true); }); diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js index 1cb4e7c7725df..e240b5b304c33 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(AutoFollowPatternAdd, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js index 9cad61893c409..c32f6a54114c7 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js @@ -14,7 +14,7 @@ import { AUTO_FOLLOW_PATTERN_EDIT_NAME } from './constants'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), // The auto-follow pattern id to fetch is read from the router ":id" param // so we first set it in our initial entries initialEntries: [`/${AUTO_FOLLOW_PATTERN_EDIT_NAME}`], @@ -25,7 +25,7 @@ const testBedConfig = { const initTestBed = registerTestBed(AutoFollowPatternEdit, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js index 2c2ab642e83c8..87cf6a13ba011 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(AutoFollowPatternList, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); const EUI_TABLE = 'autoFollowPatternListTable'; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js index 856b09f3f3cba..9778b595111a2 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(FollowerIndexAdd, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js index 893d01f151bc2..993cde86ada22 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js @@ -14,7 +14,7 @@ import { FOLLOWER_INDEX_EDIT_NAME } from './constants'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), // The follower index id to fetch is read from the router ":id" param // so we first set it in our initial entries initialEntries: [`/${FOLLOWER_INDEX_EDIT_NAME}`], @@ -25,7 +25,7 @@ const testBedConfig = { const initTestBed = registerTestBed(FollowerIndexEdit, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js index 5e9f7d1263cf7..16a4fa9cd3f3e 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(FollowerIndicesList, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); const EUI_TABLE = 'followerIndexListTable'; @@ -39,10 +39,7 @@ export const setup = props => { const clickContextMenuButtonAt = (index = 0) => { const contextMenu = testBed.find('contextMenu'); - contextMenu - .find('button') - .at(index) - .simulate('click'); + contextMenu.find('button').at(index).simulate('click'); }; const openTableRowContextMenuAt = (index = 0) => { diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js index 56dfa765bfa4f..26a0d86cdcbca 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js @@ -15,7 +15,7 @@ const testBedConfig = { memoryRouter: { initialEntries: [`${BASE_PATH}/follower_indices`], componentRoutePath: `${BASE_PATH}/:section`, - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js index e2bd54a92a1f1..e37ec0d40ee5b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js @@ -7,14 +7,14 @@ import sinon from 'sinon'; // Register helpers to mock HTTP Requests -const registerHttpRequestMockHelpers = server => { +const registerHttpRequestMockHelpers = (server) => { const mockResponse = (defaultResponse, response) => [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({ ...defaultResponse, ...response }), ]; - const setLoadFollowerIndicesResponse = response => { + const setLoadFollowerIndicesResponse = (response) => { const defaultResponse = { indices: [] }; server.respondWith( @@ -24,7 +24,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setLoadAutoFollowPatternsResponse = response => { + const setLoadAutoFollowPatternsResponse = (response) => { const defaultResponse = { patterns: [] }; server.respondWith( @@ -34,7 +34,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setDeleteAutoFollowPatternResponse = response => { + const setDeleteAutoFollowPatternResponse = (response) => { const defaultResponse = { errors: [], itemsDeleted: [] }; server.respondWith( @@ -44,7 +44,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setAutoFollowStatsResponse = response => { + const setAutoFollowStatsResponse = (response) => { const defaultResponse = { numberOfFailedFollowIndices: 0, numberOfFailedRemoteClusterStateRequests: 0, @@ -82,7 +82,7 @@ const registerHttpRequestMockHelpers = server => { } }; - const setGetAutoFollowPatternResponse = response => { + const setGetAutoFollowPatternResponse = (response) => { const defaultResponse = {}; server.respondWith( @@ -100,7 +100,7 @@ const registerHttpRequestMockHelpers = server => { ]); }; - const setGetFollowerIndexResponse = response => { + const setGetFollowerIndexResponse = (response) => { const defaultResponse = {}; server.respondWith( diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts index 016e259343285..5460b482cd579 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts @@ -8,6 +8,6 @@ jest.mock('../../../app/services/track_ui_metric', () => ({ ...jest.requireActual('../../../app/services/track_ui_metric'), trackUiMetric: jest.fn(), trackUserRequest: (request: Promise) => { - return request.then(response => response); + return request.then((response) => response); }, })); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js index f9c03165dcf97..4ed4bc45c7b19 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js @@ -19,13 +19,13 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - deleteAutoFollowPattern = id => { + deleteAutoFollowPattern = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -91,7 +91,7 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { />

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -115,8 +115,8 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - deleteAutoFollowPattern: id => dispatch(deleteAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + deleteAutoFollowPattern: (id) => dispatch(deleteAutoFollowPattern(id)), }); export const AutoFollowPatternDeleteProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js index c817637ae1854..7874f6ac649eb 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js @@ -107,7 +107,7 @@ export class AutoFollowPatternForm extends PureComponent { })); }; - onFieldsChange = fields => { + onFieldsChange = (fields) => { this.setState(({ autoFollowPattern }) => ({ autoFollowPattern: { ...autoFollowPattern, @@ -119,14 +119,14 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsErrorChange(errors); }; - onFieldsErrorChange = errors => + onFieldsErrorChange = (errors) => this.setState(({ fieldsErrors }) => updateFormErrors(errors, fieldsErrors)); - onClusterChange = remoteCluster => { + onClusterChange = (remoteCluster) => { this.onFieldsChange({ remoteCluster }); }; - onCreateLeaderIndexPattern = indexPattern => { + onCreateLeaderIndexPattern = (indexPattern) => { const error = validateLeaderIndexPattern(indexPattern); if (error) { @@ -152,13 +152,13 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ leaderIndexPatterns: newLeaderIndexPatterns }); }; - onLeaderIndexPatternChange = indexPatterns => { + onLeaderIndexPatternChange = (indexPatterns) => { this.onFieldsChange({ leaderIndexPatterns: indexPatterns.map(({ label }) => label), }); }; - onLeaderIndexPatternInputChange = leaderIndexPattern => { + onLeaderIndexPatternInputChange = (leaderIndexPattern) => { const isEmpty = !leaderIndexPattern || !leaderIndexPattern.trim(); const { autoFollowPattern: { leaderIndexPatterns }, @@ -205,7 +205,7 @@ export class AutoFollowPatternForm extends PureComponent { isFormValid() { return Object.values(this.state.fieldsErrors).every( - error => error === undefined || error === null + (error) => error === undefined || error === null ); } @@ -306,7 +306,7 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ name: e.target.value })} + onChange={(e) => this.onFieldsChange({ name: e.target.value })} fullWidth disabled={!isNew} data-test-subj="nameInput" @@ -329,7 +329,7 @@ export class AutoFollowPatternForm extends PureComponent { defaultMessage="Auto-follow patterns capture indices on remote clusters." /> ), - remoteClusterNotConnectedNotEditable: name => ({ + remoteClusterNotConnectedNotEditable: (name) => ({ title: ( ), }), - remoteClusterDoesNotExist: name => ( + remoteClusterDoesNotExist: (name) => ( @@ -547,7 +551,9 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ followIndexPatternSuffix: e.target.value })} + onChange={(e) => + this.onFieldsChange({ followIndexPatternSuffix: e.target.value }) + } fullWidth data-test-subj="suffixInput" /> diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js index 81c7ca396c511..d423dd0b1f58d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js @@ -309,7 +309,7 @@ export const emptyAdvancedSettings = advancedSettingsFields.reduce((obj, advance }, {}); export function areAdvancedSettingsEdited(followerIndex) { - return advancedSettingsFields.some(advancedSetting => { + return advancedSettingsFields.some((advancedSetting) => { const { field } = advancedSetting; return followerIndex[field] !== emptyAdvancedSettings[field]; }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js index d824efd56cef1..28673c55fd031 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js @@ -71,7 +71,7 @@ const getEmptyFollowerIndex = (remoteClusterName = '') => ({ /** * State transitions: fields update */ -export const updateFields = fields => ({ followerIndex }) => ({ +export const updateFields = (fields) => ({ followerIndex }) => ({ followerIndex: { ...followerIndex, ...fields, @@ -81,7 +81,7 @@ export const updateFields = fields => ({ followerIndex }) => ({ /** * State transitions: errors update */ -export const updateFormErrors = errors => ({ fieldsErrors }) => ({ +export const updateFormErrors = (errors) => ({ fieldsErrors }) => ({ fieldsErrors: { ...fieldsErrors, ...errors, @@ -147,7 +147,7 @@ export class FollowerIndexForm extends PureComponent { })); }; - onFieldsChange = fields => { + onFieldsChange = (fields) => { this.setState(updateFields(fields)); const newFields = { @@ -162,7 +162,7 @@ export class FollowerIndexForm extends PureComponent { } }; - getFieldsErrors = newFields => { + getFieldsErrors = (newFields) => { return Object.keys(newFields).reduce((errors, field) => { const validator = fieldToValidatorMap[field]; const value = newFields[field]; @@ -201,10 +201,10 @@ export class FollowerIndexForm extends PureComponent { this.validateIndexName(name); }; - validateIndexName = async name => { + validateIndexName = async (name) => { try { const indices = await loadIndices(); - const doesExist = indices.some(index => index.name === name); + const doesExist = indices.some((index) => index.name === name); if (doesExist) { const error = { message: ( @@ -252,7 +252,7 @@ export class FollowerIndexForm extends PureComponent { } }; - onClusterChange = remoteCluster => { + onClusterChange = (remoteCluster) => { this.onFieldsChange({ remoteCluster }); }; @@ -260,7 +260,7 @@ export class FollowerIndexForm extends PureComponent { return this.state.followerIndex; }; - toggleAdvancedSettings = event => { + toggleAdvancedSettings = (event) => { // If the user edits the advanced settings but then hides them, we need to make sure the // edited values don't get sent to the API when the user saves, but we *do* want to restore // these values to the form when the user re-opens the advanced settings. @@ -298,7 +298,7 @@ export class FollowerIndexForm extends PureComponent { isFormValid() { return Object.values(this.state.fieldsErrors).every( - error => error === undefined || error === null + (error) => error === undefined || error === null ); } @@ -440,7 +440,7 @@ export class FollowerIndexForm extends PureComponent { defaultMessage="Replication requires a leader index on a remote cluster." /> ), - remoteClusterNotConnectedNotEditable: name => ({ + remoteClusterNotConnectedNotEditable: (name) => ({ title: ( ), }), - remoteClusterDoesNotExist: name => ( + remoteClusterDoesNotExist: (name) => ( - {advancedSettingsFields.map(advancedSetting => { + {advancedSettingsFields.map((advancedSetting) => { const { field, testSubject, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js index 5965bfd8cc603..9c1e8255d069c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js @@ -25,18 +25,18 @@ class FollowerIndexPauseProviderUi extends PureComponent { indices: [], }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - pauseFollowerIndex = index => { + pauseFollowerIndex = (index) => { this.setState({ isModalOpen: true, indices: arrify(index) }); }; onConfirm = () => { - this.props.pauseFollowerIndex(this.state.indices.map(index => index.name)); + this.props.pauseFollowerIndex(this.state.indices.map((index) => index.name)); this.setState({ isModalOpen: false, indices: [] }); this.props.onConfirm && this.props.onConfirm(); }; @@ -65,7 +65,7 @@ class FollowerIndexPauseProviderUi extends PureComponent { values: { count: indices.length }, } ); - const hasCustomSettings = indices.some(index => !areAllSettingsDefault(index)); + const hasCustomSettings = indices.some((index) => !areAllSettingsDefault(index)); return ( @@ -118,7 +118,7 @@ class FollowerIndexPauseProviderUi extends PureComponent {

    - {indices.map(index => ( + {indices.map((index) => (
  • {index.name}
  • ))}
@@ -142,8 +142,8 @@ class FollowerIndexPauseProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - pauseFollowerIndex: id => dispatch(pauseFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + pauseFollowerIndex: (id) => dispatch(pauseFollowerIndex(id)), }); export const FollowerIndexPauseProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js index ed9bc015c87e2..6e4c019dab85c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js @@ -25,13 +25,13 @@ class FollowerIndexResumeProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - resumeFollowerIndex = id => { + resumeFollowerIndex = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -124,7 +124,7 @@ class FollowerIndexResumeProviderUi extends PureComponent {

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -148,8 +148,8 @@ class FollowerIndexResumeProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - resumeFollowerIndex: id => dispatch(resumeFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + resumeFollowerIndex: (id) => dispatch(resumeFollowerIndex(id)), }); export const FollowerIndexResumeProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js index f3b267a69b18c..68b6b970ad90b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js @@ -24,13 +24,13 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - unfollowLeaderIndex = id => { + unfollowLeaderIndex = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -110,7 +110,7 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { />

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -134,8 +134,8 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - unfollowLeaderIndex: id => dispatch(unfollowLeaderIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + unfollowLeaderIndex: (id) => dispatch(unfollowLeaderIndex(id)), }); export const FollowerIndexUnfollowProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js b/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js index afb0ae8a9c0c4..6c534db7fc7c5 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js @@ -19,7 +19,7 @@ import { /** * State transitions: fields update */ -export const updateFields = newValues => ({ fields }) => ({ +export const updateFields = (newValues) => ({ fields }) => ({ fields: { ...fields, ...newValues, @@ -44,7 +44,7 @@ export class FormEntryRow extends PureComponent { testSubj: PropTypes.string, }; - onFieldChange = value => { + onFieldChange = (value) => { const { field, onValueUpdate, type } = this.props; const isNumber = type === 'number'; @@ -57,7 +57,7 @@ export class FormEntryRow extends PureComponent { onValueUpdate({ [field]: valueParsed }); }; - renderField = isInvalid => { + renderField = (isInvalid) => { const { value, type, disabled, isLoading, testSubj } = this.props; switch (type) { case 'number': @@ -65,7 +65,7 @@ export class FormEntryRow extends PureComponent { this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled === true} isLoading={isLoading} fullWidth @@ -77,7 +77,7 @@ export class FormEntryRow extends PureComponent { this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled === true} isLoading={isLoading} fullWidth diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js index 00d29ffdca3a6..7b06af890ae09 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js @@ -28,7 +28,7 @@ const errorMessages = { defaultMessage="You need at least one remote cluster to create a follower index." /> ), - remoteClusterNotConnectedEditable: name => ({ + remoteClusterNotConnectedEditable: (name) => ({ title: ( c.name === clusterName); + const remoteCluster = remoteClusters.find((c) => c.name === clusterName); return remoteCluster && remoteCluster.isConnected ? { error: null } @@ -76,7 +76,7 @@ export class RemoteClustersFormField extends PureComponent { }; } - onRemoteClusterChange = cluster => { + onRemoteClusterChange = (cluster) => { const { onChange, onError } = this.props; const { error } = this.validateRemoteCluster(cluster); onChange(cluster); @@ -137,7 +137,7 @@ export class RemoteClustersFormField extends PureComponent { fullWidth options={remoteClustersOptions} value={hasClusters ? selected : ''} - onChange={e => { + onChange={(e) => { this.onRemoteClusterChange(e.target.value); }} hasNoInitialSelection={!hasClusters} @@ -252,7 +252,7 @@ export class RemoteClustersFormField extends PureComponent { ); }; - renderRemoteClusterDoesNotExist = name => { + renderRemoteClusterDoesNotExist = (name) => { const { currentUrl } = this.props; const title = i18n.translate( 'xpack.crossClusterReplication.remoteClustersFormField.remoteClusterNotFoundTitle', @@ -287,7 +287,7 @@ export class RemoteClustersFormField extends PureComponent { renderErrorMessage = () => { const { selected, remoteClusters, isEditable } = this.props; - const remoteCluster = remoteClusters.find(c => c.name === selected); + const remoteCluster = remoteClusters.find((c) => c.name === selected); const isSelectedRemoteClusterConnected = remoteCluster && remoteCluster.isConnected; let error; @@ -319,7 +319,7 @@ export class RemoteClustersFormField extends PureComponent { render() { const { remoteClusters, selected, isEditable, areErrorsVisible } = this.props; - const remoteCluster = remoteClusters.find(c => c.name === selected); + const remoteCluster = remoteClusters.find((c) => c.name === selected); const hasClusters = Boolean(remoteClusters.length); const isSelectedRemoteClusterConnected = remoteCluster && remoteCluster.isConnected; const isInvalid = areErrorsVisible && (!hasClusters || !isSelectedRemoteClusterConnected); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js index 5b26444a136b8..4690f02539886 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js @@ -19,7 +19,7 @@ export class RemoteClustersProvider extends PureComponent { } loadRemoteClusters() { - const sortClusterByName = remoteClusters => + const sortClusterByName = (remoteClusters) => remoteClusters.sort((a, b) => { if (a.name < b.name) { return -1; @@ -31,13 +31,13 @@ export class RemoteClustersProvider extends PureComponent { }); loadRemoteClusters() .then(sortClusterByName) - .then(remoteClusters => { + .then((remoteClusters) => { this.setState({ isLoading: false, remoteClusters, }); }) - .catch(error => { + .catch((error) => { this.setState({ isLoading: false, error, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js index 95ae14ab89f58..b34b831e07ca4 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js @@ -13,12 +13,12 @@ import { AutoFollowPatternAdd as AutoFollowPatternAddView } from './auto_follow_ const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: getApiStatus(`${scope}-save`)(state), apiError: getApiError(`${scope}-save`)(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ saveAutoFollowPattern: (id, autoFollowPattern) => dispatch(saveAutoFollowPattern(id, autoFollowPattern)), clearApiError: () => dispatch(clearApiError(scope)), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js index be470edc07537..4eb1054248737 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js @@ -23,7 +23,7 @@ import { AutoFollowPatternEdit as AutoFollowPatternEditView } from './auto_follo const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: { get: getApiStatus(`${scope}-get`)(state), save: getApiStatus(`${scope}-save`)(state), @@ -36,9 +36,9 @@ const mapStateToProps = state => ({ autoFollowPattern: getSelectedAutoFollowPattern('edit')(state), }); -const mapDispatchToProps = dispatch => ({ - getAutoFollowPattern: id => dispatch(getAutoFollowPattern(id)), - selectAutoFollowPattern: id => dispatch(selectEditAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + getAutoFollowPattern: (id) => dispatch(getAutoFollowPattern(id)), + selectAutoFollowPattern: (id) => dispatch(selectEditAutoFollowPattern(id)), saveAutoFollowPattern: (id, autoFollowPattern) => { // Strip out errors. const { active, remoteCluster, leaderIndexPatterns, followIndexPattern } = autoFollowPattern; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js index 16fcd876bef7f..7c667ccdd9ea8 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js @@ -13,12 +13,12 @@ import { FollowerIndexAdd as FollowerIndexAddView } from './follower_index_add'; const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: getApiStatus(`${scope}-save`)(state), apiError: getApiError(`${scope}-save`)(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ saveFollowerIndex: (id, followerIndex) => dispatch(saveFollowerIndex(id, followerIndex)), clearApiError: () => dispatch(clearApiError(`${scope}-save`)), }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js index 9bfbdda41fcd5..f870031f170db 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js @@ -23,7 +23,7 @@ import { FollowerIndexEdit as FollowerIndexEditView } from './follower_index_edi const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: { get: getApiStatus(`${scope}-get`)(state), save: getApiStatus(`${scope}-save`)(state), @@ -36,9 +36,9 @@ const mapStateToProps = state => ({ followerIndex: getSelectedFollowerIndex('edit')(state), }); -const mapDispatchToProps = dispatch => ({ - getFollowerIndex: id => dispatch(getFollowerIndex(id)), - selectFollowerIndex: id => dispatch(selectEditFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + getFollowerIndex: (id) => dispatch(getFollowerIndex(id)), + selectFollowerIndex: (id) => dispatch(selectEditFollowerIndex(id)), saveFollowerIndex: (id, followerIndex) => dispatch(saveFollowerIndex(id, followerIndex, true)), clearApiError: () => { dispatch(clearApiError(`${scope}-get`)); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js index edd2d283e9bd5..9b06da54dd34c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js @@ -23,7 +23,7 @@ import { AutoFollowPatternList as AutoFollowPatternListView } from './auto_follo const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatterns: getListAutoFollowPatterns(state), autoFollowPatternId: getSelectedAutoFollowPatternId('detail')(state), apiStatus: getApiStatus(scope)(state), @@ -31,9 +31,9 @@ const mapStateToProps = state => ({ isAuthorized: isApiAuthorized(scope)(state), }); -const mapDispatchToProps = dispatch => ({ - loadAutoFollowPatterns: inBackground => dispatch(loadAutoFollowPatterns(inBackground)), - selectAutoFollowPattern: id => dispatch(selectDetailAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + loadAutoFollowPatterns: (inBackground) => dispatch(loadAutoFollowPatterns(inBackground)), + selectAutoFollowPattern: (id) => dispatch(selectDetailAutoFollowPattern(id)), loadAutoFollowStats: () => dispatch(loadAutoFollowStats()), }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js index d3a596c7422f2..941eba63fac4d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js @@ -17,14 +17,14 @@ import { AutoFollowPatternTable as AutoFollowPatternTableComponent } from './aut const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatusDelete: getApiStatus(`${scope}-delete`)(state), }); -const mapDispatchToProps = dispatch => ({ - selectAutoFollowPattern: name => dispatch(selectDetailAutoFollowPattern(name)), - pauseAutoFollowPattern: name => dispatch(pauseAutoFollowPattern(name)), - resumeAutoFollowPattern: name => dispatch(resumeAutoFollowPattern(name)), +const mapDispatchToProps = (dispatch) => ({ + selectAutoFollowPattern: (name) => dispatch(selectDetailAutoFollowPattern(name)), + pauseAutoFollowPattern: (name) => dispatch(pauseAutoFollowPattern(name)), + resumeAutoFollowPattern: (name) => dispatch(resumeAutoFollowPattern(name)), }); export const AutoFollowPatternTable = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js index d682fdaadf818..273e2244a8cb1 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js @@ -27,7 +27,7 @@ const getFilteredPatterns = (autoFollowPatterns, queryText) => { if (queryText) { const normalizedSearchText = queryText.toLowerCase(); - return autoFollowPatterns.filter(autoFollowPattern => { + return autoFollowPatterns.filter((autoFollowPattern) => { const { name, remoteCluster, @@ -107,7 +107,7 @@ export class AutoFollowPatternTable extends PureComponent { ), sortable: true, truncateText: false, - render: name => { + render: (name) => { return ( { @@ -130,7 +130,7 @@ export class AutoFollowPatternTable extends PureComponent { defaultMessage: 'Status', } ), - render: active => { + render: (active) => { const statusText = active ? i18n.translate( 'xpack.crossClusterReplication.autoFollowPatternList.table.statusTextActive', @@ -169,7 +169,7 @@ export class AutoFollowPatternTable extends PureComponent { defaultMessage: 'Leader patterns', } ), - render: leaderIndexPatterns => leaderIndexPatterns.join(', '), + render: (leaderIndexPatterns) => leaderIndexPatterns.join(', '), }, { field: 'followIndexPatternPrefix', @@ -217,7 +217,7 @@ export class AutoFollowPatternTable extends PureComponent { return ( { + onClick={(event) => { if (event.stopPropagation) { event.stopPropagation(); } @@ -270,7 +270,7 @@ export class AutoFollowPatternTable extends PureComponent { return ( - {deleteAutoFollowPattern => ( + {(deleteAutoFollowPattern) => ( deleteAutoFollowPattern(name)} data-test-subj="contextMenuDeleteButton" @@ -318,7 +318,7 @@ export class AutoFollowPatternTable extends PureComponent { }; const selection = { - onSelectionChange: selectedItems => + onSelectionChange: (selectedItems) => this.setState({ selectedItems: selectedItems.map(({ name }) => name) }), }; @@ -326,13 +326,11 @@ export class AutoFollowPatternTable extends PureComponent { toolsLeft: selectedItems.length ? ( - filteredAutoFollowPatterns.find(item => item.name === name) + patterns={this.state.selectedItems.map((name) => + filteredAutoFollowPatterns.find((item) => item.name === name) )} /> - ) : ( - undefined - ), + ) : undefined, onChange: this.onSearch, box: { incremental: true, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js index a5d72a5e7e136..dcf494bccf8ff 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js @@ -16,7 +16,7 @@ import { SECTIONS } from '../../../../../constants'; const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatternId: getSelectedAutoFollowPatternId('detail')(state), autoFollowPattern: getSelectedAutoFollowPattern('detail')(state), apiStatus: getApiStatus(scope)(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js index 4a66f7b717bac..6549905013025 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js @@ -36,7 +36,7 @@ export class ContextMenu extends PureComponent { }; onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -47,7 +47,7 @@ export class ContextMenu extends PureComponent { }); }; - editFollowerIndex = id => { + editFollowerIndex = (id) => { const uri = routing.getFollowerIndexPath(id, '/edit', false); routing.navigate(uri); }; @@ -55,7 +55,7 @@ export class ContextMenu extends PureComponent { render() { const { followerIndices } = this.props; const followerIndicesLength = followerIndices.length; - const followerIndexNames = followerIndices.map(index => index.name); + const followerIndexNames = followerIndices.map((index) => index.name); const { iconSide = 'right', iconType = 'arrowDown', @@ -84,7 +84,7 @@ export class ContextMenu extends PureComponent { const pausedFollowerIndexNames = followerIndices .filter(({ isPaused }) => isPaused) - .map(index => index.name); + .map((index) => index.name); const activeFollowerIndices = followerIndices.filter(({ isPaused }) => !isPaused); return ( @@ -107,7 +107,7 @@ export class ContextMenu extends PureComponent { {activeFollowerIndices.length ? ( - {pauseFollowerIndex => ( + {(pauseFollowerIndex) => ( pauseFollowerIndex(activeFollowerIndices)} @@ -124,7 +124,7 @@ export class ContextMenu extends PureComponent { {pausedFollowerIndexNames.length ? ( - {resumeFollowerIndex => ( + {(resumeFollowerIndex) => ( resumeFollowerIndex(pausedFollowerIndexNames)} @@ -156,7 +156,7 @@ export class ContextMenu extends PureComponent { )} - {unfollowLeaderIndex => ( + {(unfollowLeaderIndex) => ( unfollowLeaderIndex(followerIndexNames)} diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js index 46190c27b27e5..640b7a25ce06b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js @@ -16,7 +16,7 @@ import { SECTIONS } from '../../../../../constants'; const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ followerIndexId: getSelectedFollowerIndexId('detail')(state), followerIndex: getSelectedFollowerIndex('detail')(state), apiStatus: getApiStatus(scope)(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js index 9c475082025f9..d1a175b92572e 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js @@ -13,12 +13,12 @@ import { FollowerIndicesTable as FollowerIndicesTableComponent } from './followe const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatusDelete: getApiStatus(`${scope}-delete`)(state), }); -const mapDispatchToProps = dispatch => ({ - selectFollowerIndex: name => dispatch(selectDetailFollowerIndex(name)), +const mapDispatchToProps = (dispatch) => ({ + selectFollowerIndex: (name) => dispatch(selectDetailFollowerIndex(name)), }); export const FollowerIndicesTable = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js index e95b3b0356aba..ea4a35de2282a 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js @@ -30,7 +30,7 @@ const getFilteredIndices = (followerIndices, queryText) => { if (queryText) { const normalizedSearchText = queryText.toLowerCase(); - return followerIndices.filter(followerIndex => { + return followerIndices.filter((followerIndex) => { const { name, remoteCluster, leaderIndex } = followerIndex; if (name.toLowerCase().includes(normalizedSearchText)) { @@ -96,7 +96,7 @@ export class FollowerIndicesTable extends PureComponent { }); }; - editFollowerIndex = id => { + editFollowerIndex = (id) => { const uri = routing.getFollowerIndexPath(id, '/edit', false); routing.navigate(uri); }; @@ -107,7 +107,7 @@ export class FollowerIndicesTable extends PureComponent { const actions = [ /* Pause or resume follower index */ { - render: followerIndex => { + render: (followerIndex) => { const { name, isPaused } = followerIndex; const label = isPaused ? i18n.translate( @@ -125,7 +125,7 @@ export class FollowerIndicesTable extends PureComponent { return isPaused ? ( - {resumeFollowerIndex => ( + {(resumeFollowerIndex) => ( resumeFollowerIndex(name)} data-test-subj="resumeButton"> {label} @@ -134,7 +134,7 @@ export class FollowerIndicesTable extends PureComponent { ) : ( - {pauseFollowerIndex => ( + {(pauseFollowerIndex) => ( pauseFollowerIndex(followerIndex)} data-test-subj="pauseButton" @@ -177,7 +177,7 @@ export class FollowerIndicesTable extends PureComponent { return ( - {unfollowLeaderIndex => ( + {(unfollowLeaderIndex) => ( unfollowLeaderIndex(name)} data-test-subj="unfollowButton"> {label} @@ -200,7 +200,7 @@ export class FollowerIndicesTable extends PureComponent { ), sortable: true, truncateText: false, - render: name => { + render: (name) => { return ( { @@ -224,7 +224,7 @@ export class FollowerIndicesTable extends PureComponent { ), truncateText: true, sortable: true, - render: isPaused => { + render: (isPaused) => { return isPaused ? ( this.setState({ selectedItems: newSelectedItems }), + onSelectionChange: (newSelectedItems) => this.setState({ selectedItems: newSelectedItems }), }; const search = { toolsLeft: selectedItems.length ? ( - ) : ( - undefined - ), + ) : undefined, onChange: this.onSearch, box: { incremental: true, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js index f49db53d9e304..0afb0536726a3 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js @@ -19,7 +19,7 @@ import { FollowerIndicesList as FollowerIndicesListView } from './follower_indic const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ followerIndices: getListFollowerIndices(state), followerIndexId: getSelectedFollowerIndexId('detail')(state), apiStatus: getApiStatus(scope)(state), @@ -27,9 +27,9 @@ const mapStateToProps = state => ({ isAuthorized: isApiAuthorized(scope)(state), }); -const mapDispatchToProps = dispatch => ({ - loadFollowerIndices: inBackground => dispatch(loadFollowerIndices(inBackground)), - selectFollowerIndex: id => dispatch(selectDetailFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + loadFollowerIndices: (inBackground) => dispatch(loadFollowerIndices(inBackground)), + selectFollowerIndex: (id) => dispatch(selectDetailFollowerIndex(id)), }); export const FollowerIndicesList = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js index 5b35436a483fe..c98eb4ba6ae17 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js @@ -14,7 +14,7 @@ import { } from '../../store/selectors'; import { CrossClusterReplicationHome as CrossClusterReplicationHomeView } from './home'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatterns: getListAutoFollowPatterns(state), isAutoFollowApiAuthorized: isApiAuthorized(SECTIONS.AUTO_FOLLOW_PATTERN)(state), followerIndices: getListFollowerIndices(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js index bcd9dad114862..ec62dbc2d1603 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js @@ -59,7 +59,7 @@ export class CrossClusterReplicationHome extends PureComponent { }; } - onSectionChange = section => { + onSectionChange = (section) => { routing.navigate(`/${section}`); }; @@ -79,7 +79,7 @@ export class CrossClusterReplicationHome extends PureComponent { - {this.tabs.map(tab => ( + {this.tabs.map((tab) => ( this.onSectionChange(tab.id)} isSelected={tab.id === this.state.activeSection} diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/api.js b/x-pack/plugins/cross_cluster_replication/public/app/services/api.js index adff40ef29be6..72a4532bfafac 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/api.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/api.js @@ -43,17 +43,17 @@ export const getHttpClient = () => { // --- -const createIdString = ids => ids.map(id => encodeURIComponent(id)).join(','); +const createIdString = (ids) => ids.map((id) => encodeURIComponent(id)).join(','); /* Auto Follow Pattern */ export const loadAutoFollowPatterns = () => httpClient.get(`${API_BASE_PATH}/auto_follow_patterns`); -export const getAutoFollowPattern = id => +export const getAutoFollowPattern = (id) => httpClient.get(`${API_BASE_PATH}/auto_follow_patterns/${encodeURIComponent(id)}`); export const loadRemoteClusters = () => httpClient.get(API_REMOTE_CLUSTERS_BASE_PATH); -export const createAutoFollowPattern = autoFollowPattern => { +export const createAutoFollowPattern = (autoFollowPattern) => { const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns`, { body: JSON.stringify(autoFollowPattern), }); @@ -68,16 +68,16 @@ export const updateAutoFollowPattern = (id, autoFollowPattern) => { return trackUserRequest(request, UIM_AUTO_FOLLOW_PATTERN_UPDATE); }; -export const deleteAutoFollowPattern = id => { +export const deleteAutoFollowPattern = (id) => { const ids = arrify(id); - const idString = ids.map(_id => encodeURIComponent(_id)).join(','); + const idString = ids.map((_id) => encodeURIComponent(_id)).join(','); const request = httpClient.delete(`${API_BASE_PATH}/auto_follow_patterns/${idString}`); const uiMetric = ids.length > 1 ? UIM_AUTO_FOLLOW_PATTERN_DELETE_MANY : UIM_AUTO_FOLLOW_PATTERN_DELETE; return trackUserRequest(request, uiMetric); }; -export const pauseAutoFollowPattern = id => { +export const pauseAutoFollowPattern = (id) => { const ids = arrify(id); const idString = ids.map(encodeURIComponent).join(','); const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns/${idString}/pause`); @@ -87,7 +87,7 @@ export const pauseAutoFollowPattern = id => { return trackUserRequest(request, uiMetric); }; -export const resumeAutoFollowPattern = id => { +export const resumeAutoFollowPattern = (id) => { const ids = arrify(id); const idString = ids.map(encodeURIComponent).join(','); const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns/${idString}/resume`); @@ -100,10 +100,10 @@ export const resumeAutoFollowPattern = id => { /* Follower Index */ export const loadFollowerIndices = () => httpClient.get(`${API_BASE_PATH}/follower_indices`); -export const getFollowerIndex = id => +export const getFollowerIndex = (id) => httpClient.get(`${API_BASE_PATH}/follower_indices/${encodeURIComponent(id)}`); -export const createFollowerIndex = followerIndex => { +export const createFollowerIndex = (followerIndex) => { const uiMetrics = [UIM_FOLLOWER_INDEX_CREATE]; const isUsingAdvancedSettings = !areAllSettingsDefault(followerIndex); if (isUsingAdvancedSettings) { @@ -115,7 +115,7 @@ export const createFollowerIndex = followerIndex => { return trackUserRequest(request, uiMetrics); }; -export const pauseFollowerIndex = id => { +export const pauseFollowerIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/pause`); @@ -123,7 +123,7 @@ export const pauseFollowerIndex = id => { return trackUserRequest(request, uiMetric); }; -export const resumeFollowerIndex = id => { +export const resumeFollowerIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/resume`); @@ -131,7 +131,7 @@ export const resumeFollowerIndex = id => { return trackUserRequest(request, uiMetric); }; -export const unfollowLeaderIndex = id => { +export const unfollowLeaderIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/unfollow`); @@ -189,10 +189,12 @@ export const loadIndices = () => { } abortController = new AbortController(); const { signal } = abortController; - return httpClient.get(`${API_INDEX_MANAGEMENT_BASE_PATH}/indices`, { signal }).then(response => { - abortController = null; - return response; - }); + return httpClient + .get(`${API_INDEX_MANAGEMENT_BASE_PATH}/indices`, { signal }) + .then((response) => { + abortController = null; + return response; + }); }; export const loadPermissions = () => httpClient.get(`${API_BASE_PATH}/permissions`); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js index 70311d5ba1e4d..5433ee73282a0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -export const parseAutoFollowError = error => { +export const parseAutoFollowError = (error) => { if (!error.leaderIndex) { return null; } @@ -27,7 +27,7 @@ export const parseAutoFollowError = error => { export const parseAutoFollowErrors = (recentAutoFollowErrors, maxErrorsToShow = 5) => recentAutoFollowErrors .map(parseAutoFollowError) - .filter(error => error !== null) + .filter((error) => error !== null) .reduce((byId, error) => { if (!byId[error.id]) { byId[error.id] = []; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js index 5d374ab3779e4..e717d130da2b0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js @@ -29,24 +29,22 @@ export const getPreviewIndicesFromAutoFollowPattern = ({ limit = 5, wildcardPlaceHolders = [ moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - moment() - .add(2, 'days') - .format('YYYY-MM-DD'), + moment().add(1, 'days').format('YYYY-MM-DD'), + moment().add(2, 'days').format('YYYY-MM-DD'), ], }) => { const indicesPreview = []; let indexPreview; let leaderIndexTemplate; - leaderIndexPatterns.forEach(leaderIndexPattern => { - wildcardPlaceHolders.forEach(placeHolder => { + leaderIndexPatterns.forEach((leaderIndexPattern) => { + wildcardPlaceHolders.forEach((placeHolder) => { leaderIndexTemplate = leaderIndexPattern.replace(/\*/g, placeHolder); indexPreview = getFollowPattern(prefix, suffix, leaderIndexTemplate); - if (!indicesPreview.some(_indexPreview => indexPreview.toString === _indexPreview.toString)) { + if ( + !indicesPreview.some((_indexPreview) => indexPreview.toString === _indexPreview.toString) + ) { indicesPreview.push(indexPreview); } }); @@ -58,7 +56,7 @@ export const getPreviewIndicesFromAutoFollowPattern = ({ }; }; -export const getPrefixSuffixFromFollowPattern = followPattern => { +export const getPrefixSuffixFromFollowPattern = (followPattern) => { let followIndexPatternPrefix; let followIndexPatternSuffix; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js index 56633549ef013..dc5b19799940d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js @@ -29,14 +29,10 @@ describe('Auto-follo pattern service', () => { }); expect(hasMore).toBe(false); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ `prefix_logstash-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(2, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(2, 'days').format('YYYY-MM-DD')}_suffix`, ]); }); @@ -50,18 +46,12 @@ describe('Auto-follo pattern service', () => { }); expect(hasMore).toBe(true); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ `prefix_logstash-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(2, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(2, 'days').format('YYYY-MM-DD')}_suffix`, `prefix_other-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_other-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_other-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, ]); }); @@ -76,7 +66,7 @@ describe('Auto-follo pattern service', () => { wildcardPlaceHolders, }); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ 'prefix_logstash-A_suffix', 'prefix_logstash-B_suffix', ]); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js index cf394d4b3c7d8..39d40389daa17 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js @@ -52,7 +52,7 @@ export const validateName = (name = '') => { return errorMsg; }; -export const validateLeaderIndexPattern = indexPattern => { +export const validateLeaderIndexPattern = (indexPattern) => { if (indexPattern) { const errors = indexPatterns.validate(indexPattern); @@ -100,7 +100,7 @@ export const validateLeaderIndexPattern = indexPattern => { return null; }; -export const validateLeaderIndexPatterns = indexPatterns => { +export const validateLeaderIndexPatterns = (indexPatterns) => { // We only need to check if a value has been provided, because validation for this field // has already been executed as the user has entered input into it. if (!indexPatterns.length) { @@ -117,7 +117,7 @@ export const validateLeaderIndexPatterns = indexPatterns => { return null; }; -export const validatePrefix = prefix => { +export const validatePrefix = (prefix) => { // If it's empty, it is valid if (!prefix || !prefix.trim()) { return null; @@ -161,7 +161,7 @@ export const validatePrefix = prefix => { return null; }; -export const validateSuffix = suffix => { +export const validateSuffix = (suffix) => { // If it's empty, it is valid if (!suffix || !suffix.trim()) { return null; @@ -200,7 +200,7 @@ export const validateAutoFollowPattern = (autoFollowPattern = {}) => { let error = null; let fieldValue; - Object.keys(autoFollowPattern).forEach(fieldName => { + Object.keys(autoFollowPattern).forEach((fieldName) => { fieldValue = autoFollowPattern[fieldName]; error = null; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js b/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js index 118a54887d404..7699b776620f4 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js @@ -6,7 +6,7 @@ import { FOLLOWER_INDEX_ADVANCED_SETTINGS } from '../../../common/constants'; -export const getSettingDefault = name => { +export const getSettingDefault = (name) => { if (!FOLLOWER_INDEX_ADVANCED_SETTINGS[name]) { throw new Error(`Unknown setting ${name}`); } @@ -18,8 +18,8 @@ export const isSettingDefault = (name, value) => { return getSettingDefault(name) === value; }; -export const areAllSettingsDefault = settings => { - return Object.keys(FOLLOWER_INDEX_ADVANCED_SETTINGS).every(name => +export const areAllSettingsDefault = (settings) => { + return Object.keys(FOLLOWER_INDEX_ADVANCED_SETTINGS).every((name) => isSettingDefault(name, settings[name]) ); }; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js b/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js index bf144b7129475..4f47facf70b20 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -const getFirstConnectedCluster = clusters => { +const getFirstConnectedCluster = (clusters) => { for (let i = 0; i < clusters.length; i++) { if (clusters[i].isConnected) { return clusters[i]; @@ -16,7 +16,7 @@ const getFirstConnectedCluster = clusters => { }; export const getRemoteClusterName = (remoteClusters, selected) => { - return selected && remoteClusters.some(c => c.name === selected) + return selected && remoteClusters.some((c) => c.name === selected) ? selected : getFirstConnectedCluster(remoteClusters).name; }; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js b/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js index 7e2b45b625c1f..e702a47e91155 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js @@ -8,17 +8,17 @@ import React from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { indices } from '../../../../../../src/plugins/es_ui_shared/public'; -const isEmpty = value => { +const isEmpty = (value) => { return !value || !value.trim().length; }; -const hasSpaces = value => (typeof value === 'string' ? value.includes(' ') : false); +const hasSpaces = (value) => (typeof value === 'string' ? value.includes(' ') : false); -const beginsWithPeriod = value => { +const beginsWithPeriod = (value) => { return value[0] === '.'; }; -const findIllegalCharacters = value => { +const findIllegalCharacters = (value) => { return indices.INDEX_ILLEGAL_CHARACTERS_VISIBLE.reduce((chars, char) => { if (value.includes(char)) { chars.push(char); @@ -28,7 +28,7 @@ const findIllegalCharacters = value => { }, []); }; -export const indexNameValidator = value => { +export const indexNameValidator = (value) => { if (isEmpty(value)) { return [ { return undefined; }; -export const leaderIndexValidator = value => { +export const leaderIndexValidator = (value) => { if (isEmpty(value)) { return [ +const isModifiedEvent = (event) => !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); -const isLeftClickEvent = event => event.button === 0; +const isLeftClickEvent = (event) => event.button === 0; const queryParamsFromObject = (params, encodeParams = false) => { if (!params) { @@ -48,7 +48,7 @@ class Routing { : to; const href = this._reactRouter.history.createHref(location); - const onClick = event => { + const onClick = (event) => { if (event.defaultPrevented) { return; } diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts b/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts index aecc4eb83893f..b4307ed125bf2 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts @@ -24,7 +24,7 @@ export function init(usageCollection: UsageCollectionSetup): void { */ export function trackUserRequest(request: Promise, actionType: string) { // Only track successful actions. - return request.then(response => { + return request.then((response) => { // It looks like we're using the wrong type here, added via // https://github.com/elastic/kibana/pull/41113/files#diff-e65a0a6696a9d723969afd871cbd60cdR19 // but we'll keep it for now to avoid discontinuity in our telemetry data. diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js b/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js index 9769228098c12..06ce3962966e9 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -export const objectToArray = obj => Object.keys(obj).map(k => ({ ...obj[k], __id__: k })); +export const objectToArray = (obj) => Object.keys(obj).map((k) => ({ ...obj[k], __id__: k })); export const arrayToObject = (array, keyProp = 'id') => array.reduce((acc, item) => { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js index 4b97699ece2ff..6abb024b5dcce 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js @@ -22,7 +22,10 @@ export const setApiError = ({ error, scope }) => ({ payload: { error, scope }, }); -export const clearApiError = scope => ({ type: t.API_ERROR_SET, payload: { error: null, scope } }); +export const clearApiError = (scope) => ({ + type: t.API_ERROR_SET, + payload: { error: null, scope }, +}); export const sendApiRequest = ({ label, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js index 52a22cb17d0a9..ea6801b55458d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js @@ -22,12 +22,12 @@ import { getSelectedAutoFollowPatternId } from '../selectors'; const { AUTO_FOLLOW_PATTERN: scope } = SECTIONS; -export const selectDetailAutoFollowPattern = id => ({ +export const selectDetailAutoFollowPattern = (id) => ({ type: t.AUTO_FOLLOW_PATTERN_SELECT_DETAIL, payload: id, }); -export const selectEditAutoFollowPattern = id => ({ +export const selectEditAutoFollowPattern = (id) => ({ type: t.AUTO_FOLLOW_PATTERN_SELECT_EDIT, payload: id, }); @@ -40,7 +40,7 @@ export const loadAutoFollowPatterns = (isUpdating = false) => handler: async () => await loadAutoFollowPatternsRequest(), }); -export const getAutoFollowPattern = id => +export const getAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_GET, scope: `${scope}-get`, @@ -82,7 +82,7 @@ export const saveAutoFollowPattern = (id, autoFollowPattern, isUpdating = false) }, }); -export const deleteAutoFollowPattern = id => +export const deleteAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_DELETE, scope: `${scope}-delete`, @@ -144,13 +144,13 @@ export const deleteAutoFollowPattern = id => }, }); -export const pauseAutoFollowPattern = id => +export const pauseAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_PAUSE, scope: `${scope}-pause`, status: API_STATUS.UPDATING, handler: () => pauseAutoFollowPatternRequest(id), - onSuccess: response => { + onSuccess: (response) => { /** * We can have 1 or more auto-follow pattern pause operations * that can fail or succeed. We will show 1 toast notification for each. @@ -200,13 +200,13 @@ export const pauseAutoFollowPattern = id => }, }); -export const resumeAutoFollowPattern = id => +export const resumeAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_RESUME, scope: `${scope}-resume`, status: API_STATUS.UPDATING, handler: () => resumeAutoFollowPatternRequest(id), - onSuccess: response => { + onSuccess: (response) => { /** * We can have 1 or more auto-follow pattern resume operations * that can fail or succeed. We will show 1 toast notification for each. diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js index d081e0444eb58..61d0ed1d51c72 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js @@ -23,12 +23,12 @@ import { getSelectedFollowerIndexId } from '../selectors'; const { FOLLOWER_INDEX: scope } = SECTIONS; -export const selectDetailFollowerIndex = id => ({ +export const selectDetailFollowerIndex = (id) => ({ type: t.FOLLOWER_INDEX_SELECT_DETAIL, payload: id, }); -export const selectEditFollowerIndex = id => ({ +export const selectEditFollowerIndex = (id) => ({ type: t.FOLLOWER_INDEX_SELECT_EDIT, payload: id, }); @@ -41,7 +41,7 @@ export const loadFollowerIndices = (isUpdating = false) => handler: async () => await loadFollowerIndicesRequest(), }); -export const getFollowerIndex = id => +export const getFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_GET, scope: `${scope}-get`, @@ -83,7 +83,7 @@ export const saveFollowerIndex = (name, followerIndex, isUpdating = false) => }, }); -export const pauseFollowerIndex = id => +export const pauseFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_PAUSE, status: API_STATUS.SAVING, @@ -142,7 +142,7 @@ export const pauseFollowerIndex = id => }, }); -export const resumeFollowerIndex = id => +export const resumeFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_RESUME, status: API_STATUS.SAVING, @@ -202,7 +202,7 @@ export const resumeFollowerIndex = id => }, }); -export const unfollowLeaderIndex = id => +export const unfollowLeaderIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_UNFOLLOW, status: API_STATUS.DELETING, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js index bd082f1b0372b..c09c02698106b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js @@ -14,17 +14,17 @@ const initialState = { selectedEditId: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; const setActiveForIds = (ids, byId, active) => { const shallowCopyByIds = { ...byId }; - ids.forEach(id => { + ids.forEach((id) => { shallowCopyByIds[id].active = active; }); return shallowCopyByIds; }; -const parseAutoFollowPattern = autoFollowPattern => { +const parseAutoFollowPattern = (autoFollowPattern) => { // Extract prefix and suffix from follow index pattern const { followIndexPatternPrefix, followIndexPatternSuffix } = getPrefixSuffixFromFollowPattern( autoFollowPattern.followIndexPattern @@ -56,7 +56,7 @@ export const reducer = (state = initialState, action) => { case success(t.AUTO_FOLLOW_PATTERN_DELETE): { const byId = { ...state.byId }; const { itemsDeleted } = action.payload; - itemsDeleted.forEach(id => delete byId[id]); + itemsDeleted.forEach((id) => delete byId[id]); return { ...state, byId }; } case success(t.AUTO_FOLLOW_PATTERN_PAUSE): { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js index fe69a465257ef..3fbc2ca967ec0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js @@ -13,9 +13,9 @@ const initialState = { selectedEditId: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; -const parseFollowerIndex = followerIndex => { +const parseFollowerIndex = (followerIndex) => { // Extract status into boolean return { ...followerIndex, isPaused: followerIndex.status === 'paused' }; }; @@ -42,7 +42,7 @@ export const reducer = (state = initialState, action) => { case success(t.FOLLOWER_INDEX_UNFOLLOW): { const byId = { ...state.byId }; const { itemsUnfollowed } = action.payload; - itemsUnfollowed.forEach(id => delete byId[id]); + itemsUnfollowed.forEach((id) => delete byId[id]); return { ...state, byId }; } default: diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js index 4cacfe1b759a5..39d3b1c4d8e4f 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js @@ -11,7 +11,7 @@ const initialState = { autoFollow: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; export const reducer = (state = initialState, action) => { switch (action.type) { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js index 7dbc5a327bc66..eb0b88b95bbfc 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js @@ -9,12 +9,13 @@ import { objectToArray } from '../../services/utils'; import { API_STATUS } from '../../constants'; // Api -export const getApiState = state => state.api; -export const getApiStatus = scope => - createSelector(getApiState, apiState => apiState.status[scope] || API_STATUS.IDLE); -export const getApiError = scope => createSelector(getApiState, apiState => apiState.error[scope]); -export const isApiAuthorized = scope => - createSelector(getApiError(scope), error => { +export const getApiState = (state) => state.api; +export const getApiStatus = (scope) => + createSelector(getApiState, (apiState) => apiState.status[scope] || API_STATUS.IDLE); +export const getApiError = (scope) => + createSelector(getApiState, (apiState) => apiState.error[scope]); +export const isApiAuthorized = (scope) => + createSelector(getApiError(scope), (error) => { if (!error) { return true; } @@ -22,20 +23,20 @@ export const isApiAuthorized = scope => }); // Stats -export const getStatsState = state => state.stats; +export const getStatsState = (state) => state.stats; export const getAutoFollowStats = createSelector( getStatsState, - statsState => statsState.autoFollow + (statsState) => statsState.autoFollow ); // Auto-follow pattern -export const getAutoFollowPatternState = state => state.autoFollowPattern; +export const getAutoFollowPatternState = (state) => state.autoFollowPattern; export const getAutoFollowPatterns = createSelector( getAutoFollowPatternState, - autoFollowPatternsState => autoFollowPatternsState.byId + (autoFollowPatternsState) => autoFollowPatternsState.byId ); export const getSelectedAutoFollowPatternId = (view = 'detail') => - createSelector(getAutoFollowPatternState, autoFollowPatternsState => + createSelector(getAutoFollowPatternState, (autoFollowPatternsState) => view === 'detail' ? autoFollowPatternsState.selectedDetailId : autoFollowPatternsState.selectedEditId @@ -59,22 +60,23 @@ export const getSelectedAutoFollowPattern = (view = 'detail') => return autoFollowPattern ? { ...autoFollowPattern, errors } : null; } ); -export const getListAutoFollowPatterns = createSelector(getAutoFollowPatterns, autoFollowPatterns => - objectToArray(autoFollowPatterns) +export const getListAutoFollowPatterns = createSelector( + getAutoFollowPatterns, + (autoFollowPatterns) => objectToArray(autoFollowPatterns) ); // Follower index -export const getFollowerIndexState = state => state.followerIndex; +export const getFollowerIndexState = (state) => state.followerIndex; export const getFollowerIndices = createSelector( getFollowerIndexState, - followerIndexState => followerIndexState.byId + (followerIndexState) => followerIndexState.byId ); export const getSelectedFollowerIndexId = (view = 'detail') => - createSelector(getFollowerIndexState, followerIndexState => + createSelector(getFollowerIndexState, (followerIndexState) => view === 'detail' ? followerIndexState.selectedDetailId : followerIndexState.selectedEditId ); export const getSelectedFollowerIndex = (view = 'detail') => - createSelector(getFollowerIndexState, followerIndexState => { + createSelector(getFollowerIndexState, (followerIndexState) => { const propId = view === 'detail' ? 'selectedDetailId' : 'selectedEditId'; if (!followerIndexState[propId]) { @@ -82,6 +84,6 @@ export const getSelectedFollowerIndex = (view = 'detail') => } return followerIndexState.byId[followerIndexState[propId]]; }); -export const getListFollowerIndices = createSelector(getFollowerIndices, followerIndices => +export const getListFollowerIndices = createSelector(getFollowerIndices, (followerIndices) => objectToArray(followerIndices) ); diff --git a/x-pack/plugins/cross_cluster_replication/public/plugin.ts b/x-pack/plugins/cross_cluster_replication/public/plugin.ts index 561da838a4202..e748822ab8ae7 100644 --- a/x-pack/plugins/cross_cluster_replication/public/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/public/plugin.ts @@ -65,7 +65,7 @@ export class CrossClusterReplicationPlugin implements Plugin { licensing.license$ .pipe(first()) .toPromise() - .then(license => { + .then((license) => { const licenseStatus = license.check(PLUGIN.ID, PLUGIN.minimumLicenseType); const isLicenseOk = licenseStatus.state === 'valid'; const config = this.initializerContext.config.get(); diff --git a/x-pack/plugins/cross_cluster_replication/server/plugin.ts b/x-pack/plugins/cross_cluster_replication/server/plugin.ts index 7ef085a21ac1a..f30378d874a9a 100644 --- a/x-pack/plugins/cross_cluster_replication/server/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/server/plugin.ts @@ -57,7 +57,7 @@ const ccrDataEnricher = async (indicesList: Index[], callWithRequest: APICaller) 'transport.request', params ); - return indicesList.map(index => { + return indicesList.map((index) => { const isFollowerIndex = !!followerIndices.find( (followerIndex: { follower_index: string }) => { return followerIndex.follower_index === index.name; @@ -92,7 +92,7 @@ export class CrossClusterReplicationServerPlugin implements Plugin { + .then((config) => { // remoteClusters.isUiEnabled is driven by the xpack.remote_clusters.ui.enabled setting. // The CCR UI depends upon the Remote Clusters UI (e.g. by cross-linking to it), so if // the Remote Clusters UI is disabled we can't show the CCR UI. diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts index ed2633a4a469e..085e01a836942 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts @@ -44,7 +44,7 @@ export const registerDeleteRoute = ({ }; await Promise.all( - ids.map(_id => + ids.map((_id) => context .crossClusterReplication!.client.callAsCurrentUser('ccr.deleteAutoFollowPattern', { id: _id, diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts index 325939709e751..ca224b9ae3627 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts @@ -43,13 +43,13 @@ export const registerPauseRoute = ({ }; await Promise.all( - ids.map(_id => + ids.map((_id) => context .crossClusterReplication!.client.callAsCurrentUser('ccr.pauseAutoFollowPattern', { id: _id, }) .then(() => itemsPaused.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts index f5e917773704c..c5f3e2190260e 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts @@ -49,7 +49,7 @@ export const registerResumeRoute = ({ id: _id, }) .then(() => itemsResumed.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts index 7432ea7ca5c82..bf6f026e70849 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts @@ -47,7 +47,7 @@ export const registerPauseRoute = ({ id: _id, }) .then(() => itemsPaused.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts index ca8f3a9f5fe9d..03f21df2e856e 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts @@ -47,7 +47,7 @@ export const registerResumeRoute = ({ id: _id, }) .then(() => itemsResumed.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/services/license.ts b/x-pack/plugins/cross_cluster_replication/server/services/license.ts index bfd357867c3e2..5424092a01ee5 100644 --- a/x-pack/plugins/cross_cluster_replication/server/services/license.ts +++ b/x-pack/plugins/cross_cluster_replication/server/services/license.ts @@ -37,7 +37,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx index dc19fccf5c92f..6d6803510a281 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx @@ -85,7 +85,7 @@ export class CollectConfigContainer extends React.Component< keepRange={config.useCurrentDateRange} isLoading={isLoading} error={error} - onDashboardSelect={dashboardId => { + onDashboardSelect={(dashboardId) => { onConfig({ ...config, dashboardId }); if (this.state.error) { this.setState({ error: undefined }); diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx index f3a966a73509c..37f82e449ff72 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx @@ -27,9 +27,9 @@ const InteractiveDemo: React.FC = () => { dashboards={dashboards} currentFilters={currentFilters} keepRange={keepRange} - onDashboardSelect={id => setActiveDashboardId(id)} - onCurrentFiltersToggle={() => setCurrentFilters(old => !old)} - onKeepRangeToggle={() => setKeepRange(old => !old)} + onDashboardSelect={(id) => setActiveDashboardId(id)} + onCurrentFiltersToggle={() => setCurrentFilters((old) => !old)} + onKeepRangeToggle={() => setKeepRange((old) => !old)} onSearchChange={() => {}} isLoading={false} /> @@ -44,7 +44,7 @@ storiesOf( console.log('onDashboardSelect', e)} + onDashboardSelect={(e) => console.log('onDashboardSelect', e)} onSearchChange={() => {}} isLoading={false} /> @@ -53,7 +53,7 @@ storiesOf( console.log('onDashboardSelect', e)} + onDashboardSelect={(e) => console.log('onDashboardSelect', e)} onCurrentFiltersToggle={() => console.log('onCurrentFiltersToggle')} onKeepRangeToggle={() => console.log('onKeepRangeToggle')} onSearchChange={() => {}} diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx index a41a5fb718219..c9ecc74f1391c 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx @@ -37,7 +37,7 @@ export const DashboardDrilldownConfig: React.FC = isLoading, error, }) => { - const selectedTitle = dashboards.find(item => item.value === activeDashboardId)?.label || ''; + const selectedTitle = dashboards.find((item) => item.value === activeDashboardId)?.label || ''; return ( <> diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx index 21afa6e822dc5..7ff84a75dd52c 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx @@ -38,7 +38,7 @@ export class DashboardToDashboardDrilldown public readonly euiIcon = 'dashboardApp'; - private readonly ReactCollectConfig: React.FC = props => ( + private readonly ReactCollectConfig: React.FC = (props) => ( ); @@ -93,7 +93,7 @@ export class DashboardToDashboardDrilldown const existingFilters = (config.useCurrentFilters ? currentFilters - : currentFilters?.filter(f => esFilters.isFilterPinned(f))) ?? []; + : currentFilters?.filter((f) => esFilters.isFilterPinned(f))) ?? []; // if useCurrentDashboardDataRange is enabled, then preserve current time range // if undefined is passed, then destination dashboard will figure out time range itself diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts index 211e0ad9a26c4..47cfb8cc61d00 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts @@ -34,7 +34,7 @@ describe('Kuery conjunction suggestions', () => { const suggestions = await getSuggestions(querySuggestionsArgs, mockKueryNode({ text })); expect(suggestions.length).toBe(2); - expect(suggestions.map(suggestion => suggestion.text)).toEqual(['and ', 'or ']); + expect(suggestions.map((suggestion) => suggestion.text)).toEqual(['and ', 'or ']); }); test('should suggest to insert the suggestion at the end of the string', async () => { @@ -43,8 +43,8 @@ describe('Kuery conjunction suggestions', () => { const suggestions = await getSuggestions(querySuggestionsArgs, mockKueryNode({ text, end })); expect(suggestions.length).toBe(2); - expect(suggestions.map(suggestion => suggestion.start)).toEqual([end, end]); - expect(suggestions.map(suggestion => suggestion.end)).toEqual([end, end]); + expect(suggestions.map((suggestion) => suggestion.start)).toEqual([end, end]); + expect(suggestions.map((suggestion) => suggestion.end)).toEqual([end, end]); }); test('should have descriptions', async () => { @@ -54,7 +54,7 @@ describe('Kuery conjunction suggestions', () => { expect(typeof suggestions).toBe('object'); expect(Object.keys(suggestions).length).toBe(2); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(typeof suggestion).toBe('object'); expect(suggestion).toHaveProperty('description'); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx index fedb43812d3d0..db5378982d646 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx @@ -59,7 +59,7 @@ const conjunctions: Record = { ), }; -export const setupGetConjunctionSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetConjunctionSuggestions: KqlQuerySuggestionProvider = (core) => { return (querySuggestionsArgs, { text, end }) => { let suggestions: QuerySuggestion[] | [] = []; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts index 2e12ae672f367..8751f7aee8123 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts @@ -110,7 +110,7 @@ describe('Kuery field suggestions', () => { mockKueryNode({ prefix, suffix }) ); expect(suggestions.length).toBeGreaterThan(0); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(suggestion).toHaveProperty('description'); }); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx index ca045c929f6a1..a8b5cc98c614f 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx @@ -30,24 +30,26 @@ const getDescription = (field: IFieldType) => { const keywordComparator = (first: IFieldType, second: IFieldType) => { const extensions = ['raw', 'keyword']; - if (extensions.map(ext => `${first.name}.${ext}`).includes(second.name)) { + if (extensions.map((ext) => `${first.name}.${ext}`).includes(second.name)) { return 1; - } else if (extensions.map(ext => `${second.name}.${ext}`).includes(first.name)) { + } else if (extensions.map((ext) => `${second.name}.${ext}`).includes(first.name)) { return -1; } return first.name.localeCompare(second.name); }; -export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = ( + core +) => { return ({ indexPatterns }, { start, end, prefix, suffix, nestedPath = '' }) => { const allFields = flatten( - indexPatterns.map(indexPattern => { + indexPatterns.map((indexPattern) => { return indexPattern.fields.filter(indexPatternsUtils.isFilterable); }) ); const search = `${prefix}${suffix}`.trim().toLowerCase(); - const matchingFields = allFields.filter(field => { + const matchingFields = allFields.filter((field) => { return ( (!nestedPath || (nestedPath && @@ -60,7 +62,7 @@ export const setupGetFieldSuggestions: KqlQuerySuggestionProvider { + const suggestions: QuerySuggestionField[] = sortedFields.map((field) => { const remainingPath = field.subType && field.subType.nested ? field.subType.nested.path.slice(nestedPath ? nestedPath.length + 1 : 0) diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts index 46fa7c68cee3e..546dc6361826a 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts @@ -51,7 +51,7 @@ export const setupKqlQuerySuggestionProvider = (core: CoreSetup): QuerySuggestio } }; - return querySuggestionsArgs => { + return (querySuggestionsArgs) => { const { query, selectionStart, selectionEnd } = querySuggestionsArgs; const cursoredQuery = `${query.substr(0, selectionStart)}${cursorSymbol}${query.substr( selectionEnd @@ -59,6 +59,6 @@ export const setupKqlQuerySuggestionProvider = (core: CoreSetup): QuerySuggestio return Promise.all( getSuggestionsByType(cursoredQuery, querySuggestionsArgs) - ).then(suggestionsByType => dedup(flatten(suggestionsByType))); + ).then((suggestionsByType) => dedup(flatten(suggestionsByType))); }; }; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts index a00082f8c7d7c..2ddb3966bb560 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts @@ -28,8 +28,5 @@ function escapeNot(str: string) { // See the Space rule in kuery.peg function escapeWhitespace(str: string) { - return str - .replace(/\t/g, '\\t') - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n'); + return str.replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n'); } diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts index f7ffe1c2fec68..183ef2858a2b2 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts @@ -76,7 +76,7 @@ describe('Kuery operator suggestions', () => { expect(suggestions.length).toBeGreaterThan(0); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(suggestion).toHaveProperty('description'); }); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx index 14c42d73f8d0b..47990db82f1a2 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx @@ -148,21 +148,21 @@ const getDescription = (operator: string) =>

{getOperatorByName(operator).des export const setupGetOperatorSuggestions: KqlQuerySuggestionProvider = () => { return ({ indexPatterns }, { end, fieldName, nestedPath }) => { const allFields = flatten( - indexPatterns.map(indexPattern => { + indexPatterns.map((indexPattern) => { return indexPattern.fields.slice(); }) ); const fullFieldName = nestedPath ? `${nestedPath}.${fieldName}` : fieldName; const fields = allFields - .filter(field => field.name === fullFieldName) - .map(field => { - const matchingOperators = Object.keys(operators).filter(operator => { + .filter((field) => field.name === fullFieldName) + .map((field) => { + const matchingOperators = Object.keys(operators).filter((operator) => { const { fieldTypes } = getOperatorByName(operator); return !fieldTypes || fieldTypes.includes(field.type); }); - const suggestions = matchingOperators.map(operator => ({ + const suggestions = matchingOperators.map((operator) => ({ type: QuerySuggestionTypes.Operator, text: operator + ' ', description: getDescription(operator), diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts index 03e1a9099f1ab..a8e2a83c57f75 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts @@ -12,7 +12,7 @@ export function sortPrefixFirst(array: any[], prefix?: string | number, property } const lowerCasePrefix = ('' + prefix).toLowerCase(); - const partitions = partition(array, entry => { + const partitions = partition(array, (entry) => { const value = ('' + (property ? entry[property] : entry)).toLowerCase(); return value.startsWith(lowerCasePrefix); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts index bfd1e13ad9c39..6f9ba4d00109d 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts @@ -15,22 +15,22 @@ import { const wrapAsSuggestions = (start: number, end: number, query: string, values: string[]) => values - .filter(value => value.toLowerCase().includes(query.toLowerCase())) - .map(value => ({ + .filter((value) => value.toLowerCase().includes(query.toLowerCase())) + .map((value) => ({ type: QuerySuggestionTypes.Value, text: `${value} `, start, end, })); -export const setupGetValueSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetValueSuggestions: KqlQuerySuggestionProvider = (core) => { return async ( { indexPatterns, boolFilter, signal }, { start, end, prefix, suffix, fieldName, nestedPath } ): Promise => { const allFields = flatten( - indexPatterns.map(indexPattern => - indexPattern.fields.map(field => ({ + indexPatterns.map((indexPattern) => + indexPattern.fields.map((field) => ({ ...field, indexPattern, })) @@ -38,20 +38,20 @@ export const setupGetValueSuggestions: KqlQuerySuggestionProvider = core => { ); const fullFieldName = nestedPath ? `${nestedPath}.${fieldName}` : fieldName; - const fields = allFields.filter(field => field.name === fullFieldName); + const fields = allFields.filter((field) => field.name === fullFieldName); const query = `${prefix}${suffix}`.trim(); const { getValueSuggestions } = getAutocompleteService(); const data = await Promise.all( - fields.map(field => + fields.map((field) => getValueSuggestions({ indexPattern: field.indexPattern, field, query, boolFilter, signal, - }).then(valueSuggestions => { - const quotedValues = valueSuggestions.map(value => + }).then((valueSuggestions) => { + const quotedValues = valueSuggestions.map((value) => typeof value === 'string' ? `"${escapeQuotes(value)}"` : `${value}` ); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index 1e554d3ff2d86..8df3114a8472a 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -11,7 +11,7 @@ import { CoreStart } from 'kibana/public'; jest.useFakeTimers(); -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); const mockSearch = jest.fn(); let searchInterceptor: EnhancedSearchInterceptor; let mockCoreStart: MockedKeys; diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index 472d39179b468..a4cf324f9d475 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -34,7 +34,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { */ public runBeyondTimeout = () => { this.hideToast(); - this.timeoutSubscriptions.forEach(subscription => subscription.unsubscribe()); + this.timeoutSubscriptions.forEach((subscription) => subscription.unsubscribe()); this.timeoutSubscriptions.clear(); }; diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts index bf502889ffa4f..15f2ca10af7f7 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts @@ -45,7 +45,7 @@ export const enhancedEsSearchStrategyProvider: TSearchStrategyProvider = async id => { + const cancel: ISearchCancel = async (id) => { const method = 'DELETE'; const path = encodeURI(`/_async_search/${id}`); await caller('transport.request', { method, path }); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx index 152eaf18f16c1..0f7f0cb22760b 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx @@ -136,7 +136,7 @@ test('Can delete multiple drilldowns', async () => { const checkboxes = screen.getAllByLabelText(/Select this drilldown/i); expect(checkboxes).toHaveLength(3); - checkboxes.forEach(checkbox => fireEvent.click(checkbox)); + checkboxes.forEach((checkbox) => fireEvent.click(checkbox)); expect(screen.queryByText(/Create/i)).not.toBeInTheDocument(); fireEvent.click(screen.getByText(/Delete \(3\)/i)); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx index ba273e7d578ff..3c9d2d2a86fb1 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx @@ -115,7 +115,7 @@ export function createFlyoutManageDrilldowns({ function resolveInitialDrilldownWizardConfig(): DrilldownWizardConfig | undefined { if (route !== Routes.Edit) return undefined; if (!currentEditId) return undefined; - const drilldownToEdit = drilldowns?.find(d => d.eventId === currentEditId); + const drilldownToEdit = drilldowns?.find((d) => d.eventId === currentEditId); if (!drilldownToEdit) return undefined; return { @@ -200,11 +200,11 @@ export function createFlyoutManageDrilldowns({ showWelcomeMessage={shouldShowWelcomeMessage} onWelcomeHideClick={onHideWelcomeMessage} drilldowns={drilldowns.map(mapToDrilldownToDrilldownListItem)} - onDelete={ids => { + onDelete={(ids) => { setCurrentEditId(null); deleteDrilldown(ids); }} - onEdit={id => { + onEdit={(id) => { setCurrentEditId(id); setRoute(Routes.Edit); }} @@ -228,7 +228,7 @@ function useCompatibleActionFactoriesForCurrentContext factory.isCompatible(context)) + actionFactories.map((factory) => factory.isCompatible(context)) ); if (canceled) return; setCompatibleActionFactories(actionFactories.filter((_, i) => compatibility[i])); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts index 47a04222286cb..c9cb0b0eb1cb3 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts @@ -48,8 +48,8 @@ class MockDynamicActionManager implements PublicMethodsOf const state = this.state.get(); let events = state.events; - eventIds.forEach(id => { - events = events.filter(e => e.eventId !== id); + eventIds.forEach((id) => { + events = events.filter((e) => e.eventId !== id); }); this.state.set({ @@ -65,7 +65,7 @@ class MockDynamicActionManager implements PublicMethodsOf ) { const state = this.state.get(); const events = state.events; - const idx = events.findIndex(e => e.eventId === eventId); + const idx = events.findIndex((e) => e.eventId === eventId); const event = { eventId, action, diff --git a/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx b/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx index 3bed81a971921..38168377b02bd 100644 --- a/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx +++ b/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx @@ -45,7 +45,7 @@ export const FormDrilldownWizard: React.FC = ({ placeholder={txtUntitledDrilldown} value={name} disabled={onNameChange === noopFn} - onChange={event => onNameChange(event.target.value)} + onChange={(event) => onNameChange(event.target.value)} data-test-subj="drilldownNameInput" /> @@ -60,8 +60,8 @@ export const FormDrilldownWizard: React.FC = ({ actionFactories={actionFactories} currentActionFactory={currentActionFactory} config={actionConfig} - onActionFactoryChange={actionFactory => onActionFactoryChange(actionFactory)} - onConfigChange={config => onActionConfigChange(config)} + onActionFactoryChange={(actionFactory) => onActionFactoryChange(actionFactory)} + onConfigChange={(config) => onActionConfigChange(config)} context={actionFactoryContext} /> diff --git a/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx b/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx index ab51c0a829ed3..cd41a3d6ec23a 100644 --- a/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx +++ b/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx @@ -92,8 +92,8 @@ export function ListManageDrilldowns({ isSelectable={true} responsive={false} selection={{ - onSelectionChange: selection => { - setSelectedDrilldowns(selection.map(drilldown => drilldown.id)); + onSelectionChange: (selection) => { + setSelectedDrilldowns(selection.map((drilldown) => drilldown.id)); }, selectableMessage: () => txtSelectDrilldown, }} diff --git a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts index dcb44323f6d11..e93674ba650a7 100644 --- a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts +++ b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts @@ -78,7 +78,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async remove(eventId: string) { const input = this.embbeddable.getInput(); const events = input.enhancements?.dynamicActions?.events || []; - const index = events.findIndex(event => eventId === event.eventId); + const index = events.findIndex((event) => eventId === event.eventId); if (index === -1) { throw new Error( @@ -94,7 +94,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async read(eventId: string): Promise { const input = this.embbeddable.getInput(); const events = input.enhancements?.dynamicActions?.events || []; - const event = events.find(ev => eventId === ev.eventId); + const event = events.find((ev) => eventId === ev.eventId); if (!event) { throw new Error( diff --git a/x-pack/plugins/embeddable_enhanced/public/plugin.ts b/x-pack/plugins/embeddable_enhanced/public/plugin.ts index d48c4f9e860cc..d26acb4459a71 100644 --- a/x-pack/plugins/embeddable_enhanced/public/plugin.ts +++ b/x-pack/plugins/embeddable_enhanced/public/plugin.ts @@ -126,7 +126,7 @@ export class EmbeddableEnhancedPlugin uiActions: this.uiActions!, }); - dynamicActions.start().catch(error => { + dynamicActions.start().catch((error) => { /* eslint-disable */ console.log('Failed to start embeddable dynamic actions', embeddable); console.error(error); @@ -134,7 +134,7 @@ export class EmbeddableEnhancedPlugin }); const stop = () => { - dynamicActions.stop().catch(error => { + dynamicActions.stop().catch((error) => { /* eslint-disable */ console.log('Failed to stop embeddable dynamic actions', embeddable); console.error(error); diff --git a/x-pack/plugins/encrypted_saved_objects/server/config.test.ts b/x-pack/plugins/encrypted_saved_objects/server/config.test.ts index 8f74c461a2a9b..db07f0f9ce2c0 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/config.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/config.test.ts @@ -54,9 +54,7 @@ describe('createConfig$()', () => { mockRandomBytes.mockReturnValue('ab'.repeat(16)); const contextMock = coreMock.createPluginInitializerContext({}); - const config = await createConfig$(contextMock) - .pipe(first()) - .toPromise(); + const config = await createConfig$(contextMock).pipe(first()).toPromise(); expect(config).toEqual({ config: { encryptionKey: 'ab'.repeat(16) }, usingEphemeralEncryptionKey: true, @@ -75,9 +73,7 @@ describe('createConfig$()', () => { const contextMock = coreMock.createPluginInitializerContext({ encryptionKey: 'supersecret', }); - const config = await createConfig$(contextMock) - .pipe(first()) - .toPromise(); + const config = await createConfig$(contextMock).pipe(first()).toPromise(); expect(config).toEqual({ config: { encryptionKey: 'supersecret' }, usingEphemeralEncryptionKey: false, diff --git a/x-pack/plugins/encrypted_saved_objects/server/config.ts b/x-pack/plugins/encrypted_saved_objects/server/config.ts index 2f01850520724..9c751a9c67f52 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/config.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/config.ts @@ -21,7 +21,7 @@ export const ConfigSchema = schema.object({ export function createConfig$(context: PluginInitializerContext) { return context.config.create>().pipe( - map(config => { + map((config) => { const logger = context.logger.get('config'); let encryptionKey = config.encryptionKey; diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts index de0a089ab8c66..11a0cd6f33307 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts @@ -21,7 +21,7 @@ export const encryptedSavedObjectsServiceMock = { attrs: T, action: (attrs: T, attrName: string, shouldExpose: boolean) => void ) { - const registration = registrations.find(r => r.type === descriptor.type); + const registration = registrations.find((r) => r.type === descriptor.type); if (!registration) { return attrs; } @@ -40,7 +40,7 @@ export const encryptedSavedObjectsServiceMock = { } mock.isRegistered.mockImplementation( - type => registrations.findIndex(r => r.type === type) >= 0 + (type) => registrations.findIndex((r) => r.type === type) >= 0 ); mock.encryptAttributes.mockImplementation(async (descriptor, attrs) => processAttributes( diff --git a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts index d5550703cf761..38ac8f254315e 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts @@ -18,7 +18,7 @@ function createEncryptedSavedObjectsSetupMock() { function createEncryptedSavedObjectsStartMock() { return { isEncryptionError: jest.fn(), - getClient: jest.fn(opts => createEncryptedSavedObjectsClienttMock(opts)), + getClient: jest.fn((opts) => createEncryptedSavedObjectsClienttMock(opts)), } as jest.Mocked; } diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts index 8a4e78288e411..7098f611defa0 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts @@ -450,7 +450,7 @@ describe('#bulkUpdate', () => { ]; const mockedResponse = { - saved_objects: docs.map(doc => ({ + saved_objects: docs.map((doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -465,7 +465,7 @@ describe('#bulkUpdate', () => { await expect( wrapper.bulkUpdate( - docs.map(doc => ({ ...doc })), + docs.map((doc) => ({ ...doc })), {} ) ).resolves.toEqual({ @@ -558,7 +558,7 @@ describe('#bulkUpdate', () => { const options = { namespace }; mockBaseClient.bulkUpdate.mockResolvedValue({ - saved_objects: docs.map(doc => ({ ...doc, references: undefined })), + saved_objects: docs.map((doc) => ({ ...doc, references: undefined })), }); await expect(wrapper.bulkUpdate(docs, options)).resolves.toEqual({ diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts index 7ba8ef3eaad8b..bdc2b6cb2e667 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts @@ -94,7 +94,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon // NodeJS thread pool. If it turns out to be a problem, we can consider switching to the // sequential processing. const encryptedObjects = await Promise.all( - objects.map(async object => { + objects.map(async (object) => { if (!this.options.service.isRegistered(object.type)) { return object; } @@ -137,7 +137,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon // NodeJS thread pool. If it turns out to be a problem, we can consider switching to the // sequential processing. const encryptedObjects = await Promise.all( - objects.map(async object => { + objects.map(async (object) => { const { type, id, attributes } = object; if (!this.options.service.isRegistered(type)) { return object; diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts index 9ab3e85cc8624..af00050183b77 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts @@ -62,7 +62,7 @@ export function setupSavedObjects({ }) ); - return clientOpts => { + return (clientOpts) => { const internalRepositoryAndTypeRegistryPromise = getStartServices().then( ([core]) => [ diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts index 66c16d0ddf383..0144e573fc146 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts @@ -301,9 +301,7 @@ describe('queryEventsBySavedObject', () => { }, }); - const start = moment() - .subtract(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); await clusterClientAdapter.queryEventsBySavedObject( 'index-name', @@ -374,12 +372,8 @@ describe('queryEventsBySavedObject', () => { }, }); - const start = moment() - .subtract(1, 'days') - .toISOString(); - const end = moment() - .add(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); + const end = moment().add(1, 'days').toISOString(); await clusterClientAdapter.queryEventsBySavedObject( 'index-name', diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts index c0ff87234c09d..7fd239ca49369 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts @@ -206,7 +206,7 @@ export class ClusterClientAdapter { page, per_page: perPage, total, - data: hits.map(hit => hit._source) as IEvent[], + data: hits.map((hit) => hit._source) as IEvent[], }; } catch (err) { throw new Error( diff --git a/x-pack/plugins/event_log/server/event_log_client.test.ts b/x-pack/plugins/event_log/server/event_log_client.test.ts index 17c073c4b27f9..16e5fa69d36f6 100644 --- a/x-pack/plugins/event_log/server/event_log_client.test.ts +++ b/x-pack/plugins/event_log/server/event_log_client.test.ts @@ -172,12 +172,8 @@ describe('EventLogStart', () => { }; esContext.esAdapter.queryEventsBySavedObject.mockResolvedValue(result); - const start = moment() - .subtract(1, 'days') - .toISOString(); - const end = moment() - .add(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); + const end = moment().add(1, 'days').toISOString(); expect( await eventLogClient.findEventsBySavedObject('saved-object-type', 'saved-object-id', { diff --git a/x-pack/plugins/event_log/server/lib/delay.ts b/x-pack/plugins/event_log/server/lib/delay.ts index a37569baaf692..1c64141c15fb2 100644 --- a/x-pack/plugins/event_log/server/lib/delay.ts +++ b/x-pack/plugins/event_log/server/lib/delay.ts @@ -5,5 +5,5 @@ */ export async function delay(millis: number) { - await new Promise(resolve => setTimeout(resolve, millis)); + await new Promise((resolve) => setTimeout(resolve, millis)); } diff --git a/x-pack/plugins/event_log/server/lib/ready_signal.test.ts b/x-pack/plugins/event_log/server/lib/ready_signal.test.ts index 6f1d92034c06f..c216651ee94b1 100644 --- a/x-pack/plugins/event_log/server/lib/ready_signal.test.ts +++ b/x-pack/plugins/event_log/server/lib/ready_signal.test.ts @@ -13,7 +13,7 @@ describe('ReadySignal', () => { readySignal = createReadySignal(); }); - test('works as expected', async done => { + test('works as expected', async (done) => { let value = 41; timeoutSet(100, async () => { diff --git a/x-pack/plugins/event_log/server/lib/ready_signal.ts b/x-pack/plugins/event_log/server/lib/ready_signal.ts index 2ea8e655089da..58879649b83cb 100644 --- a/x-pack/plugins/event_log/server/lib/ready_signal.ts +++ b/x-pack/plugins/event_log/server/lib/ready_signal.ts @@ -12,7 +12,7 @@ export interface ReadySignal { export function createReadySignal(): ReadySignal { let resolver: (value: T) => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolver = resolve; }); diff --git a/x-pack/plugins/event_log/server/routes/find.ts b/x-pack/plugins/event_log/server/routes/find.ts index f8e1c842ae436..e03aef7c757f6 100644 --- a/x-pack/plugins/event_log/server/routes/find.ts +++ b/x-pack/plugins/event_log/server/routes/find.ts @@ -29,7 +29,7 @@ export const findRoute = (router: IRouter) => { query: findOptionsSchema, }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, FindOptionsType, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/features/common/feature.ts b/x-pack/plugins/features/common/feature.ts index ef32a8a80a0bd..1b405094d9eda 100644 --- a/x-pack/plugins/features/common/feature.ts +++ b/x-pack/plugins/features/common/feature.ts @@ -133,7 +133,7 @@ export class Feature { constructor(protected readonly config: RecursiveReadonly) { this.subFeatures = (config.subFeatures ?? []).map( - subFeatureConfig => new SubFeature(subFeatureConfig) + (subFeatureConfig) => new SubFeature(subFeatureConfig) ); } diff --git a/x-pack/plugins/features/public/features_api_client.test.ts b/x-pack/plugins/features/public/features_api_client.test.ts index e3a25ad57425c..95f0c2d527d34 100644 --- a/x-pack/plugins/features/public/features_api_client.test.ts +++ b/x-pack/plugins/features/public/features_api_client.test.ts @@ -32,7 +32,7 @@ describe('Features API Client', () => { const client = new FeaturesAPIClient(coreSetup.http); const result = await client.getFeatures(); - expect(result.map(f => f.id)).toEqual([ + expect(result.map((f) => f.id)).toEqual([ 'feature-a', 'feature-b', 'feature-c', diff --git a/x-pack/plugins/features/public/features_api_client.ts b/x-pack/plugins/features/public/features_api_client.ts index b93c9bf917d79..50cc54a197f56 100644 --- a/x-pack/plugins/features/public/features_api_client.ts +++ b/x-pack/plugins/features/public/features_api_client.ts @@ -12,6 +12,6 @@ export class FeaturesAPIClient { public async getFeatures() { const features = await this.http.get('/api/features'); - return features.map(config => new Feature(config)); + return features.map((config) => new Feature(config)); } } diff --git a/x-pack/plugins/features/server/feature_registry.test.ts b/x-pack/plugins/features/server/feature_registry.test.ts index 2039f8f6acda2..75022922917b3 100644 --- a/x-pack/plugins/features/server/feature_registry.test.ts +++ b/x-pack/plugins/features/server/feature_registry.test.ts @@ -353,7 +353,7 @@ describe('FeatureRegistry', () => { ); }); - ['contains space', 'contains_invalid()_chars', ''].forEach(prohibitedChars => { + ['contains space', 'contains_invalid()_chars', ''].forEach((prohibitedChars) => { it(`prevents features from being registered with a navLinkId of "${prohibitedChars}"`, () => { const featureRegistry = new FeatureRegistry(); expect(() => @@ -396,7 +396,7 @@ describe('FeatureRegistry', () => { }); }); - ['catalogue', 'management', 'navLinks', `doesn't match valid regex`].forEach(prohibitedId => { + ['catalogue', 'management', 'navLinks', `doesn't match valid regex`].forEach((prohibitedId) => { it(`prevents features from being registered with an ID of "${prohibitedId}"`, () => { const featureRegistry = new FeatureRegistry(); expect(() => diff --git a/x-pack/plugins/features/server/feature_registry.ts b/x-pack/plugins/features/server/feature_registry.ts index 6140b7ac87ce0..12aafd226f754 100644 --- a/x-pack/plugins/features/server/feature_registry.ts +++ b/x-pack/plugins/features/server/feature_registry.ts @@ -32,14 +32,14 @@ export class FeatureRegistry { public getAll(): Feature[] { this.locked = true; - return Object.values(this.features).map(featureConfig => new Feature(featureConfig)); + return Object.values(this.features).map((featureConfig) => new Feature(featureConfig)); } } function applyAutomaticPrivilegeGrants(feature: FeatureConfig): FeatureConfig { const allPrivilege = feature.privileges?.all; const readPrivilege = feature.privileges?.read; - const reservedPrivileges = (feature.reserved?.privileges ?? []).map(rp => rp.privilege); + const reservedPrivileges = (feature.reserved?.privileges ?? []).map((rp) => rp.privilege); applyAutomaticAllPrivilegeGrants(allPrivilege, ...reservedPrivileges); applyAutomaticReadPrivilegeGrants(readPrivilege); @@ -50,7 +50,7 @@ function applyAutomaticPrivilegeGrants(feature: FeatureConfig): FeatureConfig { function applyAutomaticAllPrivilegeGrants( ...allPrivileges: Array ) { - allPrivileges.forEach(allPrivilege => { + allPrivileges.forEach((allPrivilege) => { if (allPrivilege) { allPrivilege.savedObject.all = uniq([...allPrivilege.savedObject.all, 'telemetry']); allPrivilege.savedObject.read = uniq([...allPrivilege.savedObject.read, 'config', 'url']); @@ -61,7 +61,7 @@ function applyAutomaticAllPrivilegeGrants( function applyAutomaticReadPrivilegeGrants( ...readPrivileges: Array ) { - readPrivileges.forEach(readPrivilege => { + readPrivileges.forEach((readPrivilege) => { if (readPrivilege) { readPrivilege.savedObject.read = uniq([...readPrivilege.savedObject.read, 'config', 'url']); } diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index 403d9586bf160..7497548cf8904 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -34,53 +34,33 @@ const privilegeSchema = Joi.object({ api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), savedObject: Joi.object({ - all: Joi.array() - .items(Joi.string()) - .required(), - read: Joi.array() - .items(Joi.string()) - .required(), + all: Joi.array().items(Joi.string()).required(), + read: Joi.array().items(Joi.string()).required(), }).required(), - ui: Joi.array() - .items(Joi.string().regex(uiCapabilitiesRegex)) - .required(), + ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), }); const subFeaturePrivilegeSchema = Joi.object({ - id: Joi.string() - .regex(subFeaturePrivilegePartRegex) - .required(), + id: Joi.string().regex(subFeaturePrivilegePartRegex).required(), name: Joi.string().required(), - includeIn: Joi.string() - .allow('all', 'read', 'none') - .required(), + includeIn: Joi.string().allow('all', 'read', 'none').required(), management: managementSchema, catalogue: catalogueSchema, api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), savedObject: Joi.object({ - all: Joi.array() - .items(Joi.string()) - .required(), - read: Joi.array() - .items(Joi.string()) - .required(), + all: Joi.array().items(Joi.string()).required(), + read: Joi.array().items(Joi.string()).required(), }).required(), - ui: Joi.array() - .items(Joi.string().regex(uiCapabilitiesRegex)) - .required(), + ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), }); const subFeatureSchema = Joi.object({ name: Joi.string().required(), privilegeGroups: Joi.array().items( Joi.object({ - groupType: Joi.string() - .valid('mutually_exclusive', 'independent') - .required(), - privileges: Joi.array() - .items(subFeaturePrivilegeSchema) - .min(1), + groupType: Joi.string().valid('mutually_exclusive', 'independent').required(), + privileges: Joi.array().items(subFeaturePrivilegeSchema).min(1), }) ), }); @@ -99,9 +79,7 @@ const schema = Joi.object({ icon: Joi.string(), description: Joi.string(), navLinkId: Joi.string().regex(uiCapabilitiesRegex), - app: Joi.array() - .items(Joi.string()) - .required(), + app: Joi.array().items(Joi.string()).required(), management: managementSchema, catalogue: catalogueSchema, privileges: Joi.object({ @@ -112,9 +90,7 @@ const schema = Joi.object({ .required(), subFeatures: Joi.when('privileges', { is: null, - then: Joi.array() - .items(subFeatureSchema) - .max(0), + then: Joi.array().items(subFeatureSchema).max(0), otherwise: Joi.array().items(subFeatureSchema), }), privilegesTooltip: Joi.string(), @@ -123,9 +99,7 @@ const schema = Joi.object({ privileges: Joi.array() .items( Joi.object({ - id: Joi.string() - .regex(reservedFeaturePrrivilegePartRegex) - .required(), + id: Joi.string().regex(reservedFeaturePrrivilegePartRegex).required(), privilege: privilegeSchema.required(), }) ) @@ -143,7 +117,7 @@ export function validateFeature(feature: FeatureConfig) { const unseenApps = new Set(app); - const managementSets = Object.entries(management).map(entry => [ + const managementSets = Object.entries(management).map((entry) => [ entry[0], new Set(entry[1]), ]) as Array<[string, Set]>; @@ -153,7 +127,7 @@ export function validateFeature(feature: FeatureConfig) { const unseenCatalogue = new Set(catalogue); function validateAppEntry(privilegeId: string, entry: string[] = []) { - entry.forEach(privilegeApp => unseenApps.delete(privilegeApp)); + entry.forEach((privilegeApp) => unseenApps.delete(privilegeApp)); const unknownAppEntries = difference(entry, app); if (unknownAppEntries.length > 0) { @@ -166,7 +140,7 @@ export function validateFeature(feature: FeatureConfig) { } function validateCatalogueEntry(privilegeId: string, entry: string[] = []) { - entry.forEach(privilegeCatalogue => unseenCatalogue.delete(privilegeCatalogue)); + entry.forEach((privilegeCatalogue) => unseenCatalogue.delete(privilegeCatalogue)); const unknownCatalogueEntries = difference(entry || [], catalogue); if (unknownCatalogueEntries.length > 0) { @@ -184,7 +158,7 @@ export function validateFeature(feature: FeatureConfig) { ) { Object.entries(managementEntry).forEach(([managementSectionId, managementSectionEntry]) => { if (unseenManagement.has(managementSectionId)) { - managementSectionEntry.forEach(entry => { + managementSectionEntry.forEach((entry) => { unseenManagement.get(managementSectionId)!.delete(entry); if (unseenManagement.get(managementSectionId)?.size === 0) { unseenManagement.delete(managementSectionId); @@ -219,7 +193,7 @@ export function validateFeature(feature: FeatureConfig) { privilegeEntries.push(...Object.entries(feature.privileges)); } if (feature.reserved) { - feature.reserved.privileges.forEach(reservedPrivilege => { + feature.reserved.privileges.forEach((reservedPrivilege) => { privilegeEntries.push([reservedPrivilege.id, reservedPrivilege.privilege]); }); } @@ -241,9 +215,9 @@ export function validateFeature(feature: FeatureConfig) { }); const subFeatureEntries = feature.subFeatures ?? []; - subFeatureEntries.forEach(subFeature => { - subFeature.privilegeGroups.forEach(subFeaturePrivilegeGroup => { - subFeaturePrivilegeGroup.privileges.forEach(subFeaturePrivilege => { + subFeatureEntries.forEach((subFeature) => { + subFeature.privilegeGroups.forEach((subFeaturePrivilegeGroup) => { + subFeaturePrivilegeGroup.privileges.forEach((subFeaturePrivilege) => { validateAppEntry(subFeaturePrivilege.id, subFeaturePrivilege.app); validateCatalogueEntry(subFeaturePrivilege.id, subFeaturePrivilege.catalogue); validateManagementEntry(subFeaturePrivilege.id, subFeaturePrivilege.management); @@ -274,7 +248,7 @@ export function validateFeature(feature: FeatureConfig) { if (unseenManagement.size > 0) { const ungrantedManagement = Array.from(unseenManagement.entries()).reduce((acc, entry) => { const values = Array.from(entry[1].values()).map( - managementPage => `${entry[0]}.${managementPage}` + (managementPage) => `${entry[0]}.${managementPage}` ); return [...acc, ...values]; }, [] as string[]); diff --git a/x-pack/plugins/features/server/oss_features.test.ts b/x-pack/plugins/features/server/oss_features.test.ts index 72beff02173d2..c38f2afc88389 100644 --- a/x-pack/plugins/features/server/oss_features.test.ts +++ b/x-pack/plugins/features/server/oss_features.test.ts @@ -11,7 +11,7 @@ import { Feature } from '.'; describe('buildOSSFeatures', () => { it('returns features including timelion', () => { expect( - buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }).map(f => f.id) + buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }).map((f) => f.id) ).toMatchInlineSnapshot(` Array [ "discover", @@ -28,7 +28,9 @@ Array [ it('returns features excluding timelion', () => { expect( - buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: false }).map(f => f.id) + buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: false }).map( + (f) => f.id + ) ).toMatchInlineSnapshot(` Array [ "discover", @@ -43,7 +45,7 @@ Array [ }); const features = buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }); - features.forEach(featureConfig => { + features.forEach((featureConfig) => { it(`returns the ${featureConfig.id} feature augmented with appropriate sub feature privileges`, () => { const privileges = []; for (const featurePrivilege of featurePrivilegeIterator(new Feature(featureConfig), { diff --git a/x-pack/plugins/features/server/plugin.test.ts b/x-pack/plugins/features/server/plugin.test.ts index 3d7cf19e58b0e..79fd012337b00 100644 --- a/x-pack/plugins/features/server/plugin.test.ts +++ b/x-pack/plugins/features/server/plugin.test.ts @@ -39,7 +39,7 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); - expect(getFeatures().map(f => f.id)).toMatchInlineSnapshot(` + expect(getFeatures().map((f) => f.id)).toMatchInlineSnapshot(` Array [ "baz", "discover", @@ -67,7 +67,7 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); - expect(getFeatures().map(f => f.id)).toMatchInlineSnapshot(` + expect(getFeatures().map((f) => f.id)).toMatchInlineSnapshot(` Array [ "baz", "discover", @@ -88,8 +88,8 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); const soTypes = - getFeatures().find(f => f.id === 'savedObjectsManagement')?.privileges?.all.savedObject.all || - []; + getFeatures().find((f) => f.id === 'savedObjectsManagement')?.privileges?.all.savedObject + .all || []; expect(soTypes.includes('foo')).toBe(true); expect(soTypes.includes('bar')).toBe(false); diff --git a/x-pack/plugins/features/server/plugin.ts b/x-pack/plugins/features/server/plugin.ts index e3480eda9fe7d..bfae416471c2f 100644 --- a/x-pack/plugins/features/server/plugin.ts +++ b/x-pack/plugins/features/server/plugin.ts @@ -83,8 +83,8 @@ export class Plugin { const registry = savedObjects.getTypeRegistry(); const savedObjectTypes = registry .getAllTypes() - .filter(t => !t.hidden) - .map(t => t.name); + .filter((t) => !t.hidden) + .map((t) => t.name); this.logger.debug( `Registering OSS features with SO types: ${savedObjectTypes.join(', ')}. "includeTimelion": ${ diff --git a/x-pack/plugins/features/server/routes/index.test.ts b/x-pack/plugins/features/server/routes/index.test.ts index 67b28b27f931f..c2e8cd6129d80 100644 --- a/x-pack/plugins/features/server/routes/index.test.ts +++ b/x-pack/plugins/features/server/routes/index.test.ts @@ -74,7 +74,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { id: 'feature_3', @@ -103,7 +103,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { @@ -133,7 +133,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { @@ -163,7 +163,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { diff --git a/x-pack/plugins/features/server/routes/index.ts b/x-pack/plugins/features/server/routes/index.ts index d07b488693091..147d34d124fca 100644 --- a/x-pack/plugins/features/server/routes/index.ts +++ b/x-pack/plugins/features/server/routes/index.ts @@ -31,7 +31,7 @@ export function defineRoutes({ router, featureRegistry }: RouteDefinitionParams) return response.ok({ body: allFeatures .filter( - feature => + (feature) => request.query.ignoreValidLicenses || !feature.validLicenses || !feature.validLicenses.length || @@ -42,7 +42,7 @@ export function defineRoutes({ router, featureRegistry }: RouteDefinitionParams) (f1, f2) => (f1.order ?? Number.MAX_SAFE_INTEGER) - (f2.order ?? Number.MAX_SAFE_INTEGER) ) - .map(feature => feature.toRaw()), + .map((feature) => feature.toRaw()), }); } ); diff --git a/x-pack/plugins/features/server/ui_capabilities_for_features.ts b/x-pack/plugins/features/server/ui_capabilities_for_features.ts index e6ff3ad4383d2..e41035e9365ce 100644 --- a/x-pack/plugins/features/server/ui_capabilities_for_features.ts +++ b/x-pack/plugins/features/server/ui_capabilities_for_features.ts @@ -42,14 +42,14 @@ function getCapabilitiesFromFeature(feature: Feature): FeatureCapabilities { const featurePrivileges = Object.values(feature.privileges ?? {}); if (feature.subFeatures) { featurePrivileges.push( - ...feature.subFeatures.map(sf => sf.privilegeGroups.map(pg => pg.privileges)).flat(2) + ...feature.subFeatures.map((sf) => sf.privilegeGroups.map((pg) => pg.privileges)).flat(2) ); } if (feature.reserved?.privileges) { - featurePrivileges.push(...feature.reserved.privileges.map(rp => rp.privilege)); + featurePrivileges.push(...feature.reserved.privileges.map((rp) => rp.privilege)); } - featurePrivileges.forEach(privilege => { + featurePrivileges.forEach((privilege) => { UIFeatureCapabilities[feature.id] = { ...UIFeatureCapabilities[feature.id], ...privilege.ui.reduce( @@ -74,7 +74,7 @@ function buildCapabilities(...allFeatureCapabilities: FeatureCapabilities[]): UI ...acc, }; - ELIGIBLE_FLAT_MERGE_KEYS.forEach(key => { + ELIGIBLE_FLAT_MERGE_KEYS.forEach((key) => { mergedFeatureCapabilities[key] = { ...mergedFeatureCapabilities[key], ...capabilities[key], diff --git a/x-pack/plugins/file_upload/public/components/index_settings.js b/x-pack/plugins/file_upload/public/components/index_settings.js index 8a745f035a8ee..cb1e639e0fede 100644 --- a/x-pack/plugins/file_upload/public/components/index_settings.js +++ b/x-pack/plugins/file_upload/public/components/index_settings.js @@ -58,7 +58,7 @@ export class IndexSettings extends Component { } } - _setIndexName = async name => { + _setIndexName = async (name) => { const errorMessage = await this._isIndexNameAndPatternValid(name); return this.setState({ indexName: name, @@ -72,7 +72,7 @@ export class IndexSettings extends Component { this.props.setIndexName(name); }; - _isIndexNameAndPatternValid = async name => { + _isIndexNameAndPatternValid = async (name) => { const { indexNameList, indexPatternList } = this.state; const nameAlreadyInUse = [...indexNameList, ...indexPatternList].includes(name); if (nameAlreadyInUse) { @@ -113,7 +113,7 @@ export class IndexSettings extends Component { ({ + options={indexTypes.map((indexType) => ({ text: indexType, value: indexType, }))} diff --git a/x-pack/plugins/file_upload/public/components/json_index_file_picker.js b/x-pack/plugins/file_upload/public/components/json_index_file_picker.js index 67086883a9a32..4728efc5b8915 100644 --- a/x-pack/plugins/file_upload/public/components/json_index_file_picker.js +++ b/x-pack/plugins/file_upload/public/components/json_index_file_picker.js @@ -13,8 +13,8 @@ import { MAX_FILE_SIZE } from '../../common/constants/file_import'; import _ from 'lodash'; const ACCEPTABLE_FILETYPES = ['json', 'geojson']; -const acceptedFileTypeString = ACCEPTABLE_FILETYPES.map(type => `.${type}`).join(','); -const acceptedFileTypeStringMessage = ACCEPTABLE_FILETYPES.map(type => `.${type}`).join(', '); +const acceptedFileTypeString = ACCEPTABLE_FILETYPES.map((type) => `.${type}`).join(','); +const acceptedFileTypeStringMessage = ACCEPTABLE_FILETYPES.map((type) => `.${type}`).join(', '); export class JsonIndexFilePicker extends Component { state = { @@ -35,7 +35,7 @@ export class JsonIndexFilePicker extends Component { getFileParseActive = () => this._isMounted && this.state.fileParseActive; - _fileHandler = fileList => { + _fileHandler = (fileList) => { const fileArr = Array.from(fileList); this.props.resetFileAndIndexSettings(); this.setState({ @@ -168,7 +168,7 @@ export class JsonIndexFilePicker extends Component { onFileUpload, setFileProgress: this.setFileProgress, getFileParseActive: this.getFileParseActive, - }).catch(err => { + }).catch((err) => { if (this._isMounted) { this.setState({ fileParseActive: false, diff --git a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js index bcfb75e05a17f..453d4f84f7e0e 100644 --- a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js +++ b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js @@ -284,9 +284,9 @@ export class JsonUploadAndParse extends Component { {...{ onFileUpload, fileRef, - setIndexName: indexName => this.setState({ indexName }), - setFileRef: fileRef => this.setState({ fileRef }), - setParsedFile: parsedFile => this.setState({ parsedFile }), + setIndexName: (indexName) => this.setState({ indexName }), + setFileRef: (fileRef) => this.setState({ fileRef }), + setParsedFile: (parsedFile) => this.setState({ parsedFile }), transformDetails, resetFileAndIndexSettings: this._resetFileAndIndexSettings, }} @@ -294,10 +294,10 @@ export class JsonUploadAndParse extends Component { this.setState({ indexName })} + setIndexName={(indexName) => this.setState({ indexName })} indexTypes={indexTypes} - setSelectedIndexType={selectedIndexType => this.setState({ selectedIndexType })} - setHasIndexErrors={hasIndexErrors => this.setState({ hasIndexErrors })} + setSelectedIndexType={(selectedIndexType) => this.setState({ selectedIndexType })} + setHasIndexErrors={(hasIndexErrors) => this.setState({ hasIndexErrors })} /> )} diff --git a/x-pack/plugins/file_upload/public/util/file_parser.js b/x-pack/plugins/file_upload/public/util/file_parser.js index 2a0cef25f1678..e396b2b688a07 100644 --- a/x-pack/plugins/file_upload/public/util/file_parser.js +++ b/x-pack/plugins/file_upload/public/util/file_parser.js @@ -46,7 +46,7 @@ export const fileHandler = async ({ // Set up feature tracking let featuresProcessed = 0; - const onFeatureRead = feature => { + const onFeatureRead = (feature) => { // TODO: Add handling and tracking for cleanAndValidate fails featuresProcessed++; return cleanAndValidate(feature); @@ -58,7 +58,7 @@ export const fileHandler = async ({ prevFileReader = fileReader; const filePromise = new Promise((resolve, reject) => { - const onStreamComplete = fileResults => { + const onStreamComplete = (fileResults) => { if (!featuresProcessed) { reject( new Error( diff --git a/x-pack/plugins/file_upload/public/util/file_parser.test.js b/x-pack/plugins/file_upload/public/util/file_parser.test.js index fd467addfba82..5fbac6c7706a4 100644 --- a/x-pack/plugins/file_upload/public/util/file_parser.test.js +++ b/x-pack/plugins/file_upload/public/util/file_parser.test.js @@ -7,8 +7,8 @@ import { fileHandler } from './file_parser'; jest.mock('./pattern_reader', () => ({})); -const cleanAndValidate = jest.fn(a => a); -const setFileProgress = jest.fn(a => a); +const cleanAndValidate = jest.fn((a) => a); +const setFileProgress = jest.fn((a) => a); const getFileReader = () => { const fileReader = { @@ -24,7 +24,7 @@ const getPatternReader = () => { writeDataToPatternStream: jest.fn(), abortStream: jest.fn(), }; - require('./pattern_reader').PatternReader = function() { + require('./pattern_reader').PatternReader = function () { this.writeDataToPatternStream = () => patternReader.writeDataToPatternStream(); this.abortStream = () => patternReader.abortStream(); }; diff --git a/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js b/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js index 872df0cddca3c..e86a0fb4284d5 100644 --- a/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js +++ b/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js @@ -79,13 +79,13 @@ describe('geo_json_clean_and_validate', () => { // Confirm invalid geometry let geoJson = reader.read(badFeaturesGeoJson); let isSimpleOrValid; - geoJson.features.forEach(feature => { + geoJson.features.forEach((feature) => { isSimpleOrValid = feature.geometry.isSimple() || feature.geometry.isValid(); expect(isSimpleOrValid).toEqual(false); }); // Confirm changes to object - const cleanedFeatures = geoJson.features.map(feature => ({ + const cleanedFeatures = geoJson.features.map((feature) => ({ ...feature, geometry: cleanGeometry(feature), })); @@ -95,7 +95,7 @@ describe('geo_json_clean_and_validate', () => { // Confirm now valid features geometry geoJson = reader.read({ ...badFeaturesGeoJson, features: cleanedFeatures }); - geoJson.features.forEach(feature => { + geoJson.features.forEach((feature) => { isSimpleOrValid = feature.geometry.isSimple() || feature.geometry.isValid(); expect(isSimpleOrValid).toEqual(true); }); diff --git a/x-pack/plugins/file_upload/public/util/indexing_service.js b/x-pack/plugins/file_upload/public/util/indexing_service.js index bfaea00bc6694..eb22b0228b48a 100644 --- a/x-pack/plugins/file_upload/public/util/indexing_service.js +++ b/x-pack/plugins/file_upload/public/util/indexing_service.js @@ -217,7 +217,7 @@ async function getIndexPatternId(name) { const indexPatternSavedObjects = savedObjectSearch.savedObjects; if (indexPatternSavedObjects) { - const ip = indexPatternSavedObjects.find(i => i.attributes.title === name); + const ip = indexPatternSavedObjects.find((i) => i.attributes.title === name); return ip !== undefined ? ip.id : undefined; } else { return undefined; @@ -239,7 +239,7 @@ export const getExistingIndexPatternNames = async () => { fields: ['id', 'title', 'type', 'fields'], perPage: 10000, }) - .then(({ savedObjects }) => savedObjects.map(savedObject => savedObject.get('title'))); + .then(({ savedObjects }) => savedObjects.map((savedObject) => savedObject.get('title'))); return indexPatterns ? indexPatterns.map(({ name }) => name) : []; }; diff --git a/x-pack/plugins/file_upload/public/util/indexing_service.test.js b/x-pack/plugins/file_upload/public/util/indexing_service.test.js index f993ed0e1fd64..072079d3bbdd0 100644 --- a/x-pack/plugins/file_upload/public/util/indexing_service.test.js +++ b/x-pack/plugins/file_upload/public/util/indexing_service.test.js @@ -20,7 +20,7 @@ describe('indexing_service', () => { 'is.not.just.one.period', // name can't be . 'x'.repeat(255), // Cannot be longer than 255 bytes ]; - validNames.forEach(validName => { + validNames.forEach((validName) => { it(`Should validate index pattern: "${validName}"`, () => { const isValid = checkIndexPatternValid(validName); expect(isValid).toEqual(true); @@ -48,7 +48,7 @@ describe('indexing_service', () => { 'x'.repeat(256), // Cannot be longer than 255 bytes 'ü'.repeat(128), // Cannot be longer than 255 bytes (using 2 byte char) ]; - inValidNames.forEach(inValidName => { + inValidNames.forEach((inValidName) => { it(`Should invalidate index pattern: "${inValidName}"`, () => { const isValid = checkIndexPatternValid(inValidName); expect(isValid).toEqual(false); diff --git a/x-pack/plugins/file_upload/public/util/pattern_reader.js b/x-pack/plugins/file_upload/public/util/pattern_reader.js index 152e0f7e54580..bb7a0cab49884 100644 --- a/x-pack/plugins/file_upload/public/util/pattern_reader.js +++ b/x-pack/plugins/file_upload/public/util/pattern_reader.js @@ -21,7 +21,7 @@ export class PatternReader { _registerFeaturePatternHandler(featurePatternCallback) { this._oboeStream.node({ - 'features.*': feature => { + 'features.*': (feature) => { if (!feature.geometry || !feature.geometry.type) { // Only add this error once // TODO: Give feedback on which features failed @@ -48,7 +48,7 @@ export class PatternReader { } _registerStreamCompleteHandler(streamCompleteCallback) { - this._oboeStream.done(parsedGeojson => { + this._oboeStream.done((parsedGeojson) => { streamCompleteCallback({ parsedGeojson, errors: this.getErrors() }); }); } diff --git a/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js b/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js index 40f81d30725da..2fac441e8139d 100644 --- a/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js +++ b/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js @@ -14,7 +14,7 @@ describe('size_limited_chunking', () => { // Confirm valid geometry const chunkLimit = 100; const chunkedArr = sizeLimitedChunking(testArr, chunkLimit); - chunkedArr.forEach(sizeLimitedArr => { + chunkedArr.forEach((sizeLimitedArr) => { const arrByteSize = new Blob(sizeLimitedArr, { type: 'application/json' }).size; // Chunk size should be less than chunk limit diff --git a/x-pack/plugins/file_upload/server/client/call_with_request_factory.js b/x-pack/plugins/file_upload/server/client/call_with_request_factory.js index bef6c369fd9ac..3ff19a5b8f84d 100644 --- a/x-pack/plugins/file_upload/server/client/call_with_request_factory.js +++ b/x-pack/plugins/file_upload/server/client/call_with_request_factory.js @@ -9,7 +9,7 @@ import { getDataClient } from '../kibana_server_services'; const callWithRequest = once(() => getDataClient()); -export const callWithRequestFactory = request => { +export const callWithRequestFactory = (request) => { return (...args) => { return ( callWithRequest() diff --git a/x-pack/plugins/file_upload/server/kibana_server_services.js b/x-pack/plugins/file_upload/server/kibana_server_services.js index 104e49015ba80..880ea5caf31d3 100644 --- a/x-pack/plugins/file_upload/server/kibana_server_services.js +++ b/x-pack/plugins/file_upload/server/kibana_server_services.js @@ -6,13 +6,13 @@ let dataClient; -export const setElasticsearchClientServices = elasticsearch => { +export const setElasticsearchClientServices = (elasticsearch) => { ({ dataClient } = elasticsearch); }; export const getDataClient = () => dataClient; let internalRepository; -export const setInternalRepository = createInternalRepository => { +export const setInternalRepository = (createInternalRepository) => { internalRepository = createInternalRepository(); }; export const getInternalRepository = () => internalRepository; diff --git a/x-pack/plugins/file_upload/server/routes/file_upload.js b/x-pack/plugins/file_upload/server/routes/file_upload.js index d75f03132b404..cd5ccc57075a3 100644 --- a/x-pack/plugins/file_upload/server/routes/file_upload.js +++ b/x-pack/plugins/file_upload/server/routes/file_upload.js @@ -115,7 +115,7 @@ const finishValidationAndProcessReq = () => { }; }; -export const initRoutes = router => { +export const initRoutes = (router) => { router.post( { path: `${IMPORT_ROUTE}{id?}`, diff --git a/x-pack/plugins/graph/public/angular/graph_client_workspace.js b/x-pack/plugins/graph/public/angular/graph_client_workspace.js index bcd31716b6d64..cfa125fcc49ee 100644 --- a/x-pack/plugins/graph/public/angular/graph_client_workspace.js +++ b/x-pack/plugins/graph/public/angular/graph_client_workspace.js @@ -11,7 +11,7 @@ import d3 from 'd3'; // Pluggable function to handle the comms with a server. Default impl here is // for use outside of Kibana server with direct access to elasticsearch -let graphExplorer = function(indexName, typeName, request, responseHandler) { +let graphExplorer = function (indexName, typeName, request, responseHandler) { const dataForServer = JSON.stringify(request); $.ajax({ type: 'POST', @@ -20,12 +20,12 @@ let graphExplorer = function(indexName, typeName, request, responseHandler) { contentType: 'application/json;charset=utf-8', async: true, data: dataForServer, - success: function(data) { + success: function (data) { responseHandler(data); }, }); }; -let searcher = function(indexName, request, responseHandler) { +let searcher = function (indexName, request, responseHandler) { const dataForServer = JSON.stringify(request); $.ajax({ type: 'POST', @@ -34,7 +34,7 @@ let searcher = function(indexName, request, responseHandler) { contentType: 'application/json;charset=utf-8', //Not sure why this was necessary - worked without elsewhere async: true, data: dataForServer, - success: function(data) { + success: function (data) { responseHandler(data); }, }); @@ -46,14 +46,14 @@ function AddNodeOperation(node, owner) { const self = this; const vm = owner; self.node = node; - self.undo = function() { + self.undo = function () { vm.arrRemove(vm.nodes, self.node); vm.arrRemove(vm.selectedNodes, self.node); self.node.isSelected = false; delete vm.nodesMap[self.node.id]; }; - self.redo = function() { + self.redo = function () { vm.nodes.push(self.node); vm.nodesMap[self.node.id] = self.node; }; @@ -63,11 +63,11 @@ function AddEdgeOperation(edge, owner) { const self = this; const vm = owner; self.edge = edge; - self.undo = function() { + self.undo = function () { vm.arrRemove(vm.edges, self.edge); delete vm.edgesMap[self.edge.id]; }; - self.redo = function() { + self.redo = function () { vm.edges.push(self.edge); vm.edgesMap[self.edge.id] = self.edge; }; @@ -84,10 +84,10 @@ function GroupOperation(receiver, orphan) { const self = this; self.receiver = receiver; self.orphan = orphan; - self.undo = function() { + self.undo = function () { self.orphan.parent = undefined; }; - self.redo = function() { + self.redo = function () { self.orphan.parent = self.receiver; }; } @@ -96,10 +96,10 @@ function UnGroupOperation(parent, child) { const self = this; self.parent = parent; self.child = child; - self.undo = function() { + self.undo = function () { self.child.parent = self.parent; }; - self.redo = function() { + self.redo = function () { self.child.parent = undefined; }; } @@ -135,7 +135,7 @@ function GraphWorkspace(options) { searcher = options.searchProxy; } - this.addUndoLogEntry = function(undoOperations) { + this.addUndoLogEntry = function (undoOperations) { self.undoLog.push(undoOperations); if (self.undoLog.length > 50) { //Remove the oldest @@ -144,29 +144,29 @@ function GraphWorkspace(options) { self.redoLog = []; }; - this.undo = function() { + this.undo = function () { const lastOps = this.undoLog.pop(); if (lastOps) { this.stopLayout(); this.redoLog.push(lastOps); - lastOps.forEach(ops => ops.undo()); + lastOps.forEach((ops) => ops.undo()); this.runLayout(); } }; - this.redo = function() { + this.redo = function () { const lastOps = this.redoLog.pop(); if (lastOps) { this.stopLayout(); this.undoLog.push(lastOps); - lastOps.forEach(ops => ops.redo()); + lastOps.forEach((ops) => ops.redo()); this.runLayout(); } }; //Determines if 2 nodes are connected via an edge - this.areLinked = function(a, b) { + this.areLinked = function (a, b) { if (a === b) return true; - this.edges.forEach(e => { + this.edges.forEach((e) => { if (e.source === a && e.target === b) { return true; } @@ -179,9 +179,9 @@ function GraphWorkspace(options) { //======== Selection functions ======== - this.selectAll = function() { + this.selectAll = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { if (node.parent === undefined) { node.isSelected = true; self.selectedNodes.push(node); @@ -191,16 +191,16 @@ function GraphWorkspace(options) { }); }; - this.selectNone = function() { + this.selectNone = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { node.isSelected = false; }); }; - this.selectInvert = function() { + this.selectInvert = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { if (node.parent !== undefined) { return; } @@ -211,8 +211,8 @@ function GraphWorkspace(options) { }); }; - this.selectNodes = function(nodes) { - nodes.forEach(node => { + this.selectNodes = function (nodes) { + nodes.forEach((node) => { node.isSelected = true; if (self.selectedNodes.indexOf(node) < 0) { self.selectedNodes.push(node); @@ -220,14 +220,14 @@ function GraphWorkspace(options) { }); }; - this.selectNode = function(node) { + this.selectNode = function (node) { node.isSelected = true; if (self.selectedNodes.indexOf(node) < 0) { self.selectedNodes.push(node); } }; - this.deleteSelection = function() { + this.deleteSelection = function () { let allAndGrouped = self.returnUnpackedGroupeds(self.selectedNodes); // Nothing selected so process all nodes @@ -236,7 +236,7 @@ function GraphWorkspace(options) { } const undoOperations = []; - allAndGrouped.forEach(node => { + allAndGrouped.forEach((node) => { //We set selected to false because despite being deleted, node objects sit in an undo log node.isSelected = false; delete self.nodesMap[node.id]; @@ -245,10 +245,10 @@ function GraphWorkspace(options) { self.arrRemoveAll(self.nodes, allAndGrouped); self.arrRemoveAll(self.selectedNodes, allAndGrouped); - const danglingEdges = self.edges.filter(function(edge) { + const danglingEdges = self.edges.filter(function (edge) { return self.nodes.indexOf(edge.source) < 0 || self.nodes.indexOf(edge.target) < 0; }); - danglingEdges.forEach(edge => { + danglingEdges.forEach((edge) => { delete self.edgesMap[edge.id]; undoOperations.push(new ReverseOperation(new AddEdgeOperation(edge, self))); }); @@ -257,9 +257,9 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.selectNeighbours = function() { + this.selectNeighbours = function () { const newSelections = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { if (!edge.topSrc.isSelected) { if (self.selectedNodes.indexOf(edge.topTarget) >= 0) { if (newSelections.indexOf(edge.topSrc) < 0) { @@ -275,37 +275,37 @@ function GraphWorkspace(options) { } } }); - newSelections.forEach(newlySelectedNode => { + newSelections.forEach((newlySelectedNode) => { self.selectedNodes.push(newlySelectedNode); newlySelectedNode.isSelected = true; }); }; - this.selectNone = function() { - self.selectedNodes.forEach(node => { + this.selectNone = function () { + self.selectedNodes.forEach((node) => { node.isSelected = false; }); self.selectedNodes = []; }; - this.deselectNode = function(node) { + this.deselectNode = function (node) { node.isSelected = false; self.arrRemove(self.selectedNodes, node); }; - this.getAllSelectedNodes = function() { + this.getAllSelectedNodes = function () { return this.returnUnpackedGroupeds(self.selectedNodes); }; - this.colorSelected = function(colorNum) { - self.getAllSelectedNodes().forEach(node => { + this.colorSelected = function (colorNum) { + self.getAllSelectedNodes().forEach((node) => { node.color = colorNum; }); }; - this.getSelectionsThatAreGrouped = function() { + this.getSelectionsThatAreGrouped = function () { const result = []; - self.selectedNodes.forEach(node => { + self.selectedNodes.forEach((node) => { if (node.numChildren > 0) { result.push(node); } @@ -313,13 +313,13 @@ function GraphWorkspace(options) { return result; }; - this.ungroupSelection = function() { - self.getSelectionsThatAreGrouped().forEach(node => { + this.ungroupSelection = function () { + self.getSelectionsThatAreGrouped().forEach((node) => { self.ungroup(node); }); }; - this.toggleNodeSelection = function(node) { + this.toggleNodeSelection = function (node) { if (node.isSelected) { self.deselectNode(node); } else { @@ -329,7 +329,7 @@ function GraphWorkspace(options) { return node.isSelected; }; - this.returnUnpackedGroupeds = function(topLevelNodeArray) { + this.returnUnpackedGroupeds = function (topLevelNodeArray) { //Gather any grouped nodes that are part of this top-level selection const result = topLevelNodeArray.slice(); @@ -371,7 +371,7 @@ function GraphWorkspace(options) { // ======= Miscellaneous functions - this.clearGraph = function() { + this.clearGraph = function () { this.stopLayout(); this.nodes = []; this.edges = []; @@ -398,9 +398,9 @@ function GraphWorkspace(options) { } }; - this.getNeighbours = function(node) { + this.getNeighbours = function (node) { const neighbourNodes = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { if (edge.topSrc === edge.topTarget) { return; } @@ -419,7 +419,7 @@ function GraphWorkspace(options) { }; //Creates a query that represents a node - either simple term query or boolean if grouped - this.buildNodeQuery = function(topLevelNode) { + this.buildNodeQuery = function (topLevelNode) { let containedNodes = [topLevelNode]; containedNodes = self.returnUnpackedGroupeds(containedNodes); if (containedNodes.length === 1) { @@ -431,7 +431,7 @@ function GraphWorkspace(options) { }; } const termsByField = {}; - containedNodes.forEach(node => { + containedNodes.forEach((node) => { let termsList = termsByField[node.data.field]; if (!termsList) { termsList = []; @@ -465,20 +465,20 @@ function GraphWorkspace(options) { //====== Layout functions ======== - this.stopLayout = function() { + this.stopLayout = function () { if (this.force) { this.force.stop(); } this.force = null; }; - this.runLayout = function() { + this.runLayout = function () { this.stopLayout(); // The set of nodes and edges we present to the d3 layout algorithms // is potentially a reduced set of nodes if the client has used any // grouping of nodes into parent nodes. const effectiveEdges = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { let topSrc = edge.source; let topTarget = edge.target; while (topSrc.parent !== undefined) { @@ -497,12 +497,12 @@ function GraphWorkspace(options) { }); } }); - const visibleNodes = self.nodes.filter(function(n) { + const visibleNodes = self.nodes.filter(function (n) { return n.parent === undefined; }); //reset then roll-up all the counts const allNodes = self.nodes; - allNodes.forEach(node => { + allNodes.forEach((node) => { node.numChildren = 0; }); @@ -527,11 +527,11 @@ function GraphWorkspace(options) { .theta(0.99) .alpha(0.5) .size([800, 600]) - .on('tick', function() { + .on('tick', function () { const nodeArray = self.nodes; let hasRollups = false; //Update the position of all "top level nodes" - nodeArray.forEach(n => { + nodeArray.forEach((n) => { //Code to support roll-ups if (n.parent === undefined) { n.kx = n.x; @@ -541,7 +541,7 @@ function GraphWorkspace(options) { } }); if (hasRollups) { - nodeArray.forEach(n => { + nodeArray.forEach((n) => { //Code to support roll-ups if (n.parent !== undefined) { // Is a grouped node - inherit parent's position so edges point into parent @@ -568,9 +568,9 @@ function GraphWorkspace(options) { //========Grouping functions========== //Merges all selected nodes into node - this.groupSelections = function(node) { + this.groupSelections = function (node) { const ops = []; - self.nodes.forEach(function(otherNode) { + self.nodes.forEach(function (otherNode) { if (otherNode !== node && otherNode.isSelected && otherNode.parent === undefined) { otherNode.parent = node; otherNode.isSelected = false; @@ -584,10 +584,10 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.mergeNeighbours = function(node) { + this.mergeNeighbours = function (node) { const neighbours = self.getNeighbours(node); const ops = []; - neighbours.forEach(function(otherNode) { + neighbours.forEach(function (otherNode) { if (otherNode !== node && otherNode.parent === undefined) { otherNode.parent = node; otherNode.isSelected = false; @@ -599,14 +599,14 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.mergeSelections = function(targetNode) { + this.mergeSelections = function (targetNode) { if (!targetNode) { console.log('Error - merge called on undefined target'); return; } const selClone = self.selectedNodes.slice(); const ops = []; - selClone.forEach(function(otherNode) { + selClone.forEach(function (otherNode) { if (otherNode !== targetNode && otherNode.parent === undefined) { otherNode.parent = targetNode; otherNode.isSelected = false; @@ -618,9 +618,9 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.ungroup = function(node) { + this.ungroup = function (node) { const ops = []; - self.nodes.forEach(function(other) { + self.nodes.forEach(function (other) { if (other.parent === node) { other.parent = undefined; ops.push(new UnGroupOperation(node, other)); @@ -630,20 +630,20 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.unblacklist = function(node) { + this.unblacklist = function (node) { self.arrRemove(self.blacklistedNodes, node); }; - this.blacklistSelection = function() { + this.blacklistSelection = function () { const selection = self.getAllSelectedNodes(); const danglingEdges = []; - self.edges.forEach(function(edge) { + self.edges.forEach(function (edge) { if (selection.indexOf(edge.source) >= 0 || selection.indexOf(edge.target) >= 0) { delete self.edgesMap[edge.id]; danglingEdges.push(edge); } }); - selection.forEach(node => { + selection.forEach((node) => { delete self.nodesMap[node.id]; self.blacklistedNodes.push(node); node.isSelected = false; @@ -656,7 +656,7 @@ function GraphWorkspace(options) { // A "simple search" operation that requires no parameters from the client. // Performs numHops hops pulling in field-specific number of terms each time - this.simpleSearch = function(searchTerm, fieldsChoice, numHops) { + this.simpleSearch = function (searchTerm, fieldsChoice, numHops) { const qs = { query_string: { query: searchTerm, @@ -665,7 +665,7 @@ function GraphWorkspace(options) { return this.search(qs, fieldsChoice, numHops); }; - this.search = function(query, fieldsChoice, numHops) { + this.search = function (query, fieldsChoice, numHops) { if (!fieldsChoice) { fieldsChoice = self.options.vertex_fields; } @@ -734,7 +734,7 @@ function GraphWorkspace(options) { self.callElasticsearch(request); }; - this.buildControls = function() { + this.buildControls = function () { //This is an object managed by the client that may be subject to change const guiSettingsObj = self.options.exploreControls; @@ -753,11 +753,11 @@ function GraphWorkspace(options) { return controls; }; - this.makeNodeId = function(field, term) { + this.makeNodeId = function (field, term) { return field + '..' + term; }; - this.makeEdgeId = function(srcId, targetId) { + this.makeEdgeId = function (srcId, targetId) { let id = srcId + '->' + targetId; if (srcId > targetId) { id = targetId + '->' + srcId; @@ -766,7 +766,7 @@ function GraphWorkspace(options) { }; //======= Adds new nodes retrieved from an elasticsearch search ======== - this.mergeGraph = function(newData) { + this.mergeGraph = function (newData) { this.stopLayout(); if (!newData.nodes) { @@ -785,7 +785,7 @@ function GraphWorkspace(options) { //Remove nodes we already have const dedupedNodes = []; - newData.nodes.forEach(node => { + newData.nodes.forEach((node) => { //Assign an ID node.id = self.makeNodeId(node.field, node.term); if (!this.nodesMap[node.id]) { @@ -801,7 +801,7 @@ function GraphWorkspace(options) { this.options.nodeLabeller(dedupedNodes); } - dedupedNodes.forEach(dedupedNode => { + dedupedNodes.forEach((dedupedNode) => { let label = dedupedNode.term; if (dedupedNode.label) { label = dedupedNode.label; @@ -827,7 +827,7 @@ function GraphWorkspace(options) { this.nodesMap[node.id] = node; }); - newData.edges.forEach(edge => { + newData.edges.forEach((edge) => { const src = newData.nodes[edge.source]; const target = newData.nodes[edge.target]; edge.id = this.makeEdgeId(src.id, target.id); @@ -867,7 +867,7 @@ function GraphWorkspace(options) { this.runLayout(); }; - this.mergeIds = function(parentId, childId) { + this.mergeIds = function (parentId, childId) { const parent = self.getNode(parentId); const child = self.getNode(childId); if (child.isSelected) { @@ -879,16 +879,16 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.getNode = function(nodeId) { + this.getNode = function (nodeId) { return this.nodesMap[nodeId]; }; - this.getEdge = function(edgeId) { + this.getEdge = function (edgeId) { return this.edgesMap[edgeId]; }; //======= Expand functions to request new additions to the graph - this.expandSelecteds = function(targetOptions = {}) { + this.expandSelecteds = function (targetOptions = {}) { let startNodes = self.getAllSelectedNodes(); if (startNodes.length === 0) { startNodes = self.nodes; @@ -897,19 +897,19 @@ function GraphWorkspace(options) { self.expand(clone, targetOptions); }; - this.expandGraph = function() { + this.expandGraph = function () { self.expandSelecteds(); }; //Find new nodes to link to existing selected nodes - this.expandNode = function(node) { + this.expandNode = function (node) { self.expand(self.returnUnpackedGroupeds([node]), {}); }; // A manual expand function where the client provides the list // of existing nodes that are the start points and some options // about what targets are of interest. - this.expand = function(startNodes, targetOptions) { + this.expand = function (startNodes, targetOptions) { //============================= const nodesByField = {}; const excludeNodesByField = {}; @@ -983,7 +983,7 @@ function GraphWorkspace(options) { } //Identify target fields - targetFields.forEach(targetField => { + targetFields.forEach((targetField) => { const fieldName = targetField.name; // Sometimes the target field is disabled from loading new hops so we need to use the last valid figure const hopSize = targetField.hopSize > 0 ? targetField.hopSize : targetField.lastValidHopSize; @@ -1005,13 +1005,13 @@ function GraphWorkspace(options) { }, }; self.lastRequest = JSON.stringify(request, null, '\t'); - graphExplorer(self.options.indexName, request, function(data) { + graphExplorer(self.options.indexName, request, function (data) { self.lastResponse = JSON.stringify(data, null, '\t'); const edges = []; //Label fields with a field number for CSS styling - data.vertices.forEach(node => { - targetFields.some(fieldDef => { + data.vertices.forEach((node) => { + targetFields.some((fieldDef) => { if (node.field === fieldDef.name) { node.color = fieldDef.color; node.icon = fieldDef.icon; @@ -1026,7 +1026,7 @@ function GraphWorkspace(options) { const minLineSize = 2; const maxLineSize = 10; let maxEdgeWeight = 0.00000001; - data.connections.forEach(edge => { + data.connections.forEach((edge) => { maxEdgeWeight = Math.max(maxEdgeWeight, edge.weight); edges.push({ source: edge.source, @@ -1046,11 +1046,11 @@ function GraphWorkspace(options) { //===== End expand graph ======================== }; - this.trimExcessNewEdges = function(newNodes, newEdges) { + this.trimExcessNewEdges = function (newNodes, newEdges) { let trimmedEdges = []; const maxNumEdgesToReturn = 5; //Trim here to just the new edges that are most interesting. - newEdges.forEach(edge => { + newEdges.forEach((edge) => { const src = newNodes[edge.source]; const target = newNodes[edge.target]; const srcId = src.field + '..' + src.term; @@ -1080,7 +1080,7 @@ function GraphWorkspace(options) { }); if (trimmedEdges.length > maxNumEdgesToReturn) { //trim to only the most interesting ones - trimmedEdges.sort(function(a, b) { + trimmedEdges.sort(function (a, b) { return b.weight - a.weight; }); trimmedEdges = trimmedEdges.splice(0, maxNumEdgesToReturn); @@ -1088,13 +1088,13 @@ function GraphWorkspace(options) { return trimmedEdges; }; - this.getQuery = function(startNodes, loose) { + this.getQuery = function (startNodes, loose) { const shoulds = []; let nodes = startNodes; if (!startNodes) { nodes = self.nodes; } - nodes.forEach(node => { + nodes.forEach((node) => { if (node.parent === undefined) { shoulds.push(self.buildNodeQuery(node)); } @@ -1107,7 +1107,7 @@ function GraphWorkspace(options) { }; }; - this.getSelectedOrAllNodes = function() { + this.getSelectedOrAllNodes = function () { let startNodes = self.getAllSelectedNodes(); if (startNodes.length === 0) { startNodes = self.nodes; @@ -1115,8 +1115,8 @@ function GraphWorkspace(options) { return startNodes; }; - this.getSelectedOrAllTopNodes = function() { - return self.getSelectedOrAllNodes().filter(function(node) { + this.getSelectedOrAllTopNodes = function () { + return self.getSelectedOrAllNodes().filter(function (node) { return node.parent === undefined; }); }; @@ -1135,7 +1135,7 @@ function GraphWorkspace(options) { * @param maxNewEdges Max number of new edges added. Avoid adding too many new edges * at once into the graph otherwise disorientating */ - this.fillInGraph = function(maxNewEdges = 10) { + this.fillInGraph = function (maxNewEdges = 10) { let nodesForLinking = self.getSelectedOrAllTopNodes(); const maxNumVerticesSearchable = 100; @@ -1161,7 +1161,7 @@ function GraphWorkspace(options) { // the first 2 nodes in the array will therefore be labelled "0|1" const shoulds = []; const filterMap = {}; - nodesForLinking.forEach(function(node, nodeNum) { + nodesForLinking.forEach(function (node, nodeNum) { const nodeQuery = self.buildNodeQuery(node); shoulds.push(nodeQuery); filterMap[nodeNum] = nodeQuery; @@ -1186,10 +1186,10 @@ function GraphWorkspace(options) { }; // Search for connections between the selected nodes. - searcher(self.options.indexName, searchReq, function(data) { + searcher(self.options.indexName, searchReq, function (data) { const numDocsMatched = data.hits.total; const buckets = data.aggregations.matrix.buckets; - const vertices = nodesForLinking.map(function(existingNode) { + const vertices = nodesForLinking.map(function (existingNode) { return { field: existingNode.data.field, term: existingNode.data.term, @@ -1202,11 +1202,11 @@ function GraphWorkspace(options) { let maxEdgeWeight = 0; // Turn matrix array of results into a map const keyedBuckets = {}; - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { keyedBuckets[bucket.key] = bucket; }); - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { // We calibrate line thickness based on % of max weight of // all edges (including the edges we may already have in the workspace) const ids = bucket.key.split('|'); @@ -1232,7 +1232,7 @@ function GraphWorkspace(options) { }); const backFilledMinLineSize = 2; const backFilledMaxLineSize = 5; - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { if (bucket.doc_count < parseInt(self.options.exploreControls.minDocCount)) { return; } @@ -1263,7 +1263,7 @@ function GraphWorkspace(options) { }); // Trim the array of connections so that we don't add too many at once - disorientating for users otherwise if (connections.length > maxNewEdges) { - connections = connections.sort(function(a, b) { + connections = connections.sort(function (a, b) { return b.weight - a.weight; }); connections = connections.slice(0, maxNewEdges); @@ -1287,11 +1287,11 @@ function GraphWorkspace(options) { // We use a free-text search on the index's configured default field (typically '_all') // to drill-down into docs that should be linked but aren't via the exact terms // we have in the workspace - this.getLikeThisButNotThisQuery = function(startNodes) { + this.getLikeThisButNotThisQuery = function (startNodes) { const likeQueries = []; const txtsByFieldType = {}; - startNodes.forEach(node => { + startNodes.forEach((node) => { let txt = txtsByFieldType[node.data.field]; if (txt) { txt = txt + ' ' + node.label; @@ -1317,11 +1317,11 @@ function GraphWorkspace(options) { const excludeNodesByField = {}; const allExistingNodes = self.nodes; - allExistingNodes.forEach(existingNode => { + allExistingNodes.forEach((existingNode) => { addTermToFieldList(excludeNodesByField, existingNode.data.field, existingNode.data.term); }); const blacklistedNodes = self.blacklistedNodes; - blacklistedNodes.forEach(blacklistedNode => { + blacklistedNodes.forEach((blacklistedNode) => { addTermToFieldList( excludeNodesByField, blacklistedNode.data.field, @@ -1331,7 +1331,7 @@ function GraphWorkspace(options) { //Create negative boosting queries to avoid matching what you already have in the workspace. const notExistingNodes = []; - Object.keys(excludeNodesByField).forEach(fieldName => { + Object.keys(excludeNodesByField).forEach((fieldName) => { const termsQuery = {}; termsQuery[fieldName] = excludeNodesByField[fieldName]; notExistingNodes.push({ @@ -1359,7 +1359,7 @@ function GraphWorkspace(options) { return result; }; - this.getSelectedIntersections = function(callback) { + this.getSelectedIntersections = function (callback) { if (self.selectedNodes.length === 0) { return self.getAllIntersections(callback, self.nodes); } @@ -1372,7 +1372,7 @@ function GraphWorkspace(options) { return self.getAllIntersections(callback, self.getAllSelectedNodes()); }; - this.jLHScore = function(subsetFreq, subsetSize, supersetFreq, supersetSize) { + this.jLHScore = function (subsetFreq, subsetSize, supersetFreq, supersetSize) { const subsetProbability = subsetFreq / subsetSize; const supersetProbability = supersetFreq / supersetSize; @@ -1392,13 +1392,13 @@ function GraphWorkspace(options) { // Determines union/intersection stats for neighbours of a node. // TODO - could move server-side as a graph API function? - this.getAllIntersections = function(callback, nodes) { + this.getAllIntersections = function (callback, nodes) { //Ensure these are all top-level nodes only - nodes = nodes.filter(function(n) { + nodes = nodes.filter(function (n) { return n.parent === undefined; }); - const allQueries = nodes.map(function(node) { + const allQueries = nodes.map(function (node) { return self.buildNodeQuery(node); }); @@ -1436,7 +1436,7 @@ function GraphWorkspace(options) { request.aggs.sources.filters.filters['bg' + n] = query; request.aggs.sources.aggs.targets.filters.filters['fg' + n] = query; }); - searcher(self.options.indexName, request, function(data) { + searcher(self.options.indexName, request, function (data) { const termIntersects = []; const fullDocCounts = []; const allDocCount = data.aggregations.all.doc_count; @@ -1499,7 +1499,7 @@ function GraphWorkspace(options) { termIntersects.push(termIntersect); }); }); - termIntersects.sort(function(a, b) { + termIntersects.sort(function (a, b) { if (b.mergeConfidence !== a.mergeConfidence) { return b.mergeConfidence - a.mergeConfidence; } @@ -1520,14 +1520,14 @@ function GraphWorkspace(options) { // Internal utility function for calling the Graph API and handling the response // by merging results into existing nodes in this workspace. - this.callElasticsearch = function(request) { + this.callElasticsearch = function (request) { self.lastRequest = JSON.stringify(request, null, '\t'); - graphExplorer(self.options.indexName, request, function(data) { + graphExplorer(self.options.indexName, request, function (data) { self.lastResponse = JSON.stringify(data, null, '\t'); const edges = []; //Label the nodes with field number for CSS styling - data.vertices.forEach(node => { - self.options.vertex_fields.some(fieldDef => { + data.vertices.forEach((node) => { + self.options.vertex_fields.some((fieldDef) => { if (node.field === fieldDef.name) { node.color = fieldDef.color; node.icon = fieldDef.icon; @@ -1542,10 +1542,10 @@ function GraphWorkspace(options) { const minLineSize = 2; const maxLineSize = 10; let maxEdgeWeight = 0.00000001; - data.connections.forEach(edge => { + data.connections.forEach((edge) => { maxEdgeWeight = Math.max(maxEdgeWeight, edge.weight); }); - data.connections.forEach(edge => { + data.connections.forEach((edge) => { edges.push({ source: edge.source, target: edge.target, diff --git a/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js b/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js index 7ffb16d986a21..fe6a782373eb2 100644 --- a/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js +++ b/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js @@ -6,16 +6,16 @@ import { createWorkspace } from './graph_client_workspace'; -describe('graphui-workspace', function() { - describe('createWorkspace()', function() { +describe('graphui-workspace', function () { + describe('createWorkspace()', function () { // var fooResource=null; let mockedResult = null; let init = null; - beforeEach(function() { + beforeEach(function () { //Setup logic here // fooResource={"foo":"bar"}; - init = function() { - const callNodeProxy = function(indexName, query, responseHandler) { + init = function () { + const callNodeProxy = function (indexName, query, responseHandler) { responseHandler(mockedResult); }; const options = { @@ -45,11 +45,11 @@ describe('graphui-workspace', function() { }; }; }); - it('initializeWorkspace', function() { + it('initializeWorkspace', function () { const { workspace } = init(); expect(workspace.nodes.length).toEqual(0); }); - it('simpleSearch', function() { + it('simpleSearch', function () { //Test that a graph is loaded from a free-text search const { workspace } = init(); @@ -91,7 +91,7 @@ describe('graphui-workspace', function() { expect(nodeD).toBe(undefined); }); - it('expandTest', function() { + it('expandTest', function () { //Test that a graph can be expanded const { workspace } = init(); @@ -155,7 +155,7 @@ describe('graphui-workspace', function() { expect(workspace.edges.length).toEqual(2); }); - it('selectionTest', function() { + it('selectionTest', function () { //Test selections on a graph const { workspace } = init(); // graph is a1->a2 and b1->b2 @@ -237,7 +237,7 @@ describe('graphui-workspace', function() { expect(workspace.selectedNodes.length).toEqual(2); }); - it('undoRedoDeletes', function() { + it('undoRedoDeletes', function () { const { workspace } = init(); // graph is a1->a2 mockedResult = { @@ -293,7 +293,7 @@ describe('graphui-workspace', function() { expect(workspace.nodes.length).toEqual(2); }); - it('undoRedoGroupings', function() { + it('undoRedoGroupings', function () { const { workspace } = init(); // graph is a1->a2 mockedResult = { diff --git a/x-pack/plugins/graph/public/app.js b/x-pack/plugins/graph/public/app.js index d4199fbd092b4..08b13e9d5c541 100644 --- a/x-pack/plugins/graph/public/app.js +++ b/x-pack/plugins/graph/public/app.js @@ -57,15 +57,15 @@ export function initGraphApp(angularModule, deps) { const app = angularModule; - app.directive('vennDiagram', function(reactDirective) { + app.directive('vennDiagram', function (reactDirective) { return reactDirective(VennDiagram); }); - app.directive('graphVisualization', function(reactDirective) { + app.directive('graphVisualization', function (reactDirective) { return reactDirective(GraphVisualization); }); - app.directive('graphListing', function(reactDirective) { + app.directive('graphListing', function (reactDirective) { return reactDirective(Listing, [ ['coreStart', { watchDepth: 'reference' }], ['createItem', { watchDepth: 'reference' }], @@ -81,7 +81,7 @@ export function initGraphApp(angularModule, deps) { ]); }); - app.directive('graphApp', function(reactDirective) { + app.directive('graphApp', function (reactDirective) { return reactDirective( GraphApp, [ @@ -102,33 +102,33 @@ export function initGraphApp(angularModule, deps) { ); }); - app.directive('graphVisualization', function(reactDirective) { + app.directive('graphVisualization', function (reactDirective) { return reactDirective(GraphVisualization, undefined, { restrict: 'A' }); }); - app.config(function($routeProvider) { + app.config(function ($routeProvider) { $routeProvider .when('/home', { template: listingTemplate, badge: getReadonlyBadge, - controller: function($location, $scope) { + controller: function ($location, $scope) { $scope.listingLimit = savedObjects.settings.getListingLimit(); $scope.initialPageSize = savedObjects.settings.getPerPage(); $scope.create = () => { $location.url(getNewPath()); }; - $scope.find = search => { + $scope.find = (search) => { return findSavedWorkspace( { savedObjectsClient, basePath: coreStart.http.basePath }, search, $scope.listingLimit ); }; - $scope.editItem = workspace => { + $scope.editItem = (workspace) => { $location.url(getEditPath(workspace)); }; - $scope.getViewUrl = workspace => getEditUrl(addBasePath, workspace); - $scope.delete = workspaces => + $scope.getViewUrl = (workspace) => getEditUrl(addBasePath, workspace); + $scope.delete = (workspaces) => deleteSavedWorkspace( savedObjectsClient, workspaces.map(({ id }) => id) @@ -143,9 +143,9 @@ export function initGraphApp(angularModule, deps) { template: appTemplate, badge: getReadonlyBadge, resolve: { - savedWorkspace: function($rootScope, $route, $location) { + savedWorkspace: function ($rootScope, $route, $location) { return $route.current.params.id - ? getSavedWorkspace(savedObjectsClient, $route.current.params.id).catch(function(e) { + ? getSavedWorkspace(savedObjectsClient, $route.current.params.id).catch(function (e) { toastNotifications.addError(e, { title: i18n.translate('xpack.graph.missingWorkspaceErrorMessage', { defaultMessage: "Couldn't load graph with ID", @@ -160,16 +160,16 @@ export function initGraphApp(angularModule, deps) { }) : getSavedWorkspace(savedObjectsClient); }, - indexPatterns: function() { + indexPatterns: function () { return savedObjectsClient .find({ type: 'index-pattern', fields: ['title', 'type'], perPage: 10000, }) - .then(response => response.savedObjects); + .then((response) => response.savedObjects); }, - GetIndexPatternProvider: function() { + GetIndexPatternProvider: function () { return indexPatterns; }, }, @@ -180,7 +180,7 @@ export function initGraphApp(angularModule, deps) { }); //======== Controller for basic UI ================== - app.controller('graphuiPlugin', function($scope, $route, $location) { + app.controller('graphuiPlugin', function ($scope, $route, $location) { function handleError(err) { const toastTitle = i18n.translate('xpack.graph.errorToastTitle', { defaultMessage: 'Graph Error', @@ -214,7 +214,7 @@ export function initGraphApp(angularModule, deps) { $scope.loading = true; return coreStart.http .post('../api/graph/graphExplore', request) - .then(function(data) { + .then(function (data) { const response = data.resp; if (response.timed_out) { toastNotifications.addWarning( @@ -233,7 +233,7 @@ export function initGraphApp(angularModule, deps) { } //Helper function for the graphClientWorkspace to perform a query - const callSearchNodeProxy = function(indexName, query, responseHandler) { + const callSearchNodeProxy = function (indexName, query, responseHandler) { const request = { body: JSON.stringify({ index: indexName, @@ -243,7 +243,7 @@ export function initGraphApp(angularModule, deps) { $scope.loading = true; coreStart.http .post('../api/graph/searchProxy', request) - .then(function(data) { + .then(function (data) { const response = data.resp; responseHandler(response); }) @@ -268,10 +268,10 @@ export function initGraphApp(angularModule, deps) { indexName: indexPattern, vertex_fields: [], // Here we have the opportunity to look up labels for nodes... - nodeLabeller: function() { + nodeLabeller: function () { // console.log(newNodes); }, - changeHandler: function() { + changeHandler: function () { //Allows DOM to update with graph layout changes. $scope.$apply(); }, @@ -281,10 +281,10 @@ export function initGraphApp(angularModule, deps) { }; $scope.workspace = createWorkspace(options); }, - setLiveResponseFields: fields => { + setLiveResponseFields: (fields) => { $scope.liveResponseFields = fields; }, - setUrlTemplates: urlTemplates => { + setUrlTemplates: (urlTemplates) => { $scope.urlTemplates = urlTemplates; }, getWorkspace: () => { @@ -302,7 +302,7 @@ export function initGraphApp(angularModule, deps) { $scope.workspaceInitialized = true; }, savePolicy: graphSavePolicy, - changeUrl: newUrl => { + changeUrl: (newUrl) => { $scope.$evalAsync(() => { $location.url(newUrl); }); @@ -326,8 +326,8 @@ export function initGraphApp(angularModule, deps) { const allSavingDisabled = graphSavePolicy === 'none'; $scope.spymode = 'request'; $scope.colors = colorChoices; - $scope.isColorDark = color => isColorDark(...hexToRgb(color)); - $scope.nodeClick = function(n, $event) { + $scope.isColorDark = (color) => isColorDark(...hexToRgb(color)); + $scope.nodeClick = function (n, $event) { //Selection logic - shift key+click helps selects multiple nodes // Without the shift key we deselect all prior selections (perhaps not // a great idea for touch devices with no concept of shift key) @@ -344,14 +344,14 @@ export function initGraphApp(angularModule, deps) { } }; - $scope.clickEdge = function(edge) { + $scope.clickEdge = function (edge) { $scope.workspace.getAllIntersections($scope.handleMergeCandidatesCallback, [ edge.topSrc, edge.topTarget, ]); }; - $scope.submit = function(searchTerm) { + $scope.submit = function (searchTerm) { $scope.workspaceInitialized = true; const numHops = 2; if (searchTerm.startsWith('{')) { @@ -372,28 +372,28 @@ export function initGraphApp(angularModule, deps) { $scope.workspace.simpleSearch(searchTerm, $scope.liveResponseFields, numHops); }; - $scope.selectSelected = function(node) { + $scope.selectSelected = function (node) { $scope.detail = { latestNodeSelection: node, }; return ($scope.selectedSelectedVertex = node); }; - $scope.isSelectedSelected = function(node) { + $scope.isSelectedSelected = function (node) { return $scope.selectedSelectedVertex === node; }; - $scope.openUrlTemplate = function(template) { + $scope.openUrlTemplate = function (template) { const url = template.url; const newUrl = url.replace(urlTemplateRegex, template.encoder.encode($scope.workspace)); window.open(newUrl, '_blank'); }; - $scope.aceLoaded = editor => { + $scope.aceLoaded = (editor) => { editor.$blockScrolling = Infinity; }; - $scope.setDetail = function(data) { + $scope.setDetail = function (data) { $scope.detail = data; }; @@ -421,7 +421,7 @@ export function initGraphApp(angularModule, deps) { }), confirmModalOptions ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { callback(); } @@ -429,7 +429,7 @@ export function initGraphApp(angularModule, deps) { } $scope.confirmWipeWorkspace = canWipeWorkspace; - $scope.performMerge = function(parentId, childId) { + $scope.performMerge = function (parentId, childId) { let found = true; while (found) { found = false; @@ -448,9 +448,9 @@ export function initGraphApp(angularModule, deps) { $scope.detail = null; }; - $scope.handleMergeCandidatesCallback = function(termIntersects) { + $scope.handleMergeCandidatesCallback = function (termIntersects) { const mergeCandidates = []; - termIntersects.forEach(ti => { + termIntersects.forEach((ti) => { mergeCandidates.push({ id1: ti.id1, id2: ti.id2, @@ -477,8 +477,8 @@ export function initGraphApp(angularModule, deps) { tooltip: i18n.translate('xpack.graph.topNavMenu.newWorkspaceTooltip', { defaultMessage: 'Create a new workspace', }), - run: function() { - canWipeWorkspace(function() { + run: function () { + canWipeWorkspace(function () { $scope.$evalAsync(() => { if ($location.url() === '/workspace/') { $route.reload(); @@ -516,7 +516,7 @@ export function initGraphApp(angularModule, deps) { }); } }, - disableButton: function() { + disableButton: function () { return allSavingDisabled || !hasFieldsSelector(store.getState()); }, run: () => { @@ -530,7 +530,7 @@ export function initGraphApp(angularModule, deps) { } $scope.topNavMenu.push({ key: 'inspect', - disableButton: function() { + disableButton: function () { return $scope.workspace === null; }, label: i18n.translate('xpack.graph.topNavMenu.inspectLabel', { @@ -550,7 +550,7 @@ export function initGraphApp(angularModule, deps) { $scope.topNavMenu.push({ key: 'settings', - disableButton: function() { + disableButton: function () { return datasourceSelector(store.getState()).type === 'none'; }, label: i18n.translate('xpack.graph.topNavMenu.settingsLabel', { @@ -605,7 +605,7 @@ export function initGraphApp(angularModule, deps) { }; $scope.closeMenus = () => { - _.forOwn($scope.menus, function(_, key) { + _.forOwn($scope.menus, function (_, key) { $scope.menus[key] = false; }); }; diff --git a/x-pack/plugins/graph/public/application.ts b/x-pack/plugins/graph/public/application.ts index 7c0fb867b9ada..b46bc88500e0a 100644 --- a/x-pack/plugins/graph/public/application.ts +++ b/x-pack/plugins/graph/public/application.ts @@ -77,7 +77,7 @@ export const renderApp = ({ appBasePath, element, ...deps }: GraphDependencies) true ); - const licenseSubscription = deps.licensing.license$.subscribe(license => { + const licenseSubscription = deps.licensing.license$.subscribe((license) => { const info = checkLicense(license); const licenseAllowsToShowThisPage = info.showAppLink && info.enableAppLink; diff --git a/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx b/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx index 211458e67d05b..cd2227bf6a18c 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx @@ -215,7 +215,7 @@ export function FieldEditor({ })} > { + onChange={(choices) => { // value is always defined because it's an unclearable single selection const newFieldName = choices[0].value!; @@ -260,7 +260,7 @@ export function FieldEditor({ > { + onChange={(newColor) => { updateProp('color', newColor); }} compressed @@ -286,7 +286,7 @@ export function FieldEditor({ ); }} - options={iconChoices.map(currentIcon => ({ + options={iconChoices.map((currentIcon) => ({ label: currentIcon.label, value: currentIcon, }))} @@ -296,7 +296,7 @@ export function FieldEditor({ value: icon, }, ]} - onChange={choices => { + onChange={(choices) => { updateProp('icon', choices[0].value!); }} compressed @@ -378,7 +378,7 @@ function toOptions( currentField: WorkspaceField ): Array<{ label: string; value: string; type: ButtonHTMLAttributes['type'] }> { return fields - .filter(field => !field.selected || field === currentField) + .filter((field) => !field.selected || field === currentField) .map(({ name, type }) => ({ label: name, value: name, diff --git a/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx b/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx index ac656ebdd9512..f213fe6b509bf 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx @@ -76,28 +76,13 @@ describe('field_manager', () => { ); - getInstance = () => - instance - .find(FieldManager) - .dive() - .dive() - .dive(); + getInstance = () => instance.find(FieldManager).dive().dive().dive(); }); it('should list editors for all selected fields', () => { expect(getInstance().find(FieldEditor).length).toEqual(2); - expect( - getInstance() - .find(FieldEditor) - .at(0) - .prop('field').name - ).toEqual('field1'); - expect( - getInstance() - .find(FieldEditor) - .at(1) - .prop('field').name - ).toEqual('field2'); + expect(getInstance().find(FieldEditor).at(0).prop('field').name).toEqual('field1'); + expect(getInstance().find(FieldEditor).at(1).prop('field').name).toEqual('field2'); }); it('should show selected non-aggregatable fields in picker, but hide unselected ones', () => { @@ -122,11 +107,9 @@ describe('field_manager', () => { ).toEqual(['field1', 'field2', 'field3']); act(() => { - getInstance() - .find(FieldPicker) - .dive() - .find(EuiSelectable) - .prop('onChange')([{ checked: 'on', label: 'field3' }]); + getInstance().find(FieldPicker).dive().find(EuiSelectable).prop('onChange')([ + { checked: 'on', label: 'field3' }, + ]); }); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -139,12 +122,8 @@ describe('field_manager', () => { it('should deselect field', () => { act(() => { - getInstance() - .find(FieldEditor) - .at(0) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![2].onClick!({} as any); + getInstance().find(FieldEditor).at(0).dive().find(EuiContextMenu).prop('panels')![0].items![2] + .onClick!({} as any); }); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -157,12 +136,8 @@ describe('field_manager', () => { it('should show remove non-aggregatable fields from picker after deselection', () => { act(() => { - getInstance() - .find(FieldEditor) - .at(1) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![2].onClick!({} as any); + getInstance().find(FieldEditor).at(1).dive().find(EuiContextMenu).prop('panels')![0].items![2] + .onClick!({} as any); }); expect( getInstance() @@ -198,12 +173,8 @@ describe('field_manager', () => { }); expect( - getInstance() - .find(FieldEditor) - .at(0) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![1].name + getInstance().find(FieldEditor).at(0).dive().find(EuiContextMenu).prop('panels')![0].items![1] + .name ).toEqual('Enable field'); }); @@ -231,37 +202,26 @@ describe('field_manager', () => { }); expect( - getInstance() - .find(FieldEditor) - .at(1) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![1].name + getInstance().find(FieldEditor).at(1).dive().find(EuiContextMenu).prop('panels')![0].items![1] + .name ).toEqual('Disable field'); }); it('should change color', () => { - const fieldEditor = getInstance() - .find(FieldEditor) - .at(1) - .dive(); + const fieldEditor = getInstance().find(FieldEditor).at(1).dive(); const getDisplayForm = () => shallow(fieldEditor.find(EuiContextMenu).prop('panels')![1].content as ReactElement); act(() => { - getDisplayForm() - .find(EuiColorPicker) - .prop('onChange')!('#aaa', { + getDisplayForm().find(EuiColorPicker).prop('onChange')!('#aaa', { rgba: [170, 170, 170, 1], hex: '#aaa', isValid: true, }); }); fieldEditor.update(); - getDisplayForm() - .find(EuiButton) - .prop('onClick')!({} as any); + getDisplayForm().find(EuiButton).prop('onClick')!({} as any); expect(dispatchSpy).toHaveBeenCalledWith({ type: 'x-pack/graph/fields/UPDATE_FIELD_PROPERTIES', diff --git a/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx b/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx index 9bca5b82e58aa..d0e44542674ef 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx @@ -40,7 +40,7 @@ export function FieldManagerComponent(props: { }) { return ( - {props.selectedFields.map(field => ( + {props.selectedFields.map((field) => ( @@ -58,7 +58,7 @@ export const FieldManager = connect( allFields: fieldsSelector(state), selectedFields: selectedFieldsSelector(state), }), - dispatch => + (dispatch) => bindActionCreators( { updateFieldProperties, diff --git a/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx b/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx index f2dc9ba0c6490..ae32e8d2ce6d6 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx @@ -88,8 +88,8 @@ export function FieldPicker({ }} searchable options={fieldOptions} - onChange={newOptions => { - newOptions.forEach(option => { + onChange={(newOptions) => { + newOptions.forEach((option) => { if (option.checked === 'on' && !fieldMap[option.label].selected) { selectField(option.label); } else if (option.checked !== 'on' && fieldMap[option.label].selected) { @@ -119,8 +119,8 @@ function toOptions( // don't show non-aggregatable fields, except for the case when they are already selected. // this is necessary to ensure backwards compatibility with existing workspaces that might // contain non-aggregatable fields. - .filter(field => isExplorable(field) || field.selected) - .map(field => ({ + .filter((field) => isExplorable(field) || field.selected) + .map((field) => ({ label: field.name, prepend: , checked: field.selected ? 'on' : undefined, diff --git a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx index be3ebee9f0e23..1dd83f17ac8d4 100644 --- a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx +++ b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx @@ -136,10 +136,7 @@ describe('graph_visualization', () => { edges={edges} /> ); - instance - .find('.gphNode') - .first() - .simulate('click', {}); + instance.find('.gphNode').first().simulate('click', {}); expect(nodeClickSpy).toHaveBeenCalledWith(nodes[0], {}); }); @@ -153,10 +150,7 @@ describe('graph_visualization', () => { edges={edges} /> ); - instance - .find('.gphEdge') - .first() - .simulate('click'); + instance.find('.gphEdge').first().simulate('click'); expect(edgeClickSpy).toHaveBeenCalledWith(edges[0]); }); }); diff --git a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx index 162e4d01db6a4..8561989c8a6bf 100644 --- a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx +++ b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx @@ -36,7 +36,7 @@ export interface GraphVisualizationProps { } function registerZooming(element: SVGSVGElement) { - const blockScroll = function() { + const blockScroll = function () { (d3.event as Event).preventDefault(); }; d3.select(element) @@ -69,7 +69,7 @@ export function GraphVisualization({ height="100%" pointerEvents="all" id="graphSvg" - ref={element => { + ref={(element) => { if (element && svgRoot.current !== element) { svgRoot.current = element; registerZooming(element); @@ -79,7 +79,7 @@ export function GraphVisualization({ {edges && - edges.map(edge => ( + edges.map((edge) => ( {nodes && nodes - .filter(node => !node.parent) - .map(node => ( + .filter((node) => !node.parent) + .map((node) => ( { + onClick={(e) => { nodeClick(node, e); }} - onMouseDown={e => { + onMouseDown={(e) => { // avoid selecting text when selecting nodes if (e.ctrlKey || e.shiftKey) { e.preventDefault(); diff --git a/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx b/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx index 4404ea494b288..583be123a48ce 100644 --- a/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx +++ b/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx @@ -217,7 +217,7 @@ export const GuidancePanel = connect( hasFields: hasFieldsSelector(state), }; }, - dispatch => ({ + (dispatch) => ({ onIndexPatternSelected: (indexPattern: IndexPatternSavedObject) => { dispatch( requestDatasource({ diff --git a/x-pack/plugins/graph/public/components/helpers.ts b/x-pack/plugins/graph/public/components/helpers.ts index e53f7f5b12713..db1d1e78f254a 100644 --- a/x-pack/plugins/graph/public/components/helpers.ts +++ b/x-pack/plugins/graph/public/components/helpers.ts @@ -5,5 +5,5 @@ */ export function isEqual(a: T, b: T) { - return (Object.keys(a) as Array).every(key => a[key] === b[key]); + return (Object.keys(a) as Array).every((key) => a[key] === b[key]); } diff --git a/x-pack/plugins/graph/public/components/save_modal.tsx b/x-pack/plugins/graph/public/components/save_modal.tsx index c4459fb1a794f..265d8155e46d6 100644 --- a/x-pack/plugins/graph/public/components/save_modal.tsx +++ b/x-pack/plugins/graph/public/components/save_modal.tsx @@ -37,7 +37,7 @@ export function SaveModal({ const [dataConsent, setDataConsent] = useState(false); return ( { + onSave={(props) => { onSave({ ...props, newDescription, dataConsent }); }} onClose={onClose} @@ -58,7 +58,7 @@ export function SaveModal({ { + onChange={(e) => { setDescription(e.target.value); }} fullWidth @@ -80,7 +80,7 @@ export function SaveModal({ defaultMessage: 'Save graph content', })} checked={dataConsent} - onChange={e => { + onChange={(e) => { setDataConsent(e.target.checked); }} /> diff --git a/x-pack/plugins/graph/public/components/search_bar.test.tsx b/x-pack/plugins/graph/public/components/search_bar.test.tsx index 10778124e2011..100122af943e1 100644 --- a/x-pack/plugins/graph/public/components/search_bar.test.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.test.tsx @@ -24,7 +24,7 @@ import { Provider } from 'react-redux'; jest.mock('ui/new_platform'); jest.mock('../services/source_modal', () => ({ openSourceModal: jest.fn() })); -const waitForIndexPatternFetch = () => new Promise(r => setTimeout(r)); +const waitForIndexPatternFetch = () => new Promise((r) => setTimeout(r)); function wrapSearchBarInContext(testProps: OuterSearchBarProps) { const services = { diff --git a/x-pack/plugins/graph/public/components/search_bar.tsx b/x-pack/plugins/graph/public/components/search_bar.tsx index ab6d94a78ceec..a74e0ccfb46b5 100644 --- a/x-pack/plugins/graph/public/components/search_bar.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.tsx @@ -97,7 +97,7 @@ export function SearchBarComponent(props: SearchBarProps) { return ( { + onSubmit={(e) => { e.preventDefault(); if (!isLoading && currentIndexPattern) { onQuerySubmit(queryToString(query, currentIndexPattern)); @@ -185,7 +185,7 @@ export const SearchBar = connect( datasource.current.type === 'indexpattern' ? datasource.current : undefined, }; }, - dispatch => ({ + (dispatch) => ({ onIndexPatternSelected: (indexPattern: IndexPatternSavedObject) => { dispatch( requestDatasource({ diff --git a/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx b/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx index 5231f7ddad6df..191655ec7bc17 100644 --- a/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx @@ -31,7 +31,7 @@ export function AdvancedSettingsForm({ } function getNumberUpdater>(key: K) { - return function({ target: { valueAsNumber } }: { target: { valueAsNumber: number } }) { + return function ({ target: { valueAsNumber } }: { target: { valueAsNumber: number } }) { updateSetting(key, Number.isNaN(valueAsNumber) ? 1 : valueAsNumber); }; } @@ -125,7 +125,7 @@ export function AdvancedSettingsForm({ { defaultMessage: 'No diversification' } )} singleSelection={{ asPlainText: true }} - options={allFields.map(field => ({ label: field.name, value: field }))} + options={allFields.map((field) => ({ label: field.name, value: field }))} selectedOptions={ advancedSettings.sampleDiversityField ? [ @@ -136,7 +136,7 @@ export function AdvancedSettingsForm({ ] : [] } - onChange={choices => { + onChange={(choices) => { updateSetting( 'sampleDiversityField', choices.length === 1 ? choices[0].value : undefined diff --git a/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx b/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx index f7ae04ef9dbcc..68cdcc1fbb7b1 100644 --- a/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx @@ -48,7 +48,7 @@ export function BlacklistForm({ {blacklistedNodes && unblacklistNode && blacklistedNodes.length > 0 && ( <> - {blacklistedNodes.map(node => ( + {blacklistedNodes.map((node) => ( } key={getListKey(node)} @@ -77,7 +77,7 @@ export function BlacklistForm({ size="s" fill onClick={() => { - blacklistedNodes.forEach(node => { + blacklistedNodes.forEach((node) => { unblacklistNode(node); }); }} diff --git a/x-pack/plugins/graph/public/components/settings/settings.test.tsx b/x-pack/plugins/graph/public/components/settings/settings.test.tsx index 0109e1f5a5ac7..b392a26ecf0d3 100644 --- a/x-pack/plugins/graph/public/components/settings/settings.test.tsx +++ b/x-pack/plugins/graph/public/components/settings/settings.test.tsx @@ -148,7 +148,7 @@ describe('settings', () => { act(() => { instance .find(EuiTab) - .findWhere(node => node.key() === tab) + .findWhere((node) => node.key() === tab) .prop('onClick')!({}); }); instance.update(); @@ -185,7 +185,7 @@ describe('settings', () => { }); it('should switch tab to blacklist', () => { - expect(instance.find(EuiListGroupItem).map(item => item.prop('label'))).toEqual([ + expect(instance.find(EuiListGroupItem).map((item) => item.prop('label'))).toEqual([ 'blacklisted node 1', 'blacklisted node 2', ]); @@ -219,25 +219,19 @@ describe('settings', () => { instance.update(); - expect(instance.find(EuiListGroupItem).map(item => item.prop('label'))).toEqual([ + expect(instance.find(EuiListGroupItem).map((item) => item.prop('label'))).toEqual([ 'blacklisted node 3', ]); }); it('should delete node', () => { - instance - .find(EuiListGroupItem) - .at(0) - .prop('extraAction')!.onClick!({} as any); + instance.find(EuiListGroupItem).at(0).prop('extraAction')!.onClick!({} as any); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![0]); }); it('should delete all nodes', () => { - instance - .find('[data-test-subj="graphUnblacklistAll"]') - .find(EuiButton) - .simulate('click'); + instance.find('[data-test-subj="graphUnblacklistAll"]').find(EuiButton).simulate('click'); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![0]); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![1]); @@ -251,11 +245,9 @@ describe('settings', () => { function insert(formIndex: number, label: string, value: string) { act(() => { - templateForm(formIndex) - .find({ label }) - .first() - .find(EuiFieldText) - .prop('onChange')!({ target: { value } } as React.ChangeEvent); + templateForm(formIndex).find({ label }).first().find(EuiFieldText).prop('onChange')!({ + target: { value }, + } as React.ChangeEvent); }); instance.update(); } @@ -265,12 +257,7 @@ describe('settings', () => { }); it('should switch tab to url templates', () => { - expect( - instance - .find(EuiAccordion) - .at(0) - .prop('buttonContent') - ).toEqual('template'); + expect(instance.find(EuiAccordion).at(0).prop('buttonContent')).toEqual('template'); }); it('should delete url template', () => { @@ -283,9 +270,7 @@ describe('settings', () => { it('should update url template', () => { insert(0, 'Title', 'Updated title'); act(() => { - templateForm(0) - .find('form') - .simulate('submit'); + templateForm(0).find('form').simulate('submit'); }); expect(dispatchSpy).toHaveBeenCalledWith( saveTemplate({ index: 0, template: { ...initialTemplate, description: 'Updated title' } }) @@ -302,9 +287,7 @@ describe('settings', () => { insert(1, 'Title', 'Title'); act(() => { - templateForm(1) - .find('form') - .simulate('submit'); + templateForm(1).find('form').simulate('submit'); }); expect(dispatchSpy).toHaveBeenCalledWith( saveTemplate({ diff --git a/x-pack/plugins/graph/public/components/settings/settings.tsx b/x-pack/plugins/graph/public/components/settings/settings.tsx index d6613cc1e0b9a..3baf6b6a0a2e3 100644 --- a/x-pack/plugins/graph/public/components/settings/settings.tsx +++ b/x-pack/plugins/graph/public/components/settings/settings.tsx @@ -123,7 +123,7 @@ export const Settings = connect + (dispatch) => bindActionCreators( { updateSettings, diff --git a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx index e92d06c3b93a5..ba0017a16f393 100644 --- a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx @@ -100,7 +100,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { encoder: currentTemplate.encoder.type === 'kql' ? currentTemplate.encoder - : outlinkEncoders.find(enc => enc.type === 'kql')!, + : outlinkEncoders.find((enc) => enc.type === 'kql')!, }); setAutoformatUrl(false); } @@ -131,13 +131,13 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { 'gphUrlTemplateList__accordion--isOpen': open, })} buttonClassName="gphUrlTemplateList__accordionbutton" - onToggle={isOpen => { + onToggle={(isOpen) => { setOpen(isOpen); }} paddingSize="m" > { + onSubmit={(e) => { e.preventDefault(); onSubmit(currentTemplate); if (!isUpdateForm(props)) { @@ -157,7 +157,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth value={currentTemplate.description} isInvalid={touched.description && !currentTemplate.description} - onChange={e => setValue('description', e.target.value)} + onChange={(e) => setValue('description', e.target.value)} placeholder={i18n.translate( 'xpack.graph.settings.drillDowns.urlDescriptionInputPlaceholder', { defaultMessage: 'Search on Google' } @@ -212,11 +212,11 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth placeholder="https://www.google.co.uk/#q={{gquery}}" value={currentTemplate.url} - onChange={e => { + onChange={(e) => { setValue('url', e.target.value); setAutoformatUrl(false); }} - onPaste={e => { + onPaste={(e) => { e.preventDefault(); const pastedUrl = e.clipboardData.getData('text/plain'); if (isKibanaUrl(pastedUrl)) { @@ -238,14 +238,14 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth singleSelection={{ asPlainText: true }} isClearable={false} - options={outlinkEncoders.map(encoder => ({ label: encoder.title, value: encoder }))} + options={outlinkEncoders.map((encoder) => ({ label: encoder.title, value: encoder }))} selectedOptions={[ { label: currentTemplate.encoder.title, value: currentTemplate.encoder, }, ]} - onChange={choices => { + onChange={(choices) => { // choices[0].value can't be null because `isClearable` is set to false above setValue('encoder', choices[0].value!); }} @@ -258,7 +258,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { })} >

- {urlTemplateIconChoices.map(icon => ( + {urlTemplateIconChoices.map((icon) => ( formId !== id)); + setUncommittedForms(uncommittedForms.filter((formId) => formId !== id)); } return ( @@ -39,7 +39,7 @@ export function UrlTemplateList({ key={getListKey(template)} id={getListKey(template)} initialTemplate={template} - onSubmit={newTemplate => { + onSubmit={(newTemplate) => { saveTemplate({ index, template: newTemplate }); }} onRemove={() => { @@ -48,11 +48,11 @@ export function UrlTemplateList({ /> ))} - {uncommittedForms.map(id => ( + {uncommittedForms.map((id) => ( { + onSubmit={(newTemplate) => { saveTemplate({ index: -1, template: newTemplate }); removeUncommittedForm(id); }} diff --git a/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx b/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx index 08821c39a58c4..c80296feccdd4 100644 --- a/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx +++ b/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx @@ -36,7 +36,7 @@ describe('use_list_keys', () => { }); expect(instance.find('li').length).toEqual(5); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { expect(ids.has(el.key())).toEqual(true); }); }); @@ -72,7 +72,7 @@ describe('use_list_keys', () => { }); expect(instance.find('li').length).toEqual(4); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { expect(ids.has(el.key())).toEqual(true); }); }); @@ -80,7 +80,7 @@ describe('use_list_keys', () => { function collectIds(instance: ReactWrapper) { const ids = new Set(); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { ids.add(el.key()); }); return ids; diff --git a/x-pack/plugins/graph/public/components/settings/use_list_keys.ts b/x-pack/plugins/graph/public/components/settings/use_list_keys.ts index 790d1d77615a5..ecf81d53056d4 100644 --- a/x-pack/plugins/graph/public/components/settings/use_list_keys.ts +++ b/x-pack/plugins/graph/public/components/settings/use_list_keys.ts @@ -30,7 +30,7 @@ export function useListKeys(list: T[]) { const idStore = useRef>(new Map()); const currentIdMap = useMemo(() => { const newMap: Map = new Map(); - list.forEach(item => { + list.forEach((item) => { if (idStore.current.has(item)) { newMap.set(item, idStore.current.get(item)!); } else { diff --git a/x-pack/plugins/graph/public/components/source_picker.tsx b/x-pack/plugins/graph/public/components/source_picker.tsx index 9172f6ba1c65c..acc965eaf3276 100644 --- a/x-pack/plugins/graph/public/components/source_picker.tsx +++ b/x-pack/plugins/graph/public/components/source_picker.tsx @@ -42,7 +42,7 @@ export function SourcePicker({ name: i18n.translate('xpack.graph.sourceModal.savedObjectType.indexPattern', { defaultMessage: 'Index pattern', }), - showSavedObject: indexPattern => !indexPattern.attributes.type, + showSavedObject: (indexPattern) => !indexPattern.attributes.type, includeFields: ['type'], }, ]} diff --git a/x-pack/plugins/graph/public/helpers/as_observable.ts b/x-pack/plugins/graph/public/helpers/as_observable.ts index 48372521babaf..f095002ef25cc 100644 --- a/x-pack/plugins/graph/public/helpers/as_observable.ts +++ b/x-pack/plugins/graph/public/helpers/as_observable.ts @@ -26,7 +26,7 @@ interface Props { export function asAngularSyncedObservable(collectProps: () => Props, angularDigest: () => void) { const boundCollectProps = () => { const collectedProps = collectProps(); - Object.keys(collectedProps).forEach(key => { + Object.keys(collectedProps).forEach((key) => { const currentValue = collectedProps[key]; if (typeof currentValue === 'function') { collectedProps[key] = (...args: unknown[]) => { diff --git a/x-pack/plugins/graph/public/helpers/kql_encoder.ts b/x-pack/plugins/graph/public/helpers/kql_encoder.ts index a12917fb93daa..3cdf8d91352c2 100644 --- a/x-pack/plugins/graph/public/helpers/kql_encoder.ts +++ b/x-pack/plugins/graph/public/helpers/kql_encoder.ts @@ -15,7 +15,7 @@ function escapeQuotes(str: string) { export function asKQL(workspace: Workspace, joinBy: 'and' | 'or') { const nodes = workspace.returnUnpackedGroupeds(workspace.getSelectedOrAllNodes()); const clauses = nodes.map( - node => `"${escapeQuotes(node.data.field)}" : "${escapeQuotes(node.data.term)}"` + (node) => `"${escapeQuotes(node.data.field)}" : "${escapeQuotes(node.data.term)}"` ); const expression = clauses.join(` ${joinBy} `); diff --git a/x-pack/plugins/graph/public/helpers/outlink_encoders.ts b/x-pack/plugins/graph/public/helpers/outlink_encoders.ts index 437641f3f2e8a..3590150fb7305 100644 --- a/x-pack/plugins/graph/public/helpers/outlink_encoders.ts +++ b/x-pack/plugins/graph/public/helpers/outlink_encoders.ts @@ -152,7 +152,7 @@ export const outlinkEncoders: OutlinkEncoder[] = [ const luceneChars = '+-&|!(){}[]^"~*?:\\'; q = q .split('') - .map(char => (luceneChars.includes(char) ? `\\${char}` : char)) + .map((char) => (luceneChars.includes(char) ? `\\${char}` : char)) .join(''); return encodeURIComponent(q); }, diff --git a/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts b/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts index 2933e94b86e86..421a72c989757 100644 --- a/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts +++ b/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts @@ -74,10 +74,10 @@ export function findSavedWorkspace( perPage: size, searchFields: ['title^3', 'description'], }) - .then(resp => { + .then((resp) => { return { total: resp.total, - hits: resp.savedObjects.map(hit => mapHits(hit, urlFor(basePath, hit.id))), + hits: resp.savedObjects.map((hit) => mapHits(hit, urlFor(basePath, hit.id))), }; }); } diff --git a/x-pack/plugins/graph/public/helpers/style_choices.ts b/x-pack/plugins/graph/public/helpers/style_choices.ts index 46fec39bfce06..f228c9f052b6b 100644 --- a/x-pack/plugins/graph/public/helpers/style_choices.ts +++ b/x-pack/plugins/graph/public/helpers/style_choices.ts @@ -167,12 +167,12 @@ export const iconChoices = [ ]; export const getSuitableIcon = (fieldName: string) => - iconChoices.find(choice => choice.patterns.some(pattern => pattern.test(fieldName))) || + iconChoices.find((choice) => choice.patterns.some((pattern) => pattern.test(fieldName))) || iconChoices[0]; export const iconChoicesByClass: Partial> = {}; -iconChoices.forEach(icon => { +iconChoices.forEach((icon) => { iconChoicesByClass[icon.class] = icon; }); @@ -251,7 +251,7 @@ export const urlTemplateIconChoices = [ ]; export const urlTemplateIconChoicesByClass: Partial> = {}; -urlTemplateIconChoices.forEach(icon => { +urlTemplateIconChoices.forEach((icon) => { urlTemplateIconChoicesByClass[icon.class] = icon; }); diff --git a/x-pack/plugins/graph/public/plugin.ts b/x-pack/plugins/graph/public/plugin.ts index 9d6d083b3e4b9..e97735c50388f 100644 --- a/x-pack/plugins/graph/public/plugin.ts +++ b/x-pack/plugins/graph/public/plugin.ts @@ -107,7 +107,7 @@ export class GraphPlugin if (this.licensing === null) { throw new Error('Start called before setup'); } - this.licensing.license$.subscribe(license => { + this.licensing.license$.subscribe((license) => { toggleNavLink(checkLicense(license), core.chrome.navLinks); }); } diff --git a/x-pack/plugins/graph/public/services/fetch_top_nodes.ts b/x-pack/plugins/graph/public/services/fetch_top_nodes.ts index d7df3513dba8d..f1f701498372b 100644 --- a/x-pack/plugins/graph/public/services/fetch_top_nodes.ts +++ b/x-pack/plugins/graph/public/services/fetch_top_nodes.ts @@ -55,7 +55,7 @@ function getTopTermsResult(response: TopTermsAggResponse, fieldName: string) { return []; } return response.aggregations.sample[createTopTermsAggName(fieldName)].buckets.map( - bucket => bucket.key + (bucket) => bucket.key ); } @@ -91,7 +91,7 @@ export async function fetchTopNodes( ) { const aggs = fields .map(({ name }) => name) - .map(fieldName => createTopTermsSubAgg(fieldName)) + .map((fieldName) => createTopTermsSubAgg(fieldName)) .reduce((allAggs, subAgg) => ({ ...allAggs, ...subAgg })); const body = createSamplerSearchBody(aggs); @@ -105,7 +105,7 @@ export async function fetchTopNodes( fields.forEach(({ name }) => { const topTerms = getTopTermsResult(response, name); - const fieldNodes = topTerms.map(term => createServerResultNode(name, term, fields)); + const fieldNodes = topTerms.map((term) => createServerResultNode(name, term, fields)); nodes.push(...fieldNodes); }); diff --git a/x-pack/plugins/graph/public/services/persistence/deserialize.ts b/x-pack/plugins/graph/public/services/persistence/deserialize.ts index 06106ed4c4f3f..6fd720a60edc0 100644 --- a/x-pack/plugins/graph/public/services/persistence/deserialize.ts +++ b/x-pack/plugins/graph/public/services/persistence/deserialize.ts @@ -42,7 +42,7 @@ function deserializeUrlTemplate({ iconClass, ...serializableProps }: SerializedUrlTemplate) { - const encoder = outlinkEncoders.find(outlinkEncoder => outlinkEncoder.id === encoderID); + const encoder = outlinkEncoders.find((outlinkEncoder) => outlinkEncoder.id === encoderID); if (!encoder) { return; } @@ -68,7 +68,7 @@ export function lookupIndexPattern( ) { const serializedWorkspaceState: SerializedWorkspaceState = JSON.parse(savedWorkspace.wsState); const indexPattern = indexPatterns.find( - pattern => pattern.attributes.title === serializedWorkspaceState.indexPattern + (pattern) => pattern.attributes.title === serializedWorkspaceState.indexPattern ); if (indexPattern) { @@ -84,7 +84,7 @@ export function mapFields(indexPattern: IndexPattern): WorkspaceField[] { return indexPattern .getNonScriptedFields() .filter( - field => !blockedFieldNames.includes(field.name) && !indexPatternsUtils.isNestedField(field) + (field) => !blockedFieldNames.includes(field.name) && !indexPatternsUtils.isNestedField(field) ) .map((field, index) => ({ name: field.name, @@ -113,8 +113,8 @@ function getFieldsWithWorkspaceSettings( const allFields = mapFields(indexPattern); // merge in selected information into all fields - selectedFields.forEach(serializedField => { - const workspaceField = allFields.find(field => field.name === serializedField.name); + selectedFields.forEach((serializedField) => { + const workspaceField = allFields.find((field) => field.name === serializedField.name); if (!workspaceField) { return; } @@ -132,8 +132,8 @@ function getBlacklistedNodes( serializedWorkspaceState: SerializedWorkspaceState, allFields: WorkspaceField[] ) { - return serializedWorkspaceState.blacklist.map(serializedNode => { - const currentField = allFields.find(field => field.name === serializedNode.field)!; + return serializedWorkspaceState.blacklist.map((serializedNode) => { + const currentField = allFields.find((field) => field.name === serializedNode.field)!; return { x: 0, y: 0, @@ -169,16 +169,16 @@ function getNodesAndEdges( allFields: WorkspaceField[] ): GraphData { return { - nodes: persistedWorkspaceState.vertices.map(serializedNode => ({ + nodes: persistedWorkspaceState.vertices.map((serializedNode) => ({ ...serializedNode, id: '', - icon: allFields.find(field => field.name === serializedNode.field)!.icon, + icon: allFields.find((field) => field.name === serializedNode.field)!.icon, data: { field: serializedNode.field, term: serializedNode.term, }, })), - edges: persistedWorkspaceState.links.map(serializedEdge => ({ + edges: persistedWorkspaceState.links.map((serializedEdge) => ({ ...serializedEdge, id: '', })), @@ -210,7 +210,7 @@ export function savedWorkspaceToAppState( indexPattern, persistedWorkspaceState.selectedFields ); - const selectedFields = allFields.filter(field => field.selected); + const selectedFields = allFields.filter((field) => field.selected); workspaceInstance.options.vertex_fields = selectedFields; // ================== advanced settings ============================= @@ -224,7 +224,7 @@ export function savedWorkspaceToAppState( // restore reference to sample diversity field const serializedField = advancedSettings.sampleDiversityField; advancedSettings.sampleDiversityField = allFields.find( - field => field.name === serializedField.name + (field) => field.name === serializedField.name ); } diff --git a/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts b/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts index 0948d7a88fce8..c92c831242ad2 100644 --- a/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts +++ b/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts @@ -53,7 +53,7 @@ export function injectReferences( return; } const indexPatternReference = references.find( - reference => reference.name === state.indexPatternRefName + (reference) => reference.name === state.indexPatternRefName ); if (!indexPatternReference) { // Throw an error as "indexPatternRefName" means the reference exists within diff --git a/x-pack/plugins/graph/public/services/persistence/serialize.ts b/x-pack/plugins/graph/public/services/persistence/serialize.ts index cc6af1b9222f1..6cbebc995d84a 100644 --- a/x-pack/plugins/graph/public/services/persistence/serialize.ts +++ b/x-pack/plugins/graph/public/services/persistence/serialize.ts @@ -97,13 +97,13 @@ export function appStateToSavedWorkspace( canSaveData: boolean ) { const blacklist: SerializedNode[] = canSaveData - ? workspace.blacklistedNodes.map(node => serializeNode(node)) + ? workspace.blacklistedNodes.map((node) => serializeNode(node)) : []; const vertices: SerializedNode[] = canSaveData - ? workspace.nodes.map(node => serializeNode(node, workspace.nodes)) + ? workspace.nodes.map((node) => serializeNode(node, workspace.nodes)) : []; const links: SerializedEdge[] = canSaveData - ? workspace.edges.map(edge => serializeEdge(edge, workspace.nodes)) + ? workspace.edges.map((edge) => serializeEdge(edge, workspace.nodes)) : []; const mappedUrlTemplates = urlTemplates.map(serializeUrlTemplate); diff --git a/x-pack/plugins/graph/public/services/save_modal.tsx b/x-pack/plugins/graph/public/services/save_modal.tsx index 94b5de3be13ac..730fe7b065e47 100644 --- a/x-pack/plugins/graph/public/services/save_modal.tsx +++ b/x-pack/plugins/graph/public/services/save_modal.tsx @@ -60,7 +60,7 @@ export function openSaveModal({ isTitleDuplicateConfirmed, onTitleDuplicate, }; - return saveWorkspace(saveOptions, dataConsent, services).then(response => { + return saveWorkspace(saveOptions, dataConsent, services).then((response) => { // If the save wasn't successful, put the original values back. if (!('id' in response) || !Boolean(response.id)) { workspace.title = currentTitle; diff --git a/x-pack/plugins/graph/public/services/source_modal.tsx b/x-pack/plugins/graph/public/services/source_modal.tsx index 20a5b6d0786bd..d5ffe4c0c9651 100644 --- a/x-pack/plugins/graph/public/services/source_modal.tsx +++ b/x-pack/plugins/graph/public/services/source_modal.tsx @@ -26,7 +26,7 @@ export function openSourceModal( { + onIndexPatternSelected={(indexPattern) => { onSelected(indexPattern); modalRef.close(); }} diff --git a/x-pack/plugins/graph/public/state_management/advanced_settings.ts b/x-pack/plugins/graph/public/state_management/advanced_settings.ts index e6325c1e7fd68..27c784ba71ee1 100644 --- a/x-pack/plugins/graph/public/state_management/advanced_settings.ts +++ b/x-pack/plugins/graph/public/state_management/advanced_settings.ts @@ -52,7 +52,7 @@ export const syncSettingsSaga = ({ getWorkspace, notifyAngular }: GraphStoreDepe notifyAngular(); } - return function*() { + return function* () { yield takeLatest(updateSettings.match, syncSettings); }; }; diff --git a/x-pack/plugins/graph/public/state_management/datasource.sagas.ts b/x-pack/plugins/graph/public/state_management/datasource.sagas.ts index 018b3b42b9157..f468ce5beb21c 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.sagas.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.sagas.ts @@ -50,7 +50,7 @@ export const datasourceSaga = ({ } } - return function*() { + return function* () { yield takeLatest(requestDatasource.match, fetchFields); }; }; diff --git a/x-pack/plugins/graph/public/state_management/datasource.test.ts b/x-pack/plugins/graph/public/state_management/datasource.test.ts index 84f3741604e20..13b7080d776a2 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.test.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.test.ts @@ -12,7 +12,7 @@ import { fieldsSelector } from './fields'; import { updateSettings } from './advanced_settings'; import { IndexPattern } from '../../../../../src/plugins/data/public'; -const waitForPromise = () => new Promise(r => setTimeout(r)); +const waitForPromise = () => new Promise((r) => setTimeout(r)); describe('datasource saga', () => { let env: MockedGraphEnvironment; diff --git a/x-pack/plugins/graph/public/state_management/datasource.ts b/x-pack/plugins/graph/public/state_management/datasource.ts index fac4f0da1edb0..4f86b6b0fd072 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.ts @@ -57,7 +57,7 @@ export const datasourceReducer = reducerWithInitialState(initia current: newDatasource, loading: true, })) - .case(datasourceLoaded, datasource => ({ + .case(datasourceLoaded, (datasource) => ({ ...datasource, loading: false, })) @@ -66,5 +66,5 @@ export const datasourceReducer = reducerWithInitialState(initia export const datasourceSelector = (state: GraphState) => state.datasource; export const hasDatasourceSelector = createSelector( datasourceSelector, - datasource => datasource.current.type !== 'none' + (datasource) => datasource.current.type !== 'none' ); diff --git a/x-pack/plugins/graph/public/state_management/fields.ts b/x-pack/plugins/graph/public/state_management/fields.ts index 865de323332c4..a54f9fd07b166 100644 --- a/x-pack/plugins/graph/public/state_management/fields.ts +++ b/x-pack/plugins/graph/public/state_management/fields.ts @@ -33,7 +33,7 @@ export const fieldsReducer = reducerWithInitialState(initialFields) .case(setDatasource, () => initialFields) .case(loadFields, (_currentFields, newFields) => { const newFieldMap: Record = {}; - newFields.forEach(field => { + newFields.forEach((field) => { newFieldMap[field.name] = field; }); @@ -51,16 +51,16 @@ export const fieldsReducer = reducerWithInitialState(initialFields) .build(); export const fieldMapSelector = (state: GraphState) => state.fields; -export const fieldsSelector = createSelector(fieldMapSelector, fields => Object.values(fields)); -export const selectedFieldsSelector = createSelector(fieldsSelector, fields => - fields.filter(field => field.selected) +export const fieldsSelector = createSelector(fieldMapSelector, (fields) => Object.values(fields)); +export const selectedFieldsSelector = createSelector(fieldsSelector, (fields) => + fields.filter((field) => field.selected) ); -export const liveResponseFieldsSelector = createSelector(selectedFieldsSelector, fields => - fields.filter(field => field.hopSize && field.hopSize > 0) +export const liveResponseFieldsSelector = createSelector(selectedFieldsSelector, (fields) => + fields.filter((field) => field.hopSize && field.hopSize > 0) ); export const hasFieldsSelector = createSelector( selectedFieldsSelector, - fields => fields.length > 0 + (fields) => fields.length > 0 ); /** @@ -72,7 +72,7 @@ export const updateSaveButtonSaga = ({ notifyAngular }: GraphStoreDependencies) function* notify(): IterableIterator { notifyAngular(); } - return function*() { + return function* () { yield takeLatest(matchesOne(selectField, deselectField), notify); }; }; @@ -94,7 +94,7 @@ export const syncFieldsSaga = ({ getWorkspace, setLiveResponseFields }: GraphSto workspace.options.vertex_fields = selectedFieldsSelector(currentState); setLiveResponseFields(liveResponseFieldsSelector(currentState)); } - return function*() { + return function* () { yield takeEvery( matchesOne(loadFields, selectField, deselectField, updateFieldProperties), syncFields @@ -116,7 +116,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep } const newColor = action.payload.fieldProperties.color; if (newColor) { - workspace.nodes.forEach(function(node) { + workspace.nodes.forEach(function (node) { if (node.data.field === action.payload.fieldName) { node.color = newColor; } @@ -125,7 +125,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep const newIcon = action.payload.fieldProperties.icon; if (newIcon) { - workspace.nodes.forEach(function(node) { + workspace.nodes.forEach(function (node) { if (node.data.field === action.payload.fieldName) { node.icon = newIcon; } @@ -137,7 +137,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep workspace.options.vertex_fields = selectedFields; } - return function*() { + return function* () { yield takeLatest(updateFieldProperties.match, syncNodeStyle); }; }; diff --git a/x-pack/plugins/graph/public/state_management/helpers.ts b/x-pack/plugins/graph/public/state_management/helpers.ts index 215691d454484..05773e545ec5e 100644 --- a/x-pack/plugins/graph/public/state_management/helpers.ts +++ b/x-pack/plugins/graph/public/state_management/helpers.ts @@ -25,4 +25,4 @@ export type InferActionType = X extends ActionCreator ? T : never; * @param actionCreators The action creators to create a unified matcher for */ export const matchesOne = (...actionCreators: Array>) => (action: AnyAction) => - actionCreators.some(actionCreator => actionCreator.match(action)); + actionCreators.some((actionCreator) => actionCreator.match(action)); diff --git a/x-pack/plugins/graph/public/state_management/meta_data.ts b/x-pack/plugins/graph/public/state_management/meta_data.ts index 560216568f65f..5ed2b68e22c86 100644 --- a/x-pack/plugins/graph/public/state_management/meta_data.ts +++ b/x-pack/plugins/graph/public/state_management/meta_data.ts @@ -53,7 +53,7 @@ export const syncBreadcrumbSaga = ({ chrome, changeUrl }: GraphStoreDependencies }, }); } - return function*() { + return function* () { // initial sync yield call(syncBreadcrumb); yield takeLatest(updateMetaData.match, syncBreadcrumb); diff --git a/x-pack/plugins/graph/public/state_management/mocks.ts b/x-pack/plugins/graph/public/state_management/mocks.ts index 02a5830ffd6be..5a0269d691de2 100644 --- a/x-pack/plugins/graph/public/state_management/mocks.ts +++ b/x-pack/plugins/graph/public/state_management/mocks.ts @@ -103,7 +103,7 @@ export function createMockGraphStore({ store.dispatch = jest.fn(store.dispatch); - sagas.forEach(sagaCreator => { + sagas.forEach((sagaCreator) => { sagaMiddleware.run(sagaCreator(mockedDeps)); }); diff --git a/x-pack/plugins/graph/public/state_management/persistence.test.ts b/x-pack/plugins/graph/public/state_management/persistence.test.ts index 285bf2d6a0ea9..efad5f95fd839 100644 --- a/x-pack/plugins/graph/public/state_management/persistence.test.ts +++ b/x-pack/plugins/graph/public/state_management/persistence.test.ts @@ -15,7 +15,7 @@ import { lookupIndexPattern, appStateToSavedWorkspace } from '../services/persis import { settingsSelector } from './advanced_settings'; import { openSaveModal } from '../services/save_modal'; -const waitForPromise = () => new Promise(r => setTimeout(r)); +const waitForPromise = () => new Promise((r) => setTimeout(r)); jest.mock('../services/persistence', () => ({ lookupIndexPattern: jest.fn(() => ({ id: '123', attributes: { title: 'test-pattern' } })), diff --git a/x-pack/plugins/graph/public/state_management/persistence.ts b/x-pack/plugins/graph/public/state_management/persistence.ts index 8dd1386f70e6e..cd2c6680c1fd2 100644 --- a/x-pack/plugins/graph/public/state_management/persistence.ts +++ b/x-pack/plugins/graph/public/state_management/persistence.ts @@ -87,7 +87,7 @@ export const loadingSaga = ({ getWorkspace()!.runLayout(); } - return function*() { + return function* () { yield takeLatest(loadSavedWorkspace.match, deserializeWorkspace); }; }; @@ -119,7 +119,7 @@ export const savingSaga = (deps: GraphStoreDependencies) => { } } - return function*() { + return function* () { yield takeLatest(saveWorkspace.match, persistWorkspace); }; }; diff --git a/x-pack/plugins/graph/public/state_management/url_templates.ts b/x-pack/plugins/graph/public/state_management/url_templates.ts index d9f95a498ea5b..19de52d444209 100644 --- a/x-pack/plugins/graph/public/state_management/url_templates.ts +++ b/x-pack/plugins/graph/public/state_management/url_templates.ts @@ -35,7 +35,7 @@ function generateDefaultTemplate( datasource: IndexpatternDatasource, addBasePath: (url: string) => string ): UrlTemplate { - const appPath = modifyUrl('/', parsed => { + const appPath = modifyUrl('/', (parsed) => { parsed.query._a = rison.encode({ columns: ['_source'], index: datasource.id, @@ -78,7 +78,7 @@ export const urlTemplatesReducer = (addBasePath: (url: string) => string) => if (datasource.type === 'none') { return initialTemplates; } - const customTemplates = templates.filter(template => !template.isDefault); + const customTemplates = templates.filter((template) => !template.isDefault); return [...customTemplates, generateDefaultTemplate(datasource, addBasePath)]; }) .case(loadTemplates, (_currentTemplates, newTemplates) => newTemplates) @@ -90,7 +90,7 @@ export const urlTemplatesReducer = (addBasePath: (url: string) => string) => : templates.map((template, index) => (index === indexToUpdate ? newTemplate : template)); }) .case(removeTemplate, (templates, templateToDelete) => - templates.filter(template => template !== templateToDelete) + templates.filter((template) => template !== templateToDelete) ) .build(); @@ -108,7 +108,7 @@ export const syncTemplatesSaga = ({ setUrlTemplates, notifyAngular }: GraphStore notifyAngular(); } - return function*() { + return function* () { yield takeEvery( matchesOne(loadTemplates, saveTemplate, removeTemplate, requestDatasource, setDatasource), syncTemplates diff --git a/x-pack/plugins/graph/public/state_management/workspace.ts b/x-pack/plugins/graph/public/state_management/workspace.ts index b18b8185ceeca..7c28d09c6424f 100644 --- a/x-pack/plugins/graph/public/state_management/workspace.ts +++ b/x-pack/plugins/graph/public/state_management/workspace.ts @@ -60,7 +60,7 @@ export const fillWorkspaceSaga = ({ } } - return function*() { + return function* () { yield takeLatest(fillWorkspace.match, fetchNodes); }; }; diff --git a/x-pack/plugins/graph/server/routes/explore.ts b/x-pack/plugins/graph/server/routes/explore.ts index ceced840bdbc6..cb4a6a3577915 100644 --- a/x-pack/plugins/graph/server/routes/explore.ts +++ b/x-pack/plugins/graph/server/routes/explore.ts @@ -57,7 +57,7 @@ export function registerExploreRoute({ error, 'body.error.root_cause', [] as Array<{ type: string; reason: string }> - ).find(cause => { + ).find((cause) => { return ( cause.reason.includes('Fielddata is disabled on text fields') || cause.reason.includes('No support for examining floating point') || diff --git a/x-pack/plugins/graph/server/sample_data/register_sample_data.ts b/x-pack/plugins/graph/server/sample_data/register_sample_data.ts index 9a05b656b61a4..d11f5ce7bb489 100644 --- a/x-pack/plugins/graph/server/sample_data/register_sample_data.ts +++ b/x-pack/plugins/graph/server/sample_data/register_sample_data.ts @@ -25,7 +25,7 @@ export function registerSampleData( throw new Error('License state has to be initialized before registering sample data'); } let registered = false; - licenseUpdates.subscribe(licenseInformation => { + licenseUpdates.subscribe((licenseInformation) => { if (!registered && licenseInformation.showAppLink) { registered = true; registerEcommerceSampleDataLink(sampleDataRegistry); diff --git a/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js b/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js index c27f3314e60ae..83be5520943b1 100644 --- a/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js +++ b/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js @@ -37,17 +37,17 @@ export class GrokDebuggerComponent extends React.Component { this.grokdebuggerRequest = new GrokdebuggerRequest(); } - onRawEventChange = rawEvent => { + onRawEventChange = (rawEvent) => { this.setState({ rawEvent }); this.grokdebuggerRequest.rawEvent = rawEvent.trimEnd(); }; - onPatternChange = pattern => { + onPatternChange = (pattern) => { this.setState({ pattern }); this.grokdebuggerRequest.pattern = pattern.trimEnd(); }; - onCustomPatternsChange = customPatterns => { + onCustomPatternsChange = (customPatterns) => { this.setState({ customPatterns }); customPatterns = customPatterns.trim(); @@ -58,7 +58,7 @@ export class GrokDebuggerComponent extends React.Component { return; } - customPatterns.split('\n').forEach(customPattern => { + customPatterns.split('\n').forEach((customPattern) => { // Patterns are defined like so: // patternName patternDefinition // For example: diff --git a/x-pack/plugins/grokdebugger/public/plugin.js b/x-pack/plugins/grokdebugger/public/plugin.js index 5f1534df9f0ae..6ac600c9dc97b 100644 --- a/x-pack/plugins/grokdebugger/public/plugin.js +++ b/x-pack/plugins/grokdebugger/public/plugin.js @@ -28,7 +28,7 @@ export class Plugin { }, }); - plugins.licensing.license$.subscribe(license => { + plugins.licensing.license$.subscribe((license) => { if (!license.isActive && !devTool.isDisabled()) { devTool.disable(); } else if (devTool.isDisabled()) { diff --git a/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js b/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js index e26c9c5091e14..207093e72ca2c 100644 --- a/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js +++ b/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js @@ -17,10 +17,10 @@ export class GrokdebuggerService { .post(`${ROUTES.API_ROOT}/simulate`, { body: JSON.stringify(grokdebuggerRequest.upstreamJSON), }) - .then(response => { + .then((response) => { return GrokdebuggerResponse.fromUpstreamJSON(response); }) - .catch(e => { + .catch((e) => { throw e.body.message; }); } diff --git a/x-pack/plugins/grokdebugger/server/plugin.js b/x-pack/plugins/grokdebugger/server/plugin.js index 06ddd92aefac9..49298fd1e5ab7 100644 --- a/x-pack/plugins/grokdebugger/server/plugin.js +++ b/x-pack/plugins/grokdebugger/server/plugin.js @@ -18,7 +18,7 @@ export class Plugin { setup(coreSetup, plugins) { const framework = new KibanaFramework(coreSetup); - plugins.licensing.license$.subscribe(license => { + plugins.licensing.license$.subscribe((license) => { framework.setLicense(license); }); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js index bf4de823f1833..c249a45fe8ed2 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js @@ -35,7 +35,7 @@ import { maximumDocumentsRequiredMessage, } from '../../public/application/store/selectors/lifecycle'; -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); initNotification({ addDanger: () => {}, @@ -59,9 +59,7 @@ const policies = []; for (let i = 0; i < 105; i++) { policies.push({ version: i, - modified_date: moment() - .subtract(i, 'days') - .valueOf(), + modified_date: moment().subtract(i, 'days').valueOf(), linkedIndices: i % 2 === 0 ? [`index${i}`] : null, name: `testy${i}`, policy: { @@ -80,7 +78,7 @@ const activatePhase = (rendered, phase) => { const expectedErrorMessages = (rendered, expectedErrorMessages) => { const errorMessages = rendered.find('.euiFormErrorText'); expect(errorMessages.length).toBe(expectedErrorMessages.length); - expectedErrorMessages.forEach(expectedErrorMessage => { + expectedErrorMessages.forEach((expectedErrorMessage) => { let foundErrorMessage; for (let i = 0; i < errorMessages.length; i++) { if (errorMessages.at(i).text() === expectedErrorMessage) { @@ -90,7 +88,7 @@ const expectedErrorMessages = (rendered, expectedErrorMessages) => { expect(foundErrorMessage).toBe(true); }); }; -const noRollover = rendered => { +const noRollover = (rendered) => { findTestSubject(rendered, 'rolloverSwitch').simulate('click'); rendered.update(); }; @@ -112,7 +110,7 @@ const setPhaseIndexPriority = (rendered, phase, priority) => { priorityInput.simulate('change', { target: { value: priority } }); rendered.update(); }; -const save = rendered => { +const save = (rendered) => { const saveButton = findTestSubject(rendered, 'savePolicyButton'); saveButton.simulate('click'); rendered.update(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js index 78c5c181eea62..52a9f28817e3a 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js @@ -19,7 +19,7 @@ import { PolicyTable } from '../../public/application/sections/policy_table'; import { init as initHttp } from '../../public/application/services/http'; import { init as initUiMetric } from '../../public/application/services/ui_metric'; -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); let server = null; @@ -29,9 +29,7 @@ const policies = []; for (let i = 0; i < 105; i++) { policies.push({ version: i, - modified_date: moment() - .subtract(i, 'days') - .valueOf(), + modified_date: moment().subtract(i, 'days').valueOf(), linkedIndices: i % 2 === 0 ? [`index${i}`] : null, name: `testy${i}`, }); @@ -39,20 +37,20 @@ for (let i = 0; i < 105; i++) { jest.mock(''); let component = null; -const snapshot = rendered => { +const snapshot = (rendered) => { expect(rendered).toMatchSnapshot(); }; -const mountedSnapshot = rendered => { +const mountedSnapshot = (rendered) => { expect(takeMountedSnapshot(rendered)).toMatchSnapshot(); }; -const names = rendered => { +const names = (rendered) => { return findTestSubject(rendered, 'policyTablePolicyNameLink'); }; -const namesText = rendered => { - return names(rendered).map(button => button.text()); +const namesText = (rendered) => { + return names(rendered).map((button) => button.text()); }; -const testSort = headerName => { +const testSort = (headerName) => { const rendered = mountWithIntl(component); const nameHeader = findTestSubject(rendered, `policyTableHeaderCell-${headerName}`).find( 'button' @@ -64,7 +62,7 @@ const testSort = headerName => { rendered.update(); snapshot(namesText(rendered)); }; -const openContextMenu = buttonIndex => { +const openContextMenu = (buttonIndex) => { const rendered = mountWithIntl(component); const actionsButton = findTestSubject(rendered, 'policyActionsContextMenuButton'); actionsButton.at(buttonIndex).simulate('click'); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js index 900de27ca36ab..b5d9b91e8c412 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js @@ -23,7 +23,7 @@ import { init as initUiMetric } from '../public/application/services/ui_metric'; // We need to init the http with a mock for any tests that depend upon the http service. // For example, add_lifecycle_confirm_modal makes an API request in its componentDidMount // lifecycle method. If we don't mock this, CI will fail with "Call retries were exceeded". -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); jest.mock('../../../plugins/index_management/public', async () => { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js index 1f2468e79ebd3..d4605ceb43499 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js @@ -12,7 +12,7 @@ import { PHASE_COLD, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../const import { ColdPhase as PresentationComponent } from './cold_phase'; export const ColdPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_COLD), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js index 02cd1a968b617..d5c0744e5eb07 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js @@ -89,7 +89,7 @@ export class ColdPhase extends PureComponent { } id={`${PHASE_COLD}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="coldPhaseContent" @@ -146,7 +146,7 @@ export class ColdPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_REPLICA_COUNT, e.target.value); }} min={0} @@ -187,7 +187,7 @@ export class ColdPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_FREEZE_ENABLED, e.target.checked); }} label={freezeLabel} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js index 74ec9b2c98ed9..84bd17e3637e8 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js @@ -11,7 +11,7 @@ import { PHASE_DELETE, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../con import { DeletePhase as PresentationComponent } from './delete_phase'; export const DeletePhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_DELETE), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js index 146b5c36847db..3b3e489d38f7d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js @@ -63,7 +63,7 @@ export class DeletePhase extends PureComponent { } id={`${PHASE_DELETE}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="deletePhaseContent" diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js index 818af79466f6b..5f1451afdcc31 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js @@ -12,11 +12,11 @@ import { PHASE_HOT, PHASE_WARM, WARM_PHASE_ON_ROLLOVER } from '../../../../const import { HotPhase as PresentationComponent } from './hot_phase'; export const HotPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_HOT), }), { setPhaseData: (key, value) => setPhaseData(PHASE_HOT, key, value), - setWarmPhaseOnRollover: value => setPhaseData(PHASE_WARM, WARM_PHASE_ON_ROLLOVER, value), + setWarmPhaseOnRollover: (value) => setPhaseData(PHASE_WARM, WARM_PHASE_ON_ROLLOVER, value), } )(PresentationComponent); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js index 475d26bb2e3c0..b420442198712 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js @@ -100,7 +100,7 @@ export class HotPhase extends PureComponent { { + onChange={async (e) => { const { checked } = e.target; setPhaseData(PHASE_ROLLOVER_ENABLED, checked); setWarmPhaseOnRollover(checked); @@ -130,7 +130,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_SIZE_STORED, e.target.value); }} min={1} @@ -153,7 +153,7 @@ export class HotPhase extends PureComponent { } )} value={phaseData[PHASE_ROLLOVER_MAX_SIZE_STORED_UNITS]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_SIZE_STORED_UNITS, e.target.value); }} options={[ @@ -216,7 +216,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_DOCUMENTS, e.target.value); }} min={1} @@ -239,7 +239,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_AGE, e.target.value); }} min={1} @@ -262,7 +262,7 @@ export class HotPhase extends PureComponent { } )} value={phaseData[PHASE_ROLLOVER_MAX_AGE_UNITS]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_AGE_UNITS, e.target.value); }} options={[ diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js index 2300979851329..bfe1bbb04338c 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js @@ -68,7 +68,7 @@ function getUnitsAriaLabelForPhase(phase) { } } -export const MinAgeInput = props => { +export const MinAgeInput = (props) => { const { rolloverEnabled, errors, phaseData, phase, setPhaseData, isShowingErrors } = props; let daysOptionLabel; @@ -166,7 +166,7 @@ export const MinAgeInput = props => { { + onChange={async (e) => { setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE, e.target.value); }} min={0} @@ -178,7 +178,7 @@ export const MinAgeInput = props => { setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE_UNITS, e.target.value)} + onChange={(e) => setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE_UNITS, e.target.value)} options={[ { value: 'd', diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js index a92959a5b31cf..0ddfcbb940aa4 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js @@ -11,7 +11,7 @@ import { fetchNodes } from '../../../../store/actions'; import { NodeAllocation as PresentationComponent } from './node_allocation'; export const NodeAllocation = connect( - state => ({ + (state) => ({ nodeOptions: getNodeOptions(state), }), { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js index 528aa85beaecc..95c1878776688 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js @@ -92,7 +92,7 @@ export class NodeAllocation extends Component { id={`${phase}-${PHASE_NODE_ATTRS}`} value={phaseData[PHASE_NODE_ATTRS] || ' '} options={nodeOptions} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_NODE_ATTRS, e.target.value); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js index 09db792b689da..bdcc1e23b4230 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js @@ -11,7 +11,7 @@ import { PHASE_INDEX_PRIORITY } from '../../../constants'; import { LearnMoreLink, OptionalLabel } from '../../components'; import { ErrableFormRow } from '../form_errors'; -export const SetPriorityInput = props => { +export const SetPriorityInput = (props) => { const { errors, phaseData, phase, setPhaseData, isShowingErrors } = props; return ( @@ -55,7 +55,7 @@ export const SetPriorityInput = props => { { + onChange={(e) => { setPhaseData(PHASE_INDEX_PRIORITY, e.target.value); }} min={0} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js index e25360b94e029..d13ad31228860 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js @@ -12,7 +12,7 @@ import { PHASE_WARM, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../const import { WarmPhase as PresentationComponent } from './warm_phase'; export const WarmPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_WARM), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js index 133e6b617c71e..55aec88c8bcab 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js @@ -108,7 +108,7 @@ export class WarmPhase extends PureComponent { } id={`${PHASE_WARM}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="warmPhaseContent" @@ -127,7 +127,7 @@ export class WarmPhase extends PureComponent { label={moveToWarmPhaseOnRolloverLabel} id={`${PHASE_WARM}-${WARM_PHASE_ON_ROLLOVER}`} checked={phaseData[WARM_PHASE_ON_ROLLOVER]} - onChange={e => { + onChange={(e) => { setPhaseData(WARM_PHASE_ON_ROLLOVER, e.target.checked); }} /> @@ -184,7 +184,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_REPLICA_COUNT, e.target.value); }} min={0} @@ -225,7 +225,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_SHRINK_ENABLED, e.target.checked); }} label={shrinkLabel} @@ -254,7 +254,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_PRIMARY_SHARD_COUNT, e.target.value); }} min={1} @@ -294,7 +294,7 @@ export class WarmPhase extends PureComponent { label={forcemergeLabel} aria-label={forcemergeLabel} checked={phaseData[PHASE_FORCE_MERGE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_FORCE_MERGE_ENABLED, e.target.checked); }} aria-controls="forcemergeContent" @@ -318,7 +318,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_FORCE_MERGE_SEGMENTS, e.target.value); }} min={1} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js index 3e4ec06fa43e7..1c6ced8953211 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js @@ -29,7 +29,7 @@ import { findFirstError } from '../../services/find_errors'; import { EditPolicy as PresentationComponent } from './edit_policy'; export const EditPolicy = connect( - state => { + (state) => { const errors = validateLifecycle(state); const firstError = findFirstError(errors); return { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js index 040ce189ba2e6..94186b7fc79d7 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js @@ -63,10 +63,10 @@ export class EditPolicy extends Component { }; } - selectPolicy = policyName => { + selectPolicy = (policyName) => { const { setSelectedPolicy, policies } = this.props; - const selectedPolicy = policies.find(policy => { + const selectedPolicy = policies.find((policy) => { return policy.name === policyName; }); @@ -125,7 +125,7 @@ export class EditPolicy extends Component { } }; - showNodeDetailsFlyout = selectedNodeAttrsForDetails => { + showNodeDetailsFlyout = (selectedNodeAttrsForDetails) => { this.setState({ isShowingNodeDetailsFlyout: true, selectedNodeAttrsForDetails }); }; @@ -222,7 +222,7 @@ export class EditPolicy extends Component { data-test-subj="saveAsNewSwitch" style={{ maxWidth: '100%' }} checked={saveAsNewPolicy} - onChange={async e => { + onChange={async (e) => { await setSaveAsNewPolicy(e.target.checked); }} label={ @@ -271,7 +271,7 @@ export class EditPolicy extends Component { { + onChange={async (e) => { await setSelectedPolicyName(e.target.value); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js index 4b50e19f9baaa..28ebad209ad96 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js @@ -15,7 +15,7 @@ export const ErrableFormRow = ({ errorKey, isShowingErrors, errors, children, .. {...rest} > - {Children.map(children, child => + {Children.map(children, (child) => cloneElement(child, { isInvalid: isShowingErrors && errors[errorKey].length > 0, }) diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js index 6129678edf3b7..8e53569047d8f 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js @@ -108,7 +108,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { } getSelectedTemplate() { const { templates, templateName } = this.state; - return find(templates, template => template.name === templateName); + return find(templates, (template) => template.name === templateName); } renderForm() { const { templates, templateName, templateError } = this.state; @@ -143,7 +143,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { { + onChange={(e) => { this.setState({ templateError: null, templateName: e.target.value }); }} /> @@ -170,7 +170,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { > { + onChange={(e) => { this.setState({ aliasName: e.target.value }); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js index 7db980abeba8a..8bd78774d2d55 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js @@ -25,28 +25,28 @@ import { import { PolicyTable as PresentationComponent } from './policy_table'; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - policyFilterChanged: filter => { + policyFilterChanged: (filter) => { dispatch(policyFilterChanged({ filter })); }, - policyPageChanged: pageNumber => { + policyPageChanged: (pageNumber) => { dispatch(policyPageChanged({ pageNumber })); }, - policyPageSizeChanged: pageSize => { + policyPageSizeChanged: (pageSize) => { dispatch(policyPageSizeChanged({ pageSize })); }, policySortChanged: (sortField, isSortAscending) => { dispatch(policySortChanged({ sortField, isSortAscending })); }, - fetchPolicies: withIndices => { + fetchPolicies: (withIndices) => { dispatch(fetchPolicies(withIndices)); }, }; }; export const PolicyTable = connect( - state => ({ + (state) => ({ totalNumberOfPolicies: getPolicies(state).length, policies: getPageOfPolicies(state), pager: getPolicyPager(state), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js index d406d86bc6ce7..d9d74becf9e5d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js @@ -141,7 +141,7 @@ export class PolicyTable extends Component { this.props.fetchPolicies(true); this.setState({ renderDeleteConfirmModal: null, policyToDelete: null }); }; - onSort = column => { + onSort = (column) => { const { sortField, isSortAscending, policySortChanged } = this.props; const newIsSortAscending = sortField === column ? !isSortAscending : true; policySortChanged(column, newIsSortAscending); @@ -286,22 +286,22 @@ export class PolicyTable extends Component { }; return flattenPanelTree(panelTree); } - togglePolicyPopover = policy => { + togglePolicyPopover = (policy) => { if (this.isPolicyPopoverOpen(policy)) { this.closePolicyPopover(policy); } else { this.openPolicyPopover(policy); } }; - isPolicyPopoverOpen = policy => { + isPolicyPopoverOpen = (policy) => { return this.state.policyPopover === policy.name; }; - closePolicyPopover = policy => { + closePolicyPopover = (policy) => { if (this.isPolicyPopoverOpen(policy)) { this.setState({ policyPopover: null }); } }; - openPolicyPopover = policy => { + openPolicyPopover = (policy) => { this.setState({ policyPopover: policy.name }); }; buildRowCells(policy) { @@ -374,7 +374,7 @@ export class PolicyTable extends Component { buildRows() { const { policies = [] } = this.props; - return policies.map(policy => { + return policies.map((policy) => { const { name } = policy; return {this.buildRowCells(policy)}; }); @@ -394,7 +394,7 @@ export class PolicyTable extends Component { ); } - onItemSelectionChanged = selectedPolicies => { + onItemSelectionChanged = (selectedPolicies) => { this.setState({ selectedPolicies }); }; @@ -455,7 +455,7 @@ export class PolicyTable extends Component { { + onChange={(event) => { policyFilterChanged(event.target.value); }} data-test-subj="policyTableFilterInput" diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/api.js b/x-pack/plugins/index_lifecycle_management/public/application/services/api.js index 1cb2089ab66db..386df63111a89 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/api.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/api.js @@ -43,28 +43,28 @@ export async function deletePolicy(policyName) { return response; } -export const retryLifecycleForIndex = async indexNames => { +export const retryLifecycleForIndex = async (indexNames) => { const response = await sendPost(`index/retry`, { indexNames }); // Only track successful actions. trackUiMetric('count', UIM_INDEX_RETRY_STEP); return response; }; -export const removeLifecycleForIndex = async indexNames => { +export const removeLifecycleForIndex = async (indexNames) => { const response = await sendPost(`index/remove`, { indexNames }); // Only track successful actions. trackUiMetric('count', UIM_POLICY_DETACH_INDEX); return response; }; -export const addLifecyclePolicyToIndex = async body => { +export const addLifecyclePolicyToIndex = async (body) => { const response = await sendPost(`index/add`, body); // Only track successful actions. trackUiMetric('count', UIM_POLICY_ATTACH_INDEX); return response; }; -export const addLifecyclePolicyToTemplate = async body => { +export const addLifecyclePolicyToTemplate = async (body) => { const response = await sendPost(`template`, body); // Only track successful actions. trackUiMetric('count', UIM_POLICY_ATTACH_INDEX_TEMPLATE); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js b/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js index 6d2e3dae57f46..dcc9036463b82 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js @@ -6,9 +6,9 @@ export const filterItems = (fields, filter = '', items = []) => { const lowerFilter = filter.toLowerCase(); - return items.filter(item => { + return items.filter((item) => { const actualFields = fields || Object.keys(item); - const indexOfMatch = actualFields.findIndex(field => { + const indexOfMatch = actualFields.findIndex((field) => { const normalizedField = String(item[field]).toLowerCase(); return normalizedField.includes(lowerFilter); }); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js b/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js index e060e22965cb3..2bb3903a6ef45 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js @@ -8,7 +8,7 @@ export const flattenPanelTree = (tree, array = []) => { array.push(tree); if (tree.items) { - tree.items.forEach(item => { + tree.items.forEach((item) => { if (item.panel) { flattenPanelTree(item.panel, array); item.panel = item.panel.id; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js b/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js index 8e9896dac0b07..1b1446bb735c1 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js @@ -6,8 +6,8 @@ import { sortBy } from 'lodash'; -const stringSort = fieldName => item => item[fieldName]; -const arraySort = fieldName => item => (item[fieldName] || []).length; +const stringSort = (fieldName) => (item) => item[fieldName]; +const arraySort = (fieldName) => (item) => (item[fieldName] || []).length; const sorters = { version: stringSort('version'), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts b/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts index ca987441c7ce9..d71e38d0b31de 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts @@ -51,7 +51,7 @@ export function getUiMetricsForPhases(phases: any): any { }; // We only care about whether the user has interacted with the priority of *any* phase at all. - return [PHASE_HOT, PHASE_WARM, PHASE_COLD].some(phase => { + return [PHASE_HOT, PHASE_WARM, PHASE_COLD].some((phase) => { // If the priority is different than the default, we'll consider it a user interaction, // even if the user has set it to undefined. return ( diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js index b665a847851b3..f2520abc7a441 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js @@ -14,7 +14,7 @@ export const setSelectedPrimaryShardCount = createAction('SET_SELECTED_PRIMARY_S export const setSelectedReplicaCount = createAction('SET_SELECTED_REPLICA_COUNT'); export const fetchedNodes = createAction('FETCHED_NODES'); let fetchingNodes = false; -export const fetchNodes = () => async dispatch => { +export const fetchNodes = () => async (dispatch) => { try { if (!fetchingNodes) { fetchingNodes = true; @@ -38,7 +38,7 @@ export const fetchedNodeDetails = createAction( details, }) ); -export const fetchNodeDetails = selectedNodeAttrs => async dispatch => { +export const fetchNodeDetails = (selectedNodeAttrs) => async (dispatch) => { let details; try { details = await loadNodeDetails(selectedNodeAttrs); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js index b6064af6e38b2..aa20c0eb1d326 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js @@ -22,7 +22,7 @@ export const policyPageChanged = createAction('POLICY_PAGE_CHANGED'); export const policySortDirectionChanged = createAction('POLICY_SORT_DIRECTION_CHANGED'); export const policyFilterChanged = createAction('POLICY_FILTER_CHANGED'); -export const fetchPolicies = (withIndices, callback) => async dispatch => { +export const fetchPolicies = (withIndices, callback) => async (dispatch) => { let policies; try { policies = await loadPolicies(withIndices); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js index d0f0973ad81f2..2d01749be3087 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js @@ -4,6 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export const getBootstrapEnabled = state => state.general.bootstrapEnabled; -export const getIndexName = state => state.general.indexName; -export const getAliasName = state => state.general.aliasName; +export const getBootstrapEnabled = (state) => state.general.bootstrapEnabled; +export const getIndexName = (state) => state.general.indexName; +export const getAliasName = (state) => state.general.aliasName; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js index 750a7feb19c3d..789de0f528b1b 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js @@ -209,7 +209,7 @@ export const policyNameAlreadyUsedErrorMessage = i18n.translate( defaultMessage: 'That policy name is already used.', } ); -export const validateLifecycle = state => { +export const validateLifecycle = (state) => { // This method of deep copy does not always work but it should be fine here const errors = JSON.parse(JSON.stringify(ERROR_STRUCTURE)); const policyName = getSelectedPolicyName(state); @@ -236,7 +236,7 @@ export const validateLifecycle = state => { ) { errors[STRUCTURE_POLICY_NAME].push(policyNameMustBeDifferentErrorMessage); } else if (getSelectedOriginalPolicyName(state) !== getSelectedPolicyName(state)) { - const policyNames = getPolicies(state).map(policy => policy.name); + const policyNames = getPolicies(state).map((policy) => policy.name); if (policyNames.includes(getSelectedPolicyName(state))) { errors[STRUCTURE_POLICY_NAME].push(policyNameAlreadyUsedErrorMessage); } @@ -254,7 +254,7 @@ export const validateLifecycle = state => { return errors; }; -export const getLifecycle = state => { +export const getLifecycle = (state) => { const policyName = getSelectedPolicyName(state); const phases = Object.entries(getPhases(state)).reduce((accum, [phaseName, phase]) => { // Hot is ALWAYS enabled diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js index a92b7154a51fd..63d849217f59e 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js @@ -6,14 +6,14 @@ import { createSelector } from 'reselect'; -export const getNodes = state => state.nodes.nodes; +export const getNodes = (state) => state.nodes.nodes; -export const getNodeOptions = createSelector([state => getNodes(state)], nodes => { +export const getNodeOptions = createSelector([(state) => getNodes(state)], (nodes) => { if (!nodes) { return null; } - const options = Object.keys(nodes).map(attrs => ({ + const options = Object.keys(nodes).map((attrs) => ({ text: `${attrs} (${nodes[attrs].length})`, value: attrs, })); @@ -26,14 +26,14 @@ export const getNodeOptions = createSelector([state => getNodes(state)], nodes = } }); -export const getSelectedPrimaryShardCount = state => state.nodes.selectedPrimaryShardCount; +export const getSelectedPrimaryShardCount = (state) => state.nodes.selectedPrimaryShardCount; -export const getSelectedReplicaCount = state => +export const getSelectedReplicaCount = (state) => state.nodes.selectedReplicaCount !== undefined ? state.nodes.selectedReplicaCount : 1; -export const getSelectedNodeAttrs = state => state.nodes.selectedNodeAttrs; +export const getSelectedNodeAttrs = (state) => state.nodes.selectedNodeAttrs; -export const getNodesFromSelectedNodeAttrs = state => { +export const getNodesFromSelectedNodeAttrs = (state) => { const nodes = getNodes(state)[getSelectedNodeAttrs(state)]; if (nodes) { return nodes.length; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js index 591a1cb3d3699..a3aef8679817d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js @@ -42,23 +42,23 @@ import { defaultEmptyHotPhase, } from '../defaults'; -export const getPolicies = state => state.policies.policies; +export const getPolicies = (state) => state.policies.policies; export const getPolicyByName = (state, name) => - getPolicies(state).find(policy => policy.name === name) || {}; -export const getIsNewPolicy = state => state.policies.selectedPolicy.isNew; -export const getSelectedPolicy = state => state.policies.selectedPolicy; -export const getIsSelectedPolicySet = state => state.policies.selectedPolicySet; -export const getSelectedOriginalPolicyName = state => state.policies.originalPolicyName; -export const getPolicyFilter = state => state.policies.filter; -export const getPolicySort = state => state.policies.sort; -export const getPolicyCurrentPage = state => state.policies.currentPage; -export const getPolicyPageSize = state => state.policies.pageSize; -export const isPolicyListLoaded = state => state.policies.isLoaded; + getPolicies(state).find((policy) => policy.name === name) || {}; +export const getIsNewPolicy = (state) => state.policies.selectedPolicy.isNew; +export const getSelectedPolicy = (state) => state.policies.selectedPolicy; +export const getIsSelectedPolicySet = (state) => state.policies.selectedPolicySet; +export const getSelectedOriginalPolicyName = (state) => state.policies.originalPolicyName; +export const getPolicyFilter = (state) => state.policies.filter; +export const getPolicySort = (state) => state.policies.sort; +export const getPolicyCurrentPage = (state) => state.policies.currentPage; +export const getPolicyPageSize = (state) => state.policies.pageSize; +export const isPolicyListLoaded = (state) => state.policies.isLoaded; const getFilteredPolicies = createSelector(getPolicies, getPolicyFilter, (policies, filter) => { return filterItems(['name'], filter, policies); }); -export const getTotalPolicies = createSelector(getFilteredPolicies, filteredPolicies => { +export const getTotalPolicies = createSelector(getFilteredPolicies, (filteredPolicies) => { return filteredPolicies.length; }); export const getPolicyPager = createSelector( @@ -80,16 +80,16 @@ export const getPageOfPolicies = createSelector( return pagedPolicies; } ); -export const getSaveAsNewPolicy = state => state.policies.selectedPolicy.saveAsNew; +export const getSaveAsNewPolicy = (state) => state.policies.selectedPolicy.saveAsNew; -export const getSelectedPolicyName = state => { +export const getSelectedPolicyName = (state) => { if (!getSaveAsNewPolicy(state)) { return getSelectedOriginalPolicyName(state); } return state.policies.selectedPolicy.name; }; -export const getPhases = state => state.policies.selectedPolicy.phases; +export const getPhases = (state) => state.policies.selectedPolicy.phases; export const getPhase = (state, phase) => getPhases(state)[phase]; @@ -100,7 +100,7 @@ export const getPhaseData = (state, phase, key) => { return getPhase(state, phase)[key]; }; -export const splitSizeAndUnits = field => { +export const splitSizeAndUnits = (field) => { let size; let units; @@ -116,8 +116,8 @@ export const splitSizeAndUnits = field => { }; }; -export const isNumber = value => typeof value === 'number'; -export const isEmptyObject = obj => { +export const isNumber = (value) => typeof value === 'number'; +export const isEmptyObject = (obj) => { return !obj || (Object.entries(obj).length === 0 && obj.constructor === Object); }; @@ -166,7 +166,7 @@ const phaseFromES = (phase, phaseName, defaultEmptyPolicy) => { if (actions.allocate) { const allocate = actions.allocate; if (allocate.require) { - Object.entries(allocate.require).forEach(entry => { + Object.entries(allocate.require).forEach((entry) => { policy[PHASE_NODE_ATTRS] = entry.join(':'); }); // checking for null or undefined here @@ -198,7 +198,7 @@ const phaseFromES = (phase, phaseName, defaultEmptyPolicy) => { return policy; }; -export const policyFromES = policy => { +export const policyFromES = (policy) => { const { name, policy: { phases }, diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js index 143895150172d..110998a7e9354 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js @@ -82,7 +82,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { ); } }; - renderAliasFormElement = selectedPolicy => { + renderAliasFormElement = (selectedPolicy) => { const { selectedAlias } = this.state; const { index } = this.props; const showAliasSelect = @@ -118,7 +118,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { ); } - const aliasOptions = aliases.map(alias => { + const aliasOptions = aliases.map((alias) => { return { text: alias, value: alias, @@ -145,7 +145,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { { + onChange={(e) => { this.setState({ selectedAlias: e.target.value }); }} /> @@ -155,7 +155,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { renderForm() { const { policies, selectedPolicyName, policyError } = this.state; const selectedPolicy = selectedPolicyName - ? policies.find(policy => policy.name === selectedPolicyName) + ? policies.find((policy) => policy.name === selectedPolicyName) : null; const options = policies.map(({ name }) => { @@ -188,7 +188,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { { + onChange={(e) => { this.setState({ policyError: null, selectedPolicyName: e.target.value }); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js index 4e0d2383c7d79..048ed44bd58b2 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js @@ -100,7 +100,7 @@ export class RemoveLifecyclePolicyConfirmModal extends Component {

    - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
  • {indexName}
  • ))}
diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js index 40ff04408002f..43f8332f4b6bd 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js @@ -17,7 +17,7 @@ import { RemoveLifecyclePolicyConfirmModal } from './components/remove_lifecycle const stepPath = 'ilm.step'; export const retryLifecycleActionExtension = ({ indices }) => { - const allHaveErrors = every(indices, index => { + const allHaveErrors = every(indices, (index) => { return index.ilm && index.ilm.failed_step; }); if (!allHaveErrors) { @@ -35,14 +35,14 @@ export const retryLifecycleActionExtension = ({ indices }) => { 'xpack.indexLifecycleMgmt.retryIndexLifecycleAction.retriedLifecycleMessage', { defaultMessage: 'Called retry lifecycle step for: {indexNames}', - values: { indexNames: indexNames.map(indexName => `"${indexName}"`).join(', ') }, + values: { indexNames: indexNames.map((indexName) => `"${indexName}"`).join(', ') }, } ), }; }; export const removeLifecyclePolicyActionExtension = ({ indices, reloadIndices }) => { - const allHaveIlm = every(indices, index => { + const allHaveIlm = every(indices, (index) => { return index.ilm && index.ilm.managed; }); if (!allHaveIlm) { @@ -50,7 +50,7 @@ export const removeLifecyclePolicyActionExtension = ({ indices, reloadIndices }) } const indexNames = indices.map(({ name }) => name); return { - renderConfirmModal: closeModal => { + renderConfirmModal: (closeModal) => { return ( } const indexName = index.name; return { - renderConfirmModal: closeModal => { + renderConfirmModal: (closeModal) => { return ( }; }; -export const ilmBannerExtension = indices => { +export const ilmBannerExtension = (indices) => { const { Query } = EuiSearchBar; if (!indices.length) { return null; } - const indicesWithLifecycleErrors = indices.filter(index => { + const indicesWithLifecycleErrors = indices.filter((index) => { return get(index, stepPath) === 'ERROR'; }); const numIndicesWithLifecycleErrors = indicesWithLifecycleErrors.length; @@ -123,12 +123,12 @@ export const ilmBannerExtension = indices => { }; }; -export const ilmSummaryExtension = index => { +export const ilmSummaryExtension = (index) => { return ; }; -export const ilmFilterExtension = indices => { - const hasIlm = any(indices, index => index.ilm && index.ilm.managed); +export const ilmFilterExtension = (indices) => { + const hasIlm = any(indices, (index) => index.ilm && index.ilm.managed); if (!hasIlm) { return []; } else { @@ -193,7 +193,7 @@ export const ilmFilterExtension = indices => { } }; -export const addAllExtensions = extensionsService => { +export const addAllExtensions = (extensionsService) => { extensionsService.addAction(retryLifecycleActionExtension); extensionsService.addAction(removeLifecyclePolicyActionExtension); extensionsService.addAction(addLifecyclePolicyActionExtension); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts index a2dc67cb77afe..865d4f488e926 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts @@ -21,7 +21,7 @@ function isReservedSystemTemplate(templateName: string, indexPatterns: string[]) return ( templateName.startsWith('kibana_index_template') || (templateName.startsWith('.') && - indexPatterns.every(pattern => { + indexPatterns.every((pattern) => { return !pattern.includes('*'); })) ); diff --git a/x-pack/plugins/index_lifecycle_management/server/services/license.ts b/x-pack/plugins/index_lifecycle_management/server/services/license.ts index 31d3654c51e3e..2d863e283d440 100644 --- a/x-pack/plugins/index_lifecycle_management/server/services/license.ts +++ b/x-pack/plugins/index_lifecycle_management/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts index a323fdf714d8d..57b925b8c6fc1 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts @@ -73,10 +73,7 @@ export const setup = async (): Promise => { const selectDetailsTab = (tab: 'summary' | 'settings' | 'mappings' | 'aliases') => { const tabs = ['summary', 'settings', 'mappings', 'aliases']; - testBed - .find('templateDetails.tab') - .at(tabs.indexOf(tab)) - .simulate('click'); + testBed.find('templateDetails.tab').at(tabs.indexOf(tab)).simulate('click'); }; const clickReloadButton = () => { @@ -101,10 +98,7 @@ export const setup = async (): Promise => { clickActionMenu(templateName); - component - .find('.euiContextMenuItem') - .at(actions.indexOf(action)) - .simulate('click'); + component.find('.euiContextMenuItem').at(actions.indexOf(action)).simulate('click'); }; const clickTemplateAt = async (index: number) => { @@ -143,9 +137,7 @@ export const setup = async (): Promise => { const indexDetailsTabs = ['settings', 'mappings', 'stats', 'edit_settings']; const { find, component } = testBed; await act(async () => { - find('detailPanelTab') - .at(indexDetailsTabs.indexOf(tab)) - .simulate('click'); + find('detailPanelTab').at(indexDetailsTabs.indexOf(tab)).simulate('click'); }); component.update(); }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts index e0cffb7f0969a..21713428c4316 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts @@ -34,10 +34,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { }; const clickEditButtonAtField = (index: number) => { - testBed - .find('editFieldButton') - .at(index) - .simulate('click'); + testBed.find('editFieldButton').at(index).simulate('click'); }; const clickEditFieldUpdateButton = () => { @@ -45,10 +42,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { }; const deleteMappingsFieldAt = (index: number) => { - testBed - .find('removeFieldButton') - .at(index) - .simulate('click'); + testBed.find('removeFieldButton').at(index).simulate('click'); testBed.find('confirmModalConfirmButton').simulate('click'); }; @@ -143,11 +137,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { const selectSummaryTab = (tab: 'summary' | 'request') => { const tabs = ['summary', 'request']; - testBed - .find('summaryTabContent') - .find('.euiTab') - .at(tabs.indexOf(tab)) - .simulate('click'); + testBed.find('summaryTabContent').find('.euiTab').at(tabs.indexOf(tab)).simulate('click'); }; const addMappingField = async (name: string, type: string) => { diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts index 4c5cfcd826844..f5af11330a6d8 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts @@ -13,7 +13,7 @@ import { API_BASE_PATH } from '../../common/constants'; const { setup } = pageHelpers.home; const removeWhiteSpaceOnArrayValues = (array: any[]) => - array.map(value => { + array.map((value) => { if (!value.trim) { return value; } @@ -216,7 +216,7 @@ describe('', () => { const { rows } = table.getMetaData('templateTable'); expect(rows.length).toEqual( - templates.filter(template => !template.name.startsWith('.')).length + templates.filter((template) => !template.name.startsWith('.')).length ); expect(exists('systemTemplatesSwitch')).toBe(true); @@ -446,7 +446,7 @@ describe('', () => { await actions.clickTemplateAt(0); expect(find('templateDetails.tab').length).toBe(4); - expect(find('templateDetails.tab').map(t => t.text())).toEqual([ + expect(find('templateDetails.tab').map((t) => t.text())).toEqual([ 'Summary', 'Settings', 'Mappings', @@ -549,9 +549,7 @@ describe('', () => { component.update(); - find('indexTableIndexNameLink') - .at(0) - .simulate('click'); + find('indexTableIndexNameLink').at(0).simulate('click'); }); test('should encode indexName when loading settings in detail panel', async () => { diff --git a/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx b/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx index ec810faf687be..05abe284fab32 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx @@ -259,7 +259,7 @@ describe('', () => { expect( find('summaryTabContent') .find('.euiTab') - .map(t => t.text()) + .map((t) => t.text()) ).toEqual(['Summary', 'Request']); }); diff --git a/x-pack/plugins/index_management/__jest__/components/index_table.test.js b/x-pack/plugins/index_management/__jest__/components/index_table.test.js index 5e3edc78da5a8..ffd3cbb83c2ce 100644 --- a/x-pack/plugins/index_management/__jest__/components/index_table.test.js +++ b/x-pack/plugins/index_management/__jest__/components/index_table.test.js @@ -75,7 +75,7 @@ const status = (rendered, row = 0) => { .text(); }; -const snapshot = rendered => { +const snapshot = (rendered) => { expect(rendered).toMatchSnapshot(); }; const openMenuAndClickButton = (rendered, rowIndex, buttonIndex) => { @@ -108,11 +108,11 @@ const testAction = (buttonIndex, done, rowIndex = 0) => { openMenuAndClickButton(rendered, rowIndex, buttonIndex); snapshot(status(rendered, rowIndex)); }; -const names = rendered => { +const names = (rendered) => { return findTestSubject(rendered, 'indexTableIndexNameLink'); }; -const namesText = rendered => { - return names(rendered).map(button => button.text()); +const namesText = (rendered) => { + return names(rendered).map((button) => button.text()); }; describe('index table', () => { @@ -203,14 +203,14 @@ describe('index table', () => { snapshot( rendered .find('.euiPagination .euiPaginationButton .euiButtonEmpty__content > span') - .map(span => span.text()) + .map((span) => span.text()) ); const switchControl = rendered.find('.euiSwitch__button'); switchControl.simulate('click'); snapshot( rendered .find('.euiPagination .euiPaginationButton .euiButtonEmpty__content > span') - .map(span => span.text()) + .map((span) => span.text()) ); }); test('should filter based on content of search input', () => { @@ -247,7 +247,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when one index is selected and closed', () => { const rendered = mountWithIntl(component); @@ -257,7 +257,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when one open and one closed index is selected', () => { const rendered = mountWithIntl(component); @@ -268,7 +268,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when more than one open index is selected', () => { const rendered = mountWithIntl(component); @@ -279,7 +279,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when more than one closed index is selected', () => { const rendered = mountWithIntl(component); @@ -290,18 +290,18 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); - test('flush button works from context menu', done => { + test('flush button works from context menu', (done) => { testAction(8, done); }); - test('clear cache button works from context menu', done => { + test('clear cache button works from context menu', (done) => { testAction(7, done); }); - test('refresh button works from context menu', done => { + test('refresh button works from context menu', (done) => { testAction(6, done); }); - test('force merge button works from context menu', done => { + test('force merge button works from context menu', (done) => { const rendered = mountWithIntl(component); const rowIndex = 0; openMenuAndClickButton(rendered, rowIndex, 5); @@ -322,8 +322,8 @@ describe('index table', () => { }); // Commenting the following 2 tests as it works in the browser (status changes to "closed" or "open") but the // snapshot say the contrary. Need to be investigated. - test('close index button works from context menu', done => { - const modifiedIndices = indices.map(index => { + test('close index button works from context menu', (done) => { + const modifiedIndices = indices.map((index) => { return { ...index, status: index.name === 'testy0' ? 'close' : index.status, @@ -337,8 +337,8 @@ describe('index table', () => { ]); testAction(4, done); }); - test('open index button works from context menu', done => { - const modifiedIndices = indices.map(index => { + test('open index button works from context menu', (done) => { + const modifiedIndices = indices.map((index) => { return { ...index, status: index.name === 'testy1' ? 'open' : index.status, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx index e708bf1b4de66..581624e312206 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx @@ -370,7 +370,7 @@ describe.skip('Mappings editor: text datatype', () => { const subSelectOptions = indexAnalyzerSelects .at(1) .find('option') - .map(wrapper => wrapper.text()); + .map((wrapper) => wrapper.text()); expect(subSelectOptions).toEqual(customAnalyzers); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx index 28fe2bfdc0711..bef2d5c79be99 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx @@ -40,7 +40,7 @@ jest.mock('@elastic/eui', () => ({ { + onChange={(e) => { props.onChange(e.target.value); }} /> @@ -108,7 +108,7 @@ const createActions = (testBed: TestBed) => { ): Promise => { const fields = find( fieldName ? (`${fieldName}.fieldsList.fieldsListItem` as TestSubjects) : 'fieldsListItem' - ).map(wrapper => wrapper); // convert to Array for our for of loop below + ).map((wrapper) => wrapper); // convert to Array for our for of loop below for (const field of fields) { const { hasChildren, testSubjectField } = await expandField(field); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx index 07f72d7cbf54a..0743211a2b7bf 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx @@ -279,7 +279,7 @@ describe.skip('Mappings editor: core', () => { * Mapped fields */ // Test that root-level mappings "properties" are rendered as root-level "DOM tree items" - const fields = find('fieldsListItem.fieldName').map(item => item.text()); + const fields = find('fieldsListItem.fieldName').map((item) => item.text()); expect(fields).toEqual(Object.keys(defaultMappings.properties).sort()); /** diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx index 99c6fc37c4219..19eec0f0a9f9d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx @@ -24,7 +24,7 @@ interface Props { const stringifyJson = (json: GenericObject) => Object.keys(json).length ? JSON.stringify(json, null, 2) : '{\n\n}'; -const formSerializer: SerializerFunc = formData => { +const formSerializer: SerializerFunc = (formData) => { const { dynamicMapping: { enabled: dynamicMappingsEnabled, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx index 9d777cdccf83d..c06340fd9ae14 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx @@ -26,7 +26,7 @@ const fieldPathComboBoxConfig = { type: FIELD_TYPES.COMBO_BOX, defaultValue: [], serializer: (options: ComboBoxOption[]): string[] => options.map(({ label }) => label), - deserializer: (values: string[]): ComboBoxOption[] => values.map(value => ({ label: value })), + deserializer: (values: string[]): ComboBoxOption[] => values.map((value) => ({ label: value })), }; export const configurationFormSchema: FormSchema = { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx index c1a2b195a3f57..05d871ccfac71 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx @@ -52,7 +52,7 @@ export const DynamicMappingSection = () => ( } > - {formData => { + {(formData) => { const { 'dynamicMapping.enabled': enabled, 'dynamicMapping.date_detection': dateDetection, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx index 4278598dfc7c1..d195f1abfc444 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx @@ -78,7 +78,7 @@ export const SourceFieldSection = () => { } )} selectedOptions={value as ComboBoxOption[]} - onChange={newValue => { + onChange={(newValue) => { setValue(newValue); }} onCreateOption={(searchValue: string) => { @@ -109,7 +109,7 @@ export const SourceFieldSection = () => { } )} selectedOptions={value as ComboBoxOption[]} - onChange={newValue => { + onChange={(newValue) => { setValue(newValue); }} onCreateOption={(searchValue: string) => { @@ -154,7 +154,7 @@ export const SourceFieldSection = () => { } > - {formData => { + {(formData) => { const { 'sourceField.enabled': enabled } = formData; if (enabled === undefined) { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx index a4e746aa4037d..56c01510376be 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx @@ -46,7 +46,7 @@ export const DocumentFieldsHeader = React.memo(({ searchValue, onSearchChange }: } )} value={searchValue} - onChange={e => { + onChange={(e) => { // Temporary fix until EUI fixes the contract // See my comment https://github.com/elastic/eui/pull/2723/files#r366725059 if (typeof e === 'string') { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx index 569af5d21cdb0..dc52a362008c6 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx @@ -50,7 +50,7 @@ const getCustomAnalyzers = (indexSettings: IndexSettings): SelectOption[] | unde // We wrap inside a try catch as the index settings are written in JSON // and who knows what the user has entered. try { - return Object.keys(settings.analysis!.analyzer).map(value => ({ value, text: value })); + return Object.keys(settings.analysis!.analyzer).map((value) => ({ value, text: value })); } catch { return undefined; } @@ -156,7 +156,7 @@ export const AnalyzerParameter = ({ return ( - {field => ( + {(field) => (
{ - const subscription = form.subscribe(updateData => { + const subscription = form.subscribe((updateData) => { const formData = updateData.data.raw; const value = formData.sub ? formData.sub : formData.main; onChange(value); @@ -102,7 +102,7 @@ export const AnalyzerParameterSelects = ({ - {field => renderSelect(field, options)} + {(field) => renderSelect(field, options)} {subOptions && ( @@ -115,7 +115,7 @@ export const AnalyzerParameterSelects = ({ label: subOptions.label, }} > - {field => renderSelect(field, subOptions.options)} + {(field) => renderSelect(field, subOptions.options)} )} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx index 975a6cd9bba4f..1882802b27487 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx @@ -79,7 +79,7 @@ export const DynamicParameter = ({ defaultToggleValue }: Props) => { formFieldPath="dynamic_toggle" defaultToggleValue={defaultToggleValue} > - {isOn => { + {(isOn) => { return isOn === false ? ( { const defaultValueArray = - defaultValue !== undefined ? defaultValue.split('||').map(value => ({ label: value })) : []; - const defaultValuesInOptions = defaultValueArray.filter(defaultFormat => + defaultValue !== undefined ? defaultValue.split('||').map((value) => ({ label: value })) : []; + const defaultValuesInOptions = defaultValueArray.filter((defaultFormat) => ALL_DATE_FORMAT_OPTIONS.includes(defaultFormat) ); @@ -57,7 +57,7 @@ export const FormatParameter = ({ defaultValue, defaultToggleValue }: Props) => defaultToggleValue={defaultToggleValue} > - {formatField => { + {(formatField) => { return ( )} options={comboBoxOptions} selectedOptions={formatField.value as ComboBoxOption[]} - onChange={value => { + onChange={(value) => { formatField.setValue(value); }} onCreateOption={(searchValue: string) => { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx index 3e91e97eef618..59ed0f3a0a2e5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx @@ -53,8 +53,6 @@ export const IndexParameter = ({ }, }} /> - ) : ( - undefined - )} + ) : undefined} ); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx index 44c19c12db88b..ae5ffaae3552b 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx @@ -70,7 +70,7 @@ export const PathParameter = ({ field, allFields }: Props) => { deserializer: getDeserializer(allFields), }} > - {pathField => { + {(pathField) => { const error = pathField.getErrorsMessages(); const isInvalid = error ? Boolean(error.length) : false; @@ -123,7 +123,7 @@ export const PathParameter = ({ field, allFields }: Props) => { singleSelection={{ asPlainText: true }} options={suggestedFields} selectedOptions={pathField.value as AliasOption[]} - onChange={value => pathField.setValue(value)} + onChange={(value) => pathField.setValue(value)} isClearable={false} fullWidth /> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx index f955c68a6c8d5..cfa8b60653d4c 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx @@ -47,8 +47,8 @@ export const SubTypeParameter = ({ // Field sub type (if any) const subTypeOptions = typeDefinition - .subTypes!.types.map(_subType => TYPE_DEFINITION[_subType]) - .map(_subType => ({ value: _subType.value, label: _subType.label })); + .subTypes!.types.map((_subType) => TYPE_DEFINITION[_subType]) + .map((_subType) => ({ value: _subType.value, label: _subType.label })); const defaultValueSubType = typeDefinition.subTypes!.types.includes(defaultValueType as SubType) ? defaultValueType // we use the default value provided @@ -64,7 +64,7 @@ export const SubTypeParameter = ({ label: typeDefinition.subTypes!.label, }} > - {subTypeField => { + {(subTypeField) => { return ( { defaultToggleValue={defaultToggleValue} > - {formData => ( + {(formData) => ( <> ( path="type" config={getFieldConfig('type')}> - {typeField => { + {(typeField) => { const error = typeField.getErrorsMessages(); const isInvalid = error ? Boolean(error.length) : false; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx index 718d00ea461c0..230e6615bc4a4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx @@ -51,7 +51,7 @@ export const CreateField = React.memo(function CreateFieldComponent({ }); useEffect(() => { - const subscription = form.subscribe(updatedFieldForm => { + const subscription = form.subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx index 64ed3a6f87117..80e3e9bec605a 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx @@ -54,9 +54,9 @@ export const DeleteFieldProvider = ({ children }: Props) => { ); } - const deleteField: DeleteFieldFunc = field => { + const deleteField: DeleteFieldFunc = (field) => { const aliases = getAllDescendantAliases(field, fields) - .map(id => byId[id].path.join(' > ')) + .map((id) => byId[id].path.join(' > ')) .sort(); const hasAliases = Boolean(aliases.length); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx index 33c4a21775d69..e8e41955a5e80 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx @@ -64,7 +64,7 @@ export const EditField = React.memo(({ form, field, allFields, exitEdit }: Props return ( - {updateField => ( + {(updateField) => ( { }); useEffect(() => { - const subscription = form.subscribe(updatedFieldForm => { + const subscription = form.subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx index 1c079c8d5cf87..c0e68b082c310 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx @@ -100,7 +100,7 @@ export const EditFieldFormRow = React.memo( defaultValue: initialVisibleState, }} > - {field => { + {(field) => { return ( - {formData => { + {(formData) => { setIsContentVisible(formData[formFieldPath]); return renderContent(); }} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx index 88e08bc7098cb..e31d12689e7e0 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx @@ -62,7 +62,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { setState({ isModalOpen: false }); }; - const updateField: UpdateFieldFunc = field => { + const updateField: UpdateFieldFunc = (field) => { const previousField = byId[field.id]; const willDeleteChildFields = (oldType: DataType, newType: DataType): boolean => { @@ -102,7 +102,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { if (requiresConfirmation) { aliasesToDelete = aliasesOnFieldAndDescendants.filter( // We will only delete aliases that points to possible children, *NOT* the field itself - id => aliasesOnField.includes(id) === false + (id) => aliasesOnField.includes(id) === false ); } } @@ -112,7 +112,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { isModalOpen: true, field, aliases: Boolean(aliasesToDelete.length) - ? aliasesToDelete.map(id => byId[id].path.join(' > ')).sort() + ? aliasesToDelete.map((id) => byId[id].path.join(' > ')).sort() : undefined, }); return; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx index 89af480d79a20..3d78205934eea 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx @@ -47,7 +47,7 @@ export const NumericType = ({ field }: Props) => { {/* scaling_factor */} - {formData => + {(formData) => formData.subType === 'scaled_float' ? ( { - {formData => + {(formData) => formData.subType === 'date_range' ? ( { - {formData => + {(formData) => formData.subType === 'date_range' ? ( ) : null diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx index 73032ad31461e..c4ed11097b609 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx @@ -182,7 +182,7 @@ export const TextType = React.memo(({ field }: Props) => { defaultToggleValue={getDefaultToggleValue('position_increment_gap', field.source)} > - {formData => { + {(formData) => { return ( <> - {deleteField => ( + {(deleteField) => (
    - {aliases.map(aliasPath => ( + {aliases.map((aliasPath) => (
  • {aliasPath}
  • diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx index 614b7cb56bef6..ab8b90b6be3b5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx @@ -68,7 +68,7 @@ export const SearchResultItem = React.memo(function FieldListItemFlatComponent({ - {deleteField => ( + {(deleteField) => ( ( - {openModal => ( + {(openModal) => ( {i18n.translate('xpack.idxMgmt.mappingsEditor.loadFromJsonButtonLabel', { defaultMessage: 'Load JSON', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx index fdd45889353d4..86bc0900f1678 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx @@ -29,7 +29,7 @@ import { LoadMappingsProvider } from './load_mappings_provider'; const ComponentToTest = ({ onJson }: { onJson: () => void }) => ( - {openModal => ( + {(openModal) => ( diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx index 6bc360a1ec70e..a50572df9004e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx @@ -134,7 +134,7 @@ export const LoadMappingsProvider = ({ onJson, children }: Props) => { state.json !== undefined && state.errors !== undefined ? 'validationResult' : 'json'; const i18nTexts = getTexts(view, state.errors?.length); - const onJsonUpdate: OnJsonEditorUpdateHandler = jsonUpdateData => { + const onJsonUpdate: OnJsonEditorUpdateHandler = (jsonUpdateData) => { jsonContent.current = jsonUpdateData; }; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx index 31ebce067b3b9..e6b7eeb12b4c8 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx @@ -22,7 +22,7 @@ interface Props { const stringifyJson = (json: { [key: string]: any }) => Array.isArray(json) ? JSON.stringify(json, null, 2) : '[\n\n]'; -const formSerializer: SerializerFunc = formData => { +const formSerializer: SerializerFunc = (formData) => { const { dynamicTemplates } = formData; let parsedTemplates; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx index 4206fe8b696da..edfb6903a8585 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx @@ -852,7 +852,7 @@ export const MAIN_DATA_TYPE_DEFINITION: { export const SUB_TYPE_MAP_TO_MAIN = Object.entries(MAIN_DATA_TYPE_DEFINITION).reduce( (acc, [type, definition]) => { if ({}.hasOwnProperty.call(definition, 'subTypes')) { - definition.subTypes!.types.forEach(subType => { + definition.subTypes!.types.forEach((subType) => { acc[subType] = type; }); } diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx index 710e637de8b08..d16bf68b80e5d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx @@ -244,7 +244,7 @@ const DATE_FORMATS = [ { label: 'year_month_day', strict: true }, ]; -const STRICT_DATE_FORMAT_OPTIONS = DATE_FORMATS.filter(format => format.strict).map( +const STRICT_DATE_FORMAT_OPTIONS = DATE_FORMATS.filter((format) => format.strict).map( ({ label }) => ({ label: `strict_${label}`, }) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx index 1b9372e4b50c4..c7529ff272e22 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx @@ -225,15 +225,15 @@ export const PARAMETERS_DEFINITION: { [key in ParameterName]: ParameterDefinitio min: { fieldConfig: { defaultValue: 0.01, - serializer: value => (value === '' ? '' : toInt(value) / 100), - deserializer: value => Math.round(value * 100), + serializer: (value) => (value === '' ? '' : toInt(value) / 100), + deserializer: (value) => Math.round(value * 100), } as FieldConfig, }, max: { fieldConfig: { defaultValue: 1, - serializer: value => (value === '' ? '' : toInt(value) / 100), - deserializer: value => Math.round(value * 100), + serializer: (value) => (value === '' ? '' : toInt(value) / 100), + deserializer: (value) => Math.round(value * 100), } as FieldConfig, }, }, @@ -582,7 +582,7 @@ export const PARAMETERS_DEFINITION: { [key in ParameterName]: ParameterDefinitio serializer: (format: ComboBoxOption[]): string | undefined => format.length ? format.map(({ label }) => label).join('||') : undefined, deserializer: (formats: string): ComboBoxOption[] | undefined => - formats.split('||').map(format => ({ label: format })), + formats.split('||').map((format) => ({ label: format })), helpText: ( (value === '' ? '' : toInt(value)), + serializer: (value) => (value === '' ? '' : toInt(value)), } as FieldConfig, }, max_chars: { fieldConfig: { type: FIELD_TYPES.NUMBER, defaultValue: 5, - serializer: value => (value === '' ? '' : toInt(value)), + serializer: (value) => (value === '' ? '' : toInt(value)), } as FieldConfig, }, }, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts index e9beee1071597..405324920419e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts @@ -10,7 +10,7 @@ import { Reporter } from 'io-ts/lib/Reporter'; export type ReporterResult = Array<{ path: string[]; message: string }>; const failure = (validation: ValidationError[]): ReporterResult => { - return validation.map(e => { + return validation.map((e) => { const path: string[] = []; let validationName = ''; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts index 817b0f4a4d3d0..1fd8329ae4b40 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts @@ -9,7 +9,7 @@ import { GenericObject } from '../types'; import { validateMappingsConfiguration, VALID_MAPPINGS_PARAMETERS } from './mappings_validator'; const isMappingDefinition = (obj: GenericObject): boolean => { - const areAllKeysValid = Object.keys(obj).every(key => VALID_MAPPINGS_PARAMETERS.includes(key)); + const areAllKeysValid = Object.keys(obj).every((key) => VALID_MAPPINGS_PARAMETERS.includes(key)); if (!areAllKeysValid) { return false; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts index d67c267dda6ae..a3feaf21e6493 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts @@ -11,7 +11,7 @@ describe('Mappings configuration validator', () => { it('should convert non object to empty object', () => { const tests = ['abc', 123, [], null, undefined]; - tests.forEach(testValue => { + tests.forEach((testValue) => { const { value, errors } = validateMappings(testValue as any); expect(isPlainObject(value)).toBe(true); expect(errors).toBe(undefined); @@ -93,7 +93,7 @@ describe('Properties validator', () => { it('should convert non object to empty object', () => { const tests = ['abc', 123, [], null, undefined]; - tests.forEach(testValue => { + tests.forEach((testValue) => { const { value, errors } = validateProperties(testValue as any); expect(isPlainObject(value)).toBe(true); expect(errors).toEqual([]); @@ -127,7 +127,7 @@ describe('Properties validator', () => { }); expect(errors).toEqual( - ['prop2', 'prop3', 'prop4', 'prop5', 'prop6.prop2'].map(fieldPath => ({ + ['prop2', 'prop3', 'prop4', 'prop5', 'prop6.prop2'].map((fieldPath) => ({ code: 'ERR_FIELD', fieldPath, })) @@ -348,9 +348,9 @@ describe('Properties validator', () => { expect(value.goodField2).toEqual(properties.goodField2); expect(value.goodField3).toEqual(properties.goodField3); - const allWrongParameters = Object.keys(properties.wrongField).filter(v => v !== 'type'); + const allWrongParameters = Object.keys(properties.wrongField).filter((v) => v !== 'type'); expect(errors).toEqual( - allWrongParameters.map(paramName => ({ + allWrongParameters.map((paramName) => ({ code: 'ERR_PARAMETER', fieldPath: 'wrongField', paramName, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts index 78d638e398593..f0d90be9472f6 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts @@ -149,7 +149,7 @@ const parseFields = ( if (Boolean(parametersRemoved.length)) { acc.errors = [ ...acc.errors, - ...parametersRemoved.map(paramName => ({ + ...parametersRemoved.map((paramName) => ({ code: 'ERR_PARAMETER' as 'ERR_PARAMETER', fieldPath, paramName, @@ -232,13 +232,13 @@ export const validateMappingsConfiguration = ( const isSchemaInvalid = isLeft(result); const unknownConfigurationParameters = Object.keys(mappingsConfiguration).filter( - key => mappingsConfigurationSchemaKeys.includes(key) === false + (key) => mappingsConfigurationSchemaKeys.includes(key) === false ); const unknownSourceConfigurationParameters = mappingsConfiguration._source !== undefined ? Object.keys(mappingsConfiguration._source).filter( - key => sourceConfigurationSchemaKeys.includes(key) === false + (key) => sourceConfigurationSchemaKeys.includes(key) === false ) : []; @@ -247,7 +247,7 @@ export const validateMappingsConfiguration = ( * To keep the logic simple we will strip out the parameters that contain errors */ const errors = errorReporter.report(result); - errors.forEach(error => { + errors.forEach((error) => { const configurationName = error.path[0]; configurationRemoved.add(configurationName); delete copyOfMappingsConfig[configurationName]; @@ -255,7 +255,7 @@ export const validateMappingsConfiguration = ( } if (unknownConfigurationParameters.length > 0) { - unknownConfigurationParameters.forEach(configName => configurationRemoved.add(configName)); + unknownConfigurationParameters.forEach((configName) => configurationRemoved.add(configName)); } if (unknownSourceConfigurationParameters.length > 0) { @@ -266,7 +266,7 @@ export const validateMappingsConfiguration = ( copyOfMappingsConfig = pick(copyOfMappingsConfig, mappingsConfigurationSchemaKeys); const errors: MappingsValidationError[] = toArray(ordString)(configurationRemoved) - .map(configName => ({ + .map((configName) => ({ code: 'ERR_CONFIG', configName, })) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx index 618d106b0e7a1..b937962a0944d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx @@ -160,7 +160,7 @@ const getSearchMetadata = (searchData: SearchData, fieldData: FieldData): Search // Execute all the regEx and sort them with the one that has the most // characters match first. const arrayMatch = searchRegexArray - .map(regex => regex.exec(fieldData.path)) + .map((regex) => regex.exec(fieldData.path)) .filter(Boolean) .sort((a, b) => b![0].length - a![0].length); @@ -239,7 +239,7 @@ export const searchFields = (term: string, fields: NormalizedFields['byId']): Se } return Object.values(fields) - .map(field => ({ + .map((field) => ({ field, metadata: getSearchMetadata(searchData, { name: field.source.name, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts index 6a1fd51a5af64..14f5858cb95d9 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts @@ -111,7 +111,7 @@ const replaceAliasPathByAliasId = ( Object.entries(byId).forEach(([id, field]) => { if (field.source.type === 'alias') { const aliasTargetField = Object.values(byId).find( - _field => _field.path.join('.') === field.source.path + (_field) => _field.path.join('.') === field.source.path ); if (aliasTargetField) { @@ -292,7 +292,7 @@ const replaceAliasIdByAliasPath = ( Object.entries(aliases).forEach(([targetId, aliasesIds]) => { const path = updatedById[targetId] ? updatedById[targetId].path.join('.') : ''; - aliasesIds.forEach(id => { + aliasesIds.forEach((id) => { const aliasField = updatedById[id]; if (!aliasField) { return; @@ -313,7 +313,7 @@ export const deNormalize = ({ rootLevelFields, byId, aliases }: NormalizedFields const serializedFieldsById = replaceAliasIdByAliasPath(aliases, byId); const deNormalizePaths = (ids: string[], to: Fields = {}) => { - ids.forEach(id => { + ids.forEach((id) => { const { source, childFields, childFieldsName } = serializedFieldsById[id]; const { name, ...normalizedField } = source; const field: Omit = normalizedField; @@ -356,8 +356,8 @@ export const updateFieldsPathAfterFieldNameChange = ( if (_field.hasChildFields || _field.hasMultiFields) { _field - .childFields!.map(fieldId => byId[fieldId]) - .forEach(childField => { + .childFields!.map((fieldId) => byId[fieldId]) + .forEach((childField) => { updateFieldPath(childField, [..._paths, name]); }); } @@ -381,8 +381,8 @@ export const getAllChildFields = ( const getChildFields = (_field: NormalizedField, to: NormalizedField[] = []) => { if (_field.hasChildFields || _field.hasMultiFields) { _field - .childFields!.map(fieldId => byId[fieldId]) - .forEach(childField => { + .childFields!.map((fieldId) => byId[fieldId]) + .forEach((childField) => { to.push(childField); getChildFields(childField, to); }); @@ -411,13 +411,13 @@ export const getAllDescendantAliases = ( } if (hasAliases) { - fields.aliases[field.id].forEach(id => { + fields.aliases[field.id].forEach((id) => { aliasesIds.push(id); }); } if (field.childFields) { - field.childFields.forEach(id => { + field.childFields.forEach((id) => { if (!fields.byId[id]) { return; } @@ -455,14 +455,14 @@ export const filterTypesForMultiField = ( options: ComboBoxOption[] ): ComboBoxOption[] => options.filter( - option => TYPE_NOT_ALLOWED_MULTIFIELD.includes(option.value as MainType) === false + (option) => TYPE_NOT_ALLOWED_MULTIFIELD.includes(option.value as MainType) === false ); export const filterTypesForNonRootFields = ( options: ComboBoxOption[] ): ComboBoxOption[] => options.filter( - option => TYPE_ONLY_ALLOWED_AT_ROOT_LEVEL.includes(option.value as MainType) === false + (option) => TYPE_ONLY_ALLOWED_AT_ROOT_LEVEL.includes(option.value as MainType) === false ); /** @@ -484,7 +484,7 @@ export const buildFieldTreeFromIds = ( byId: NormalizedFields['byId'], render: (field: NormalizedField) => JSX.Element | string ): TreeItem[] => - fieldsIds.map(id => { + fieldsIds.map((id) => { const field = byId[id]; const children = field.childFields ? buildFieldTreeFromIds(field.childFields, byId, render) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts index 279d4612f3df1..43498b2bb9e72 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts @@ -17,11 +17,11 @@ export const validateUniqueName = ( const validator: ValidationFunc = ({ value }) => { const existingNames = parentId ? Object.values(byId) - .filter(field => field.parentId === parentId) - .map(field => field.source.name) - : rootLevelFields.map(fieldId => byId[fieldId].source.name); + .filter((field) => field.parentId === parentId) + .map((field) => field.source.name) + : rootLevelFields.map((fieldId) => byId[fieldId].source.name); - if (existingNames.filter(name => name !== initialName).includes(value as string)) { + if (existingNames.filter((name) => name !== initialName).includes(value as string)) { return { message: i18n.translate('xpack.idxMgmt.mappingsEditor.existNamesValidationErrorMessage', { defaultMessage: 'There is already a field with this name.', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx index 280ea5c3dd28c..029b154761ea4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx @@ -143,7 +143,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = validate: async () => { const configurationFormValidator = state.configuration.submitForm !== undefined - ? new Promise(async resolve => { + ? new Promise(async (resolve) => { const { isValid } = await state.configuration.submitForm!(); resolve(isValid); }) @@ -151,7 +151,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = const templatesFormValidator = state.templates.submitForm !== undefined - ? new Promise(async resolve => { + ? new Promise(async (resolve) => { const { isValid } = await state.templates.submitForm!(); resolve(isValid); }) @@ -164,7 +164,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = } return Promise.all(promisesToValidate).then( - validationArray => validationArray.every(Boolean) && state.fieldsJsonEditor.isValid + (validationArray) => validationArray.every(Boolean) && state.fieldsJsonEditor.isValid ); }, isValid: state.isValid, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts index 61ba010fbc7b0..e0311fc86a3b0 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts @@ -180,7 +180,7 @@ const updateAliasesReferences = ( */ if (previousTargetPath && updatedAliases[previousTargetPath]) { updatedAliases[previousTargetPath] = updatedAliases[previousTargetPath].filter( - id => id !== field.id + (id) => id !== field.id ); } @@ -217,7 +217,7 @@ const removeFieldFromMap = (fieldId: string, fields: NormalizedFields): Normaliz if (parentField) { // If the parent exist, update its childFields Array - const childFields = parentField.childFields!.filter(childId => childId !== fieldId); + const childFields = parentField.childFields!.filter((childId) => childId !== fieldId); updatedById[parentId] = { ...parentField, @@ -233,7 +233,7 @@ const removeFieldFromMap = (fieldId: string, fields: NormalizedFields): Normaliz } else { // If there are no parentId it means that we have deleted a top level field // We need to update the root level fields Array - rootLevelFields = rootLevelFields.filter(childId => childId !== fieldId); + rootLevelFields = rootLevelFields.filter((childId) => childId !== fieldId); } let updatedFields = { @@ -410,7 +410,7 @@ export const reducer = (state: State, action: Action): State => { const allChildFields = getAllChildFields(field, state.fields.byId); // Remove all of its children - allChildFields!.forEach(childField => { + allChildFields!.forEach((childField) => { updatedFields = removeFieldFromMap(childField.id, updatedFields); }); } @@ -423,7 +423,7 @@ export const reducer = (state: State, action: Action): State => { const targetId = field.source.path as string; updatedFields.aliases = { ...updatedFields.aliases, - [targetId]: updatedFields.aliases[targetId].filter(aliasId => aliasId !== id), + [targetId]: updatedFields.aliases[targetId].filter((aliasId) => aliasId !== id), }; } @@ -491,7 +491,7 @@ export const reducer = (state: State, action: Action): State => { ...updatedFields.aliases, [previousField.source.path as string]: updatedFields.aliases[ previousField.source.path as string - ].filter(aliasId => aliasId !== fieldToEdit), + ].filter((aliasId) => aliasId !== fieldToEdit), }; } else { const nextTypeCanHaveAlias = !PARAMETERS_DEFINITION.path.targetTypesNotAllowed.includes( @@ -499,7 +499,7 @@ export const reducer = (state: State, action: Action): State => { ); if (!nextTypeCanHaveAlias && updatedFields.aliases[fieldToEdit]) { - updatedFields.aliases[fieldToEdit].forEach(aliasId => { + updatedFields.aliases[fieldToEdit].forEach((aliasId) => { updatedFields = removeFieldFromMap(aliasId, updatedFields); }); delete updatedFields.aliases[fieldToEdit]; @@ -508,7 +508,7 @@ export const reducer = (state: State, action: Action): State => { if (shouldDeleteChildFields && previousField.childFields) { const allChildFields = getAllChildFields(previousField, updatedFields.byId); - allChildFields!.forEach(childField => { + allChildFields!.forEach((childField) => { updatedFields = removeFieldFromMap(childField.id, updatedFields); }); } diff --git a/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx b/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx index b80e51d8d139f..a87412ef92950 100644 --- a/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx @@ -164,7 +164,7 @@ export const TemplateDeleteModal = ({ /> } checked={isDeleteConfirmed} - onChange={e => setIsDeleteConfirmed(e.target.checked)} + onChange={(e) => setIsDeleteConfirmed(e.target.checked)} /> )} diff --git a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx index 0cb2ae9fbcd92..7b266034bc336 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx @@ -77,7 +77,7 @@ export const StepReview: React.FunctionComponent = ({ template, updat const numIndexPatterns = indexPatterns!.length; - const hasWildCardIndexPattern = Boolean(indexPatterns!.find(pattern => pattern === '*')); + const hasWildCardIndexPattern = Boolean(indexPatterns!.find((pattern) => pattern === '*')); const SummaryTab = () => (
    diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx index f6193bc71aa91..0cdfaae70f151 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx @@ -87,7 +87,7 @@ export const TemplateForm: React.FunctionComponent = ({ const onStepValidityChange = useCallback( (isValid: boolean | undefined) => { - setValidation(prev => ({ + setValidation((prev) => ({ ...prev, [currentStep]: { isValid, diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx index f36742c43af16..7a31c74c1a9c2 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx @@ -37,7 +37,7 @@ export const TemplateSteps: React.FunctionComponent = ({ updateCurrentStep, isCurrentStepValid, }) => { - const steps = [1, 2, 3, 4, 5].map(step => { + const steps = [1, 2, 3, 4, 5].map((step) => { return { title: stepNamesMap[step], isComplete: currentStep > step, diff --git a/x-pack/plugins/index_management/public/application/lib/ace.js b/x-pack/plugins/index_management/public/application/lib/ace.js index 3b37c8fb8870e..58e0100202cf5 100644 --- a/x-pack/plugins/index_management/public/application/lib/ace.js +++ b/x-pack/plugins/index_management/public/application/lib/ace.js @@ -7,10 +7,10 @@ import brace from 'brace'; import 'brace/ext/language_tools'; -const splitTokens = line => { +const splitTokens = (line) => { return line.split(/\s+/); }; -const wordCompleter = words => { +const wordCompleter = (words) => { return { identifierRegexps: [ /[a-zA-Z_0-9\.\$\-\u00A2-\uFFFF]/, // adds support for dot character @@ -31,7 +31,7 @@ const wordCompleter = words => { const endQuote = secondFullToken === '""' ? '' : '"'; callback( null, - words.map(word => { + words.map((word) => { return { caption: ` ${word}`, value: `${startQuote}${word}${endQuote}`, diff --git a/x-pack/plugins/index_management/public/application/lib/flatten_object.js b/x-pack/plugins/index_management/public/application/lib/flatten_object.js index dd85698b9175e..a1bb52cc8ffc7 100644 --- a/x-pack/plugins/index_management/public/application/lib/flatten_object.js +++ b/x-pack/plugins/index_management/public/application/lib/flatten_object.js @@ -11,7 +11,7 @@ export const flattenObject = (nestedObj, flattenArrays) => { const flatObj = {}; const dot = '.'; (function flattenObj(obj) { - _.keys(obj).forEach(function(key) { + _.keys(obj).forEach(function (key) { stack.push(key); if (!flattenArrays && Array.isArray(obj[key])) flatObj[stack.join(dot)] = obj[key]; else if (_.isObject(obj[key])) flattenObj(obj[key]); diff --git a/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js b/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js index e060e22965cb3..2bb3903a6ef45 100644 --- a/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js +++ b/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js @@ -8,7 +8,7 @@ export const flattenPanelTree = (tree, array = []) => { array.push(tree); if (tree.items) { - tree.items.forEach(item => { + tree.items.forEach((item) => { if (item.panel) { flattenPanelTree(item.panel, array); item.panel = item.panel.id; diff --git a/x-pack/plugins/index_management/public/application/sections/home/home.tsx b/x-pack/plugins/index_management/public/application/sections/home/home.tsx index 5d8e32031ea10..8e8616d24be20 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/home.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/home.tsx @@ -92,7 +92,7 @@ export const IndexManagementHome: React.FunctionComponent - {tabs.map(tab => ( + {tabs.map((tab) => ( onSectionChange(tab.id)} isSelected={tab.id === section} diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js index 5c5b73542f7e4..c183bdb0020ca 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js @@ -23,7 +23,7 @@ import { refreshIndices, } from '../../../../store/actions'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { panelType: getDetailPanelType(state), @@ -32,27 +32,27 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - clearCacheIndex: indexName => { + clearCacheIndex: (indexName) => { dispatch(clearCacheIndices({ indexNames: [indexName] })); }, - closeIndex: indexName => { + closeIndex: (indexName) => { dispatch(closeIndices({ indexNames: [indexName] })); }, - flushIndex: indexName => { + flushIndex: (indexName) => { dispatch(flushIndices({ indexNames: [indexName] })); }, - openIndex: indexName => { + openIndex: (indexName) => { dispatch(openIndices({ indexNames: [indexName] })); }, - refreshIndex: indexName => { + refreshIndex: (indexName) => { dispatch(refreshIndices({ indexNames: [indexName] })); }, - forcemergeIndex: indexName => { + forcemergeIndex: (indexName) => { dispatch(forcemergeIndices({ indexNames: [indexName] })); }, - deleteIndex: indexName => { + deleteIndex: (indexName) => { dispatch(deleteIndices({ indexNames: [indexName] })); }, closeDetailPanel: () => dispatch(closeDetailPanel()), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js index c8d06a8dd2eec..a25b8abbc222b 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js @@ -14,7 +14,7 @@ import { getIndexStatusByIndexName, } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { error: getDetailPanelError(state), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js index 4f2d0b3de96b7..5f105a2002761 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js @@ -45,7 +45,7 @@ export class EditSettingsJson extends React.PureComponent { const newSettings = { ...filteredDefaults, ...flattenedSettings }; //store these to be used as autocomplete values later this.settingsKeys = Object.keys(newSettings); - readOnlySettings.forEach(e => delete newSettings[e]); + readOnlySettings.forEach((e) => delete newSettings[e]); //can't change codec on open index if (isOpen) { delete newSettings['index.codec']; @@ -80,7 +80,7 @@ export class EditSettingsJson extends React.PureComponent { const json = this.editor.getValue(); const settings = JSON.parse(json); //don't set if the values have not changed - Object.keys(this.originalSettings).forEach(key => { + Object.keys(this.originalSettings).forEach((key) => { if (_.isEqual(this.originalSettings[key], settings[key])) { delete settings[key]; } @@ -148,7 +148,7 @@ export class EditSettingsJson extends React.PureComponent {
    { + ref={(aceDiv) => { this.aceDiv = aceDiv; }} /> diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js index d47661479eaab..39c16ef155fd3 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js @@ -16,7 +16,7 @@ import { getIndexStatusByIndexName, } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { error: getDetailPanelError(state), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js index 58dc55a384bae..ea85837c19b2a 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js @@ -9,7 +9,7 @@ import { Summary as PresentationComponent } from './summary'; import { getIndexByIndexName, getDetailPanelIndexName } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { indexName, diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js index 9ad31d563eb86..e715173f35f5a 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js @@ -34,7 +34,7 @@ const mapStateToProps = (state, ownProps) => { const indexStatusByName = {}; const { indexNames } = ownProps; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { indexStatusByName[indexName] = getIndexStatusByIndexName(state, indexName); }); @@ -72,7 +72,7 @@ const mapDispatchToProps = (dispatch, { indexNames }) => { unfreezeIndices: () => { dispatch(unfreezeIndices({ indexNames })); }, - forcemergeIndices: maxNumSegments => { + forcemergeIndices: (maxNumSegments) => { dispatch(forcemergeIndices({ indexNames, maxNumSegments })); }, showSettings: () => { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js index a351d39b123a8..effd80c39f0d1 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js @@ -43,7 +43,7 @@ export class IndexActionsContextMenu extends Component { }); this.props.resetSelection && this.props.resetSelection(); }; - confirmAction = isActionConfirmed => { + confirmAction = (isActionConfirmed) => { this.setState({ isActionConfirmed }); }; panels({ services: { extensionsService } }) { @@ -66,11 +66,11 @@ export class IndexActionsContextMenu extends Component { unfreezeIndices, hasSystemIndex, } = this.props; - const allOpen = all(indexNames, indexName => { + const allOpen = all(indexNames, (indexName) => { return indexStatusByName[indexName] === INDEX_OPEN; }); - const allFrozen = all(indices, index => index.isFrozen); - const allUnfrozen = all(indices, index => !index.isFrozen); + const allFrozen = all(indices, (index) => index.isFrozen); + const allUnfrozen = all(indices, (index) => !index.isFrozen); const selectedIndexCount = indexNames.length; const items = []; if (!detailPanel && selectedIndexCount === 1) { @@ -210,7 +210,7 @@ export class IndexActionsContextMenu extends Component { this.setState({ renderConfirmModal: this.renderConfirmDeleteModal }); }, }); - extensionsService.actions.forEach(actionExtension => { + extensionsService.actions.forEach((actionExtension) => { const actionExtensionDefinition = actionExtension({ indices, reloadIndices, @@ -242,7 +242,7 @@ export class IndexActionsContextMenu extends Component { } } }); - items.forEach(item => { + items.forEach((item) => { item['data-test-subj'] = 'indexTableContextMenuButton'; }); const panelTree = { @@ -257,12 +257,12 @@ export class IndexActionsContextMenu extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; - closePopoverAndExecute = func => { + closePopoverAndExecute = (func) => { this.setState({ isPopoverOpen: false, renderConfirmModal: false, @@ -341,7 +341,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName}
    • ))}
    @@ -384,7 +384,7 @@ export class IndexActionsContextMenu extends Component { helpText={helpText} > { + onChange={(event) => { this.setState({ forcemergeSegments: event.target.value }); }} min={1} @@ -413,7 +413,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName}
    • ))}
    @@ -438,7 +438,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName} {isSystemIndexByName[indexName] ? ( @@ -484,7 +484,7 @@ export class IndexActionsContextMenu extends Component { /> } checked={isActionConfirmed} - onChange={e => this.confirmAction(e.target.checked)} + onChange={(e) => this.confirmAction(e.target.checked)} /> @@ -572,7 +572,7 @@ export class IndexActionsContextMenu extends Component {

        - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
      • {indexName} {isSystemIndexByName[indexName] ? ( @@ -618,7 +618,7 @@ export class IndexActionsContextMenu extends Component { /> } checked={isActionConfirmed} - onChange={e => this.confirmAction(e.target.checked)} + onChange={(e) => this.confirmAction(e.target.checked)} /> @@ -668,7 +668,7 @@ export class IndexActionsContextMenu extends Component {

          - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
        • {indexName}
        • ))}
        @@ -701,7 +701,7 @@ export class IndexActionsContextMenu extends Component { render() { return ( - {appDependencies => { + {(appDependencies) => { const { indexNames } = this.props; const selectedIndexCount = indexNames.length; const { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js index f6250a7a6e25c..44d811f490d9d 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js @@ -34,7 +34,7 @@ import { import { IndexTable as PresentationComponent } from './index_table'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { allIndices: getIndicesAsArray(state), isDetailPanelOpen: isDetailPanelOpen(state), @@ -51,27 +51,27 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - filterChanged: filter => { + filterChanged: (filter) => { dispatch(filterChanged({ filter })); }, - pageChanged: pageNumber => { + pageChanged: (pageNumber) => { dispatch(pageChanged({ pageNumber })); }, - pageSizeChanged: pageSize => { + pageSizeChanged: (pageSize) => { dispatch(pageSizeChanged({ pageSize })); }, sortChanged: (sortField, isSortAscending) => { dispatch(sortChanged({ sortField, isSortAscending })); }, - showHiddenIndicesChanged: showHiddenIndices => { + showHiddenIndicesChanged: (showHiddenIndices) => { dispatch(showHiddenIndicesChanged({ showHiddenIndices })); }, toggleChanged: (toggleName, toggleValue) => { dispatch(toggleChanged({ toggleName, toggleValue })); }, - openDetailPanel: indexName => { + openDetailPanel: (indexName) => { dispatch(openDetailPanel({ indexName })); }, closeDetailPanel: () => { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js index 799f3a6bcb535..0d005b2864863 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js @@ -72,15 +72,15 @@ export class IndexTable extends Component { static getDerivedStateFromProps(props, state) { // Deselct any indices which no longer exist, e.g. they've been deleted. const { selectedIndicesMap } = state; - const indexNames = props.indices.map(index => index.name); + const indexNames = props.indices.map((index) => index.name); const selectedIndexNames = Object.keys(selectedIndicesMap); - const missingIndexNames = selectedIndexNames.filter(selectedIndexName => { + const missingIndexNames = selectedIndexNames.filter((selectedIndexName) => { return !indexNames.includes(selectedIndexName); }); if (missingIndexNames.length) { const newMap = { ...selectedIndicesMap }; - missingIndexNames.forEach(missingIndexName => delete newMap[missingIndexName]); + missingIndexNames.forEach((missingIndexName) => delete newMap[missingIndexName]); return { selectedIndicesMap: newMap }; } @@ -127,7 +127,7 @@ export class IndexTable extends Component { componentWillUnmount() { clearInterval(this.interval); } - onSort = column => { + onSort = (column) => { const { sortField, isSortAscending, sortChanged } = this.props; const newIsSortAscending = sortField === column ? !isSortAscending : true; @@ -164,7 +164,7 @@ export class IndexTable extends Component { this.setState({ filterError: null }); } }; - getFilters = extensionsService => { + getFilters = (extensionsService) => { const { allIndices } = this.props; return extensionsService.filters.reduce((accum, filterExtension) => { const filtersToAdd = filterExtension(allIndices); @@ -186,7 +186,7 @@ export class IndexTable extends Component { }); }; - toggleItem = name => { + toggleItem = (name) => { this.setState(({ selectedIndicesMap }) => { const newMap = { ...selectedIndicesMap }; if (newMap[name]) { @@ -200,13 +200,13 @@ export class IndexTable extends Component { }); }; - isItemSelected = name => { + isItemSelected = (name) => { return !!this.state.selectedIndicesMap[name]; }; areAllItemsSelected = () => { const { indices } = this.props; - const indexOfUnselectedItem = indices.findIndex(index => !this.isItemSelected(index.name)); + const indexOfUnselectedItem = indices.findIndex((index) => !this.isItemSelected(index.name)); return indexOfUnselectedItem === -1; }; @@ -253,7 +253,7 @@ export class IndexTable extends Component { } buildRowCells(index, appServices) { - return Object.keys(HEADERS).map(fieldName => { + return Object.keys(HEADERS).map((fieldName) => { const { name } = index; const value = index[fieldName]; @@ -351,7 +351,7 @@ export class IndexTable extends Component { buildRows(appServices) { const { indices = [], detailPanelIndexName } = this.props; - return indices.map(index => { + return indices.map((index) => { const { name } = index; return ( { + onItemSelectionChanged = (selectedIndices) => { this.setState({ selectedIndices }); }; @@ -406,7 +406,7 @@ export class IndexTable extends Component { id={`checkboxToggles-${name}`} data-test-subj={`checkboxToggles-${name}`} checked={toggleNameToVisibleMap[name]} - onChange={event => toggleChanged(name, event.target.checked)} + onChange={(event) => toggleChanged(name, event.target.checked)} label={label} /> @@ -470,7 +470,7 @@ export class IndexTable extends Component { {(indicesLoading && allIndices.length === 0) || indicesError ? null : ( - {extensionsService.toggles.map(toggle => { + {extensionsService.toggles.map((toggle) => { return this.renderToggleControl(toggle); })} @@ -478,7 +478,7 @@ export class IndexTable extends Component { id="checkboxShowHiddenIndices" data-test-subj="indexTableIncludeHiddenIndicesToggle" checked={showHiddenIndices} - onChange={event => showHiddenIndicesChanged(event.target.checked)} + onChange={(event) => showHiddenIndicesChanged(event.target.checked)} label={ = ({ {managedTemplateCallout} - {TABS.map(tab => ( + {TABS.map((tab) => ( { uiMetricService.trackMetric('click', tabToUiMetricMap[tab.id]); @@ -192,7 +192,7 @@ export const TemplateDetails: React.FunctionComponent = ({ {templateToDelete && templateToDelete.length > 0 ? ( { + callback={(data) => { if (data && data.hasDeletedTemplates) { reload(); } else { @@ -247,7 +247,7 @@ export const TemplateDetails: React.FunctionComponent = ({ data-test-subj="manageTemplateButton" iconType="arrowDown" iconSide="right" - onClick={() => setIsPopOverOpen(prev => !prev)} + onClick={() => setIsPopOverOpen((prev) => !prev)} > (templates ? templates.filter(template => !template.name.startsWith('.')) : []), + () => (templates ? templates.filter((template) => !template.name.startsWith('.')) : []), [templates] ); @@ -128,7 +128,7 @@ export const TemplateList: React.FunctionComponent setShowSystemTemplates(event.target.checked)} + onChange={(event) => setShowSystemTemplates(event.target.checked)} label={ = ({ values={{ count: selection.length }} /> - ) : ( - undefined - ), + ) : undefined, toolsRight: [ = ({ {templatesToDelete && templatesToDelete.length > 0 ? ( { + callback={(data) => { if (data && data.hasDeletedTemplates) { reload(); } else { diff --git a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js index 2200b21ba39c2..4f606e0bf76a2 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js @@ -13,7 +13,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const clearCacheIndicesStart = createAction('INDEX_MANAGEMENT_CLEAR_CACHE_INDICES_START'); -export const clearCacheIndices = ({ indexNames }) => async dispatch => { +export const clearCacheIndices = ({ indexNames }) => async (dispatch) => { dispatch(clearCacheIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js index b1016fe054c95..8ba42c9af41b0 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js @@ -11,7 +11,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const closeIndicesStart = createAction('INDEX_MANAGEMENT_CLOSE_INDICES_START'); -export const closeIndices = ({ indexNames }) => async dispatch => { +export const closeIndices = ({ indexNames }) => async (dispatch) => { dispatch(closeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js index df3c134f3ca76..491054602918c 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js @@ -11,7 +11,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus } from '../actions'; export const deleteIndicesSuccess = createAction('INDEX_MANAGEMENT_DELETE_INDICES_SUCCESS'); -export const deleteIndices = ({ indexNames }) => async dispatch => { +export const deleteIndices = ({ indexNames }) => async (dispatch) => { try { await request(indexNames); } catch (error) { diff --git a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js index 0e0d36d1ec0e2..8d220a150e415 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js @@ -9,7 +9,7 @@ import { loadIndexSettings as request } from '../../services'; import { notificationService } from '../../services/notification'; import { loadIndexDataSuccess } from './load_index_data'; -export const editIndexSettings = ({ indexName }) => async dispatch => { +export const editIndexSettings = ({ indexName }) => async (dispatch) => { let indexSettings; try { indexSettings = await request(indexName); diff --git a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js index 277a71999492f..63f8f134aa76f 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js +++ b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js @@ -8,11 +8,9 @@ import { reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; import { httpService } from '../../services/http'; -export const performExtensionAction = ({ - requestMethod, - indexNames, - successMessage, -}) => async dispatch => { +export const performExtensionAction = ({ requestMethod, indexNames, successMessage }) => async ( + dispatch +) => { try { await requestMethod(indexNames, httpService.httpClient); } catch (error) { diff --git a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js index 15e92bb965923..b77144e9614ce 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const flushIndicesStart = createAction('INDEX_MANAGEMENT_FLUSH_INDICES_START'); -export const flushIndices = ({ indexNames }) => async dispatch => { +export const flushIndices = ({ indexNames }) => async (dispatch) => { dispatch(flushIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js index aa8753cbee905..757d133f38f32 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const forcemergeIndicesStart = createAction('INDEX_MANAGEMENT_FORCEMERGE_INDICES_START'); -export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async dispatch => { +export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async (dispatch) => { dispatch(forcemergeIndicesStart({ indexNames })); try { await request(indexNames, maxNumSegments); diff --git a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js index 801390206841d..52ec78aaa3460 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const freezeIndicesStart = createAction('INDEX_MANAGEMENT_FREEZE_INDICES_START'); -export const freezeIndices = ({ indexNames }) => async dispatch => { +export const freezeIndices = ({ indexNames }) => async (dispatch) => { dispatch(freezeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js index 26189962d88f1..0472db84400fc 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js +++ b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js @@ -10,7 +10,7 @@ import { notificationService } from '../../services/notification'; export const loadIndexDataSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDEX_DATA_SUCCESS'); -export const loadIndexData = ({ indexName, dataType }) => async dispatch => { +export const loadIndexData = ({ indexName, dataType }) => async (dispatch) => { let data; try { data = await request(dataType, indexName); diff --git a/x-pack/plugins/index_management/public/application/store/actions/load_indices.js b/x-pack/plugins/index_management/public/application/store/actions/load_indices.js index f53ff8adc2b85..98134396043f8 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/load_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/load_indices.js @@ -11,7 +11,7 @@ export const loadIndicesStart = createAction('INDEX_MANAGEMENT_LOAD_INDICES_STAR export const loadIndicesSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDICES_SUCCESS'); export const loadIndicesError = createAction('INDEX_MANAGEMENT_LOAD_INDICES_ERROR'); -export const loadIndices = () => async dispatch => { +export const loadIndices = () => async (dispatch) => { dispatch(loadIndicesStart()); let indices; try { diff --git a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js index 76819c100c3c9..16c39b04f71da 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const openIndicesStart = createAction('INDEX_MANAGEMENT_OPEN_INDICES_START'); -export const openIndices = ({ indexNames }) => async dispatch => { +export const openIndices = ({ indexNames }) => async (dispatch) => { dispatch(openIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js index d1c2e1be10545..0a937accab7ad 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js @@ -12,7 +12,7 @@ import { clearRowStatus, reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; export const refreshIndicesStart = createAction('INDEX_MANAGEMENT_REFRESH_INDICES_START'); -export const refreshIndices = ({ indexNames }) => async dispatch => { +export const refreshIndices = ({ indexNames }) => async (dispatch) => { dispatch(refreshIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js b/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js index b70eb33e32c73..11329ece8f59f 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js @@ -12,7 +12,7 @@ import { loadIndices } from './load_indices'; import { notificationService } from '../../services/notification'; export const reloadIndicesSuccess = createAction('INDEX_MANAGEMENT_RELOAD_INDICES_SUCCESS'); -export const reloadIndices = indexNames => async (dispatch, getState) => { +export const reloadIndices = (indexNames) => async (dispatch, getState) => { let indices; indexNames = indexNames || getIndexNamesForCurrentPage(getState()); try { diff --git a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js index f22d7a0067401..953379ca71c5d 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const unfreezeIndicesStart = createAction('INDEX_MANAGEMENT_UNFREEZE_INDICES_START'); -export const unfreezeIndices = ({ indexNames }) => async dispatch => { +export const unfreezeIndices = ({ indexNames }) => async (dispatch) => { dispatch(unfreezeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js index 3e92829611780..384edbffdbaf1 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js @@ -17,7 +17,7 @@ export const updateIndexSettingsError = createAction( 'INDEX_MANAGEMENT_UPDATE_INDEX_SETTINGS_ERROR' ); -export const updateIndexSettings = ({ indexName, settings }) => async dispatch => { +export const updateIndexSettings = ({ indexName, settings }) => async (dispatch) => { if (Object.keys(settings).length !== 0) { try { const { error, message } = await request(indexName, settings); diff --git a/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts b/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts index 6dd2efe935141..145b4b6c9a8bc 100644 --- a/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts +++ b/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts @@ -8,7 +8,7 @@ import { Middleware } from 'redux'; // @ts-ignore import { showHiddenIndicesChanged } from '../actions'; -export const syncUrlHashQueryParam: Middleware = () => next => action => { +export const syncUrlHashQueryParam: Middleware = () => (next) => (action) => { if (action.type === String(showHiddenIndicesChanged)) { const { url, query } = q.parseUrl(window.location.hash); if (action.payload.showHiddenIndices) { diff --git a/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js b/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js index c38971a633954..d28623636f5a8 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js @@ -29,7 +29,7 @@ import { deleteIndicesSuccess } from '../actions/delete_indices'; const defaultState = {}; -export const getDetailPanelReducer = uiMetricService => +export const getDetailPanelReducer = (uiMetricService) => handleActions( { [deleteIndicesSuccess](state, action) { diff --git a/x-pack/plugins/index_management/public/application/store/reducers/indices.js b/x-pack/plugins/index_management/public/application/store/reducers/indices.js index 7007c8c42bffb..4bea9ba464888 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/indices.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/indices.js @@ -20,7 +20,7 @@ const byId = handleActions( const { indexNames } = action.payload; const newState = {}; - Object.values(state).forEach(index => { + Object.values(state).forEach((index) => { if (!indexNames.includes(index.name)) { newState[index.name] = index; } @@ -31,7 +31,7 @@ const byId = handleActions( [loadIndicesSuccess](state, action) { const { indices } = action.payload; const newState = {}; - indices.forEach(index => { + indices.forEach((index) => { newState[index.name] = index; }); @@ -41,7 +41,7 @@ const byId = handleActions( const { indices } = action.payload; const newState = {}; - indices.forEach(index => { + indices.forEach((index) => { newState[index.name] = index; }); @@ -59,7 +59,7 @@ const allIds = handleActions( [deleteIndicesSuccess](state, action) { const { indexNames } = action.payload; const newState = []; - state.forEach(indexName => { + state.forEach((indexName) => { if (!indexNames.includes(indexName)) { newState.push(indexName); } @@ -68,7 +68,7 @@ const allIds = handleActions( }, [loadIndicesSuccess](state, action) { const { indices } = action.payload; - return indices.map(index => index.name); + return indices.map((index) => index.name); }, [reloadIndicesSuccess](state) { // the set of IDs should never change when refreshing indexes. diff --git a/x-pack/plugins/index_management/public/application/store/reducers/row_status.js b/x-pack/plugins/index_management/public/application/store/reducers/row_status.js index 31d3e3c6e082c..875a6c6c2edc3 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/row_status.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/row_status.js @@ -31,7 +31,7 @@ export const rowStatus = handleActions( [clearRowStatus](state, action) { const { indexNames } = action.payload; const newState = { ...state }; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { delete newState[indexName]; }); return newState; @@ -40,7 +40,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_CLOSING; }); @@ -53,7 +53,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_OPENING; }); @@ -66,7 +66,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_REFRESHING; }); @@ -79,7 +79,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_FLUSHING; }); @@ -92,7 +92,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_FORCEMERGING; }); @@ -105,7 +105,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_CLEARING_CACHE; }); diff --git a/x-pack/plugins/index_management/public/application/store/selectors/index.js b/x-pack/plugins/index_management/public/application/store/selectors/index.js index 0f481c55782b0..c1011680d4da2 100644 --- a/x-pack/plugins/index_management/public/application/store/selectors/index.js +++ b/x-pack/plugins/index_management/public/application/store/selectors/index.js @@ -13,42 +13,42 @@ import { sortTable } from '../../services'; // TODO: Refactor and export all the app selectors through the app dependencies context let extensionsService; -export const setExtensionsService = _extensionsService => { +export const setExtensionsService = (_extensionsService) => { extensionsService = _extensionsService; }; // End hack -export const getDetailPanelData = state => state.detailPanel.data; -export const getDetailPanelError = state => state.detailPanel.error; -export const getDetailPanelType = state => state.detailPanel.panelType; -export const isDetailPanelOpen = state => !!getDetailPanelType(state); -export const getDetailPanelIndexName = state => state.detailPanel.indexName; -export const getIndices = state => state.indices.byId; -export const indicesLoading = state => state.indices.loading; -export const indicesError = state => state.indices.error; -export const getIndicesAsArray = state => Object.values(state.indices.byId); +export const getDetailPanelData = (state) => state.detailPanel.data; +export const getDetailPanelError = (state) => state.detailPanel.error; +export const getDetailPanelType = (state) => state.detailPanel.panelType; +export const isDetailPanelOpen = (state) => !!getDetailPanelType(state); +export const getDetailPanelIndexName = (state) => state.detailPanel.indexName; +export const getIndices = (state) => state.indices.byId; +export const indicesLoading = (state) => state.indices.loading; +export const indicesError = (state) => state.indices.error; +export const getIndicesAsArray = (state) => Object.values(state.indices.byId); export const getIndicesByName = (state, indexNames) => { const indices = getIndices(state); - return indexNames.map(indexName => indices[indexName]); + return indexNames.map((indexName) => indices[indexName]); }; export const getIndexByIndexName = (state, name) => getIndices(state)[name]; -export const getFilteredIds = state => state.indices.filteredIds; -export const getRowStatuses = state => state.rowStatus; -export const getTableState = state => state.tableState; -export const getAllIds = state => state.indices.allIds; +export const getFilteredIds = (state) => state.indices.filteredIds; +export const getRowStatuses = (state) => state.rowStatus; +export const getTableState = (state) => state.tableState; +export const getAllIds = (state) => state.indices.allIds; export const getIndexStatusByIndexName = (state, indexName) => { const indices = getIndices(state); const { status } = indices[indexName] || {}; return status; }; -export const getIsSystemIndexByName = indexNames => { +export const getIsSystemIndexByName = (indexNames) => { return indexNames.reduce((obj, indexName) => { obj[indexName] = indexName.startsWith('.'); return obj; }, {}); }; -export const hasSystemIndex = indexNames => { - return Boolean(indexNames.find(indexName => indexName.startsWith('.'))); +export const hasSystemIndex = (indexNames) => { + return Boolean(indexNames.find((indexName) => indexName.startsWith('.'))); }; const defaultFilterFields = ['name']; @@ -67,8 +67,8 @@ const filterByToggles = (indices, toggleNameToVisibleMap) => { return indices; } // An index is visible if ANY applicable toggle is visible. - return indices.filter(index => { - return toggleNames.some(toggleName => { + return indices.filter((index) => { + return toggleNames.some((toggleName) => { if (!togglesByName[toggleName].matchIndex(index)) { return true; } @@ -84,18 +84,18 @@ const getFilteredIndices = createSelector( getAllIds, getTableState, (indices, allIds, tableState) => { - let indexArray = allIds.map(indexName => indices[indexName]); + let indexArray = allIds.map((indexName) => indices[indexName]); indexArray = filterByToggles(indexArray, tableState.toggleNameToVisibleMap); const systemFilteredIndexes = tableState.showHiddenIndices ? indexArray - : indexArray.filter(index => !(index.name + '').startsWith('.') && !index.hidden); + : indexArray.filter((index) => !(index.name + '').startsWith('.') && !index.hidden); const filter = tableState.filter || EuiSearchBar.Query.MATCH_ALL; return EuiSearchBar.Query.execute(filter, systemFilteredIndexes, { defaultFields: defaultFilterFields, }); } ); -export const getTotalItems = createSelector(getFilteredIndices, filteredIndices => { +export const getTotalItems = createSelector(getFilteredIndices, (filteredIndices) => { return Object.keys(filteredIndices).length; }); @@ -119,7 +119,7 @@ export const getPageOfIndices = createSelector( ); const { firstItemIndex, lastItemIndex } = pager; const pagedIndexes = sortedIndexes.slice(firstItemIndex, lastItemIndex + 1); - return pagedIndexes.map(index => { + return pagedIndexes.map((index) => { const status = indexStatusLabels[rowStatuses[index.name]] || // user friendly version of row status rowStatuses[index.name] || // row status @@ -133,19 +133,19 @@ export const getPageOfIndices = createSelector( } ); -export const getIndexNamesForCurrentPage = createSelector(getPageOfIndices, pageOfIndices => { - return pageOfIndices.map(index => index.name); +export const getIndexNamesForCurrentPage = createSelector(getPageOfIndices, (pageOfIndices) => { + return pageOfIndices.map((index) => index.name); }); -export const getHasNextPage = createSelector(getPager, pager => { +export const getHasNextPage = createSelector(getPager, (pager) => { return pager.hasNextPage; }); -export const getHasPreviousPage = createSelector(getPager, pager => { +export const getHasPreviousPage = createSelector(getPager, (pager) => { return pager.hasPreviousPage; }); -export const getCurrentPage = createSelector(getPager, pager => { +export const getCurrentPage = createSelector(getPager, (pager) => { return pager.currentPage; }); diff --git a/x-pack/plugins/index_management/public/application/store/store.js b/x-pack/plugins/index_management/public/application/store/store.js index 26a9ff8f997f9..d2f24d50941c6 100644 --- a/x-pack/plugins/index_management/public/application/store/store.js +++ b/x-pack/plugins/index_management/public/application/store/store.js @@ -13,7 +13,7 @@ import { syncUrlHashQueryParam } from './middlewares'; export function indexManagementStore(services) { const toggleNameToVisibleMap = {}; - services.extensionsService.toggles.forEach(toggleExtension => { + services.extensionsService.toggles.forEach((toggleExtension) => { toggleNameToVisibleMap[toggleExtension.name] = false; }); const initialState = { tableState: { ...defaultTableState, toggleNameToVisibleMap } }; diff --git a/x-pack/plugins/index_management/public/plugin.ts b/x-pack/plugins/index_management/public/plugin.ts index 5fb8ce7207729..94d9bccdc63ca 100644 --- a/x-pack/plugins/index_management/public/plugin.ts +++ b/x-pack/plugins/index_management/public/plugin.ts @@ -52,7 +52,7 @@ export class IndexMgmtUIPlugin { id: PLUGIN.id, title: i18n.translate('xpack.idxMgmt.appTitle', { defaultMessage: 'Index Management' }), order: 0, - mount: async params => { + mount: async (params) => { const { mountManagementSection } = await import('./application/mount_management_section'); const services = { httpService, diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.ts index 1f62680a41cbc..b52a63a414967 100644 --- a/x-pack/plugins/index_management/server/lib/fetch_indices.ts +++ b/x-pack/plugins/index_management/server/lib/fetch_indices.ts @@ -71,7 +71,7 @@ async function fetchIndicesCall( }); // The two responses should be equal in the number of indices returned - return catHits.map(hit => { + return catHits.map((hit) => { const index = indices[hit.index]; const aliases = Object.keys(index.aliases); diff --git a/x-pack/plugins/index_management/server/services/license.ts b/x-pack/plugins/index_management/server/services/license.ts index 31d3654c51e3e..2d863e283d440 100644 --- a/x-pack/plugins/index_management/server/services/license.ts +++ b/x-pack/plugins/index_management/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/infra/common/http_api/source_api.ts b/x-pack/plugins/infra/common/http_api/source_api.ts index 218f8cebc9869..2c7d15d317cac 100644 --- a/x-pack/plugins/infra/common/http_api/source_api.ts +++ b/x-pack/plugins/infra/common/http_api/source_api.ts @@ -17,14 +17,14 @@ export const TimestampFromString = new rt.Type( (input, context) => pipe( rt.string.validate(input, context), - chain(stringInput => { + chain((stringInput) => { const momentValue = moment(stringInput); return momentValue.isValid() ? rt.success(momentValue.valueOf()) : rt.failure(stringInput, context); }) ), - output => new Date(output).toISOString() + (output) => new Date(output).toISOString() ); /** diff --git a/x-pack/plugins/infra/common/inventory_models/index.ts b/x-pack/plugins/infra/common/inventory_models/index.ts index d9fd8fa465b7a..1ddf92516c409 100644 --- a/x-pack/plugins/infra/common/inventory_models/index.ts +++ b/x-pack/plugins/infra/common/inventory_models/index.ts @@ -18,7 +18,7 @@ export { metrics } from './metrics'; export const inventoryModels = [host, pod, container, awsEC2, awsS3, awsRDS, awsSQS]; export const findInventoryModel = (type: InventoryItemType) => { - const model = inventoryModels.find(m => m.id === type); + const model = inventoryModels.find((m) => m.id === type); if (!model) { throw new Error( i18n.translate('xpack.infra.inventoryModels.findInventoryModel.error', { diff --git a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx index 4a4accc6edfed..fcb29e3eb1c02 100644 --- a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx +++ b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx @@ -28,7 +28,7 @@ interface Props extends ToolbarProps { export const MetricsAndGroupByToolbarItems = (props: Props) => { const metricOptions = useMemo( () => - props.metricTypes.map(toMetricOpt).filter(v => v) as Array<{ text: string; value: string }>, + props.metricTypes.map(toMetricOpt).filter((v) => v) as Array<{ text: string; value: string }>, [props.metricTypes] ); diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx index 4151fd8d6cf49..f4c7332a88e1d 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx @@ -66,7 +66,7 @@ const defaultExpression = { timeUnit: 'm', } as MetricExpression; -export const Expressions: React.FC = props => { +export const Expressions: React.FC = (props) => { const { setAlertParams, alertParams, errors, alertsContext } = props; const { source, createDerivedIndexPattern } = useSourceViaHttp({ sourceId: 'default', @@ -155,7 +155,7 @@ export const Expressions: React.FC = props => { const updateTimeSize = useCallback( (ts: number | undefined) => { const criteria = - alertParams.criteria?.map(c => ({ + alertParams.criteria?.map((c) => ({ ...c, timeSize: ts, })) || []; @@ -168,7 +168,7 @@ export const Expressions: React.FC = props => { const updateTimeUnit = useCallback( (tu: string) => { const criteria = - alertParams.criteria?.map(c => ({ + alertParams.criteria?.map((c) => ({ ...c, timeUnit: tu, })) || []; @@ -183,7 +183,7 @@ export const Expressions: React.FC = props => { if (md && md.currentOptions?.metrics) { setAlertParams( 'criteria', - md.currentOptions.metrics.map(metric => ({ + md.currentOptions.metrics.map((metric) => ({ metric: metric.field, comparator: Comparator.GT, threshold: [], @@ -322,7 +322,7 @@ export const Expressions: React.FC = props => { } checked={alertParams.alertOnNoData} - onChange={e => setAlertParams('alertOnNoData', e.target.checked)} + onChange={(e) => setAlertParams('alertOnNoData', e.target.checked)} /> diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx index 99f5aa972758d..64a5792689d52 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx @@ -120,7 +120,7 @@ export const ExpressionChart: React.FC = ({ const series = { ...firstSeries, - rows: firstSeries.rows.map(row => { + rows: firstSeries.rows.map((row) => { const newRow: MetricsExplorerRow = { ...row }; thresholds.forEach((thresholdValue, index) => { newRow[getMetricId(metric, `threshold_${index}`)] = thresholdValue; @@ -161,7 +161,7 @@ export const ExpressionChart: React.FC = ({ ({ + dataValues={thresholds.map((threshold) => ({ dataValue: threshold, }))} style={{ diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx index be0f5f88a2b55..653b9e1d5c308 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx @@ -56,7 +56,7 @@ const StyledExpression = euiStyled.div` padding: 0 4px; `; -export const ExpressionRow: React.FC = props => { +export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); const { @@ -102,7 +102,7 @@ export const ExpressionRow: React.FC = props => { ); const updateThreshold = useCallback( - t => { + (t) => { if (t.join() !== expression.threshold.join()) { setAlertParams(expressionId, { ...expression, threshold: t }); } @@ -136,7 +136,7 @@ export const ExpressionRow: React.FC = props => { ({ + fields={fields.map((f) => ({ normalizedType: f.type, name: f.name, }))} diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx index 97c0bb98962d4..f4fab113cdd17 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx @@ -85,7 +85,7 @@ const defaultExpression = { timeUnit: 'm', } as InventoryMetricConditions; -export const Expressions: React.FC = props => { +export const Expressions: React.FC = (props) => { const { setAlertParams, alertParams, errors, alertsContext } = props; const { source, createDerivedIndexPattern } = useSourceViaHttp({ sourceId: 'default', @@ -155,7 +155,7 @@ export const Expressions: React.FC = props => { const updateTimeSize = useCallback( (ts: number | undefined) => { - const criteria = alertParams.criteria.map(c => ({ + const criteria = alertParams.criteria.map((c) => ({ ...c, timeSize: ts, })); @@ -167,7 +167,7 @@ export const Expressions: React.FC = props => { const updateTimeUnit = useCallback( (tu: string) => { - const criteria = alertParams.criteria.map(c => ({ + const criteria = alertParams.criteria.map((c) => ({ ...c, timeUnit: tu, })); @@ -357,7 +357,7 @@ const StyledExpression = euiStyled.div` padding: 0 4px; `; -export const ExpressionRow: React.FC = props => { +export const ExpressionRow: React.FC = (props) => { const { setAlertParams, expression, errors, expressionId, remove, canDelete } = props; const { metric, comparator = Comparator.GT, threshold = [] } = expression; @@ -376,7 +376,7 @@ export const ExpressionRow: React.FC = props => { ); const updateThreshold = useCallback( - t => { + (t) => { if (t.join() !== expression.threshold.join()) { setAlertParams(expressionId, { ...expression, threshold: t }); } @@ -422,10 +422,10 @@ export const ExpressionRow: React.FC = props => { v?.value === metric)?.text || '', + text: ofFields.find((v) => v?.value === metric)?.text || '', }} metrics={ - ofFields.filter(m => m !== undefined && m.value !== undefined) as Array<{ + ofFields.filter((m) => m !== undefined && m.value !== undefined) as Array<{ value: SnapshotMetricType; text: string; }> diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx index 2c72c658ce093..ff859a95a3d9d 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx @@ -49,7 +49,7 @@ export const MetricExpression = ({ metric, metrics, errors, onChange, popupPosit value: '', }; - const availablefieldsOptions = metrics.map(m => { + const availablefieldsOptions = metrics.map((m) => { return { label: m.text, value: m.value }; }, []); @@ -99,10 +99,10 @@ export const MetricExpression = ({ metric, metrics, errors, onChange, popupPosit options={availablefieldsOptions} noSuggestions={!availablefieldsOptions.length} selectedOptions={ - metric ? availablefieldsOptions.filter(a => a.value === metric.value) : [] + metric ? availablefieldsOptions.filter((a) => a.value === metric.value) : [] } renderOption={(o: any) => o.label} - onChange={selectedOptions => { + onChange={(selectedOptions) => { if (selectedOptions.length > 0) { onChange(selectedOptions[0].value as SnapshotMetricType); setAggFieldPopoverOpen(false); diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx index 1623fc4e24dcb..9c215b89f4634 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx @@ -75,11 +75,11 @@ export const NodeTypeExpression = ({ data-test-subj="forExpressionSelect" value={value} fullWidth - onChange={e => { + onChange={(e) => { onChange(e.target.value as InventoryItemType); setAggTypePopoverOpen(false); }} - options={Object.values(options).map(o => o)} + options={Object.values(options).map((o) => o)} />
    diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx index e8cafecd94db1..66bde380a6d9e 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx @@ -81,7 +81,7 @@ const getCompatibleComparatorsForField = (fieldInfo: IFieldType | undefined) => }; const getFieldInfo = (fields: IFieldType[], fieldName: string): IFieldType | undefined => { - return fields.find(field => { + return fields.find((field) => { return field.name === fieldName; }); }; @@ -109,7 +109,7 @@ export const Criterion: React.FC = ({ const [isComparatorPopoverOpen, setIsComparatorPopoverOpen] = useState(false); const fieldOptions = useMemo(() => { - return fields.map(field => { + return fields.map((field) => { return { value: field.name, text: field.name }; }); }, [fields]); @@ -123,7 +123,7 @@ export const Criterion: React.FC = ({ }, [fieldInfo]); const handleFieldChange = useCallback( - e => { + (e) => { const fieldName = e.target.value; const nextFieldInfo = getFieldInfo(fields, fieldName); // If the field information we're dealing with has changed, reset the comparator and value. @@ -219,7 +219,7 @@ export const Criterion: React.FC = ({ + onChange={(e) => updateCriterion(idx, { comparator: e.target.value as Comparator }) } options={compatibleComparatorOptions} @@ -232,7 +232,7 @@ export const Criterion: React.FC = ({ { + onChange={(e) => { const number = parseInt(e.target.value, 10); updateCriterion(idx, { value: number ? number : undefined }); }} @@ -241,7 +241,7 @@ export const Criterion: React.FC = ({ updateCriterion(idx, { value: e.target.value })} + onChange={(e) => updateCriterion(idx, { value: e.target.value })} /> )} diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx index f80781f5a68d7..ff6a8e7e55fd6 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx @@ -86,7 +86,7 @@ export const DocumentCount: React.FC = ({ comparator, value, updateCount, updateCount({ comparator: e.target.value as Comparator })} + onChange={(e) => updateCount({ comparator: e.target.value as Comparator })} options={getComparatorOptions()} />
    @@ -118,7 +118,7 @@ export const DocumentCount: React.FC = ({ comparator, value, updateCount, { + onChange={(e) => { const number = parseInt(e.target.value, 10); updateCount({ value: number ? number : undefined }); }} diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx index 06855cc7e765d..cc87167b10a96 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx @@ -57,7 +57,7 @@ const DEFAULT_EXPRESSION = { timeUnit: 'm', }; -export const ExpressionEditor: React.FC = props => { +export const ExpressionEditor: React.FC = (props) => { const isInternal = props.alertsContext.metadata?.isInternal; const [sourceId] = useSourceId(); @@ -78,7 +78,7 @@ export const ExpressionEditor: React.FC = props => { ); }; -export const SourceStatusWrapper: React.FC = props => { +export const SourceStatusWrapper: React.FC = (props) => { const { initialize, isLoadingSourceStatus, @@ -121,7 +121,7 @@ export const SourceStatusWrapper: React.FC = props => { ); }; -export const Editor: React.FC = props => { +export const Editor: React.FC = (props) => { const { setAlertParams, alertParams, errors } = props; const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); @@ -137,7 +137,7 @@ export const Editor: React.FC = props => { const supportedFields = useMemo(() => { if (sourceStatus?.logIndexFields) { - return sourceStatus.logIndexFields.filter(field => { + return sourceStatus.logIndexFields.filter((field) => { return (field.type === 'string' || field.type === 'number') && field.searchable; }); } else { @@ -146,7 +146,7 @@ export const Editor: React.FC = props => { }, [sourceStatus]); const updateCount = useCallback( - countParams => { + (countParams) => { const nextCountParams = { ...alertParams.count, ...countParams }; setAlertParams('count', nextCountParams); }, @@ -187,7 +187,7 @@ export const Editor: React.FC = props => { }, [alertParams, setAlertParams]); const removeCriterion = useCallback( - idx => { + (idx) => { const nextCriteria = alertParams?.criteria?.filter((criterion, index) => { return index !== idx; }); diff --git a/x-pack/plugins/infra/public/components/auto_sizer.tsx b/x-pack/plugins/infra/public/components/auto_sizer.tsx index 284b5295111c6..af67e38a341a6 100644 --- a/x-pack/plugins/infra/public/components/auto_sizer.tsx +++ b/x-pack/plugins/infra/public/components/auto_sizer.tsx @@ -55,8 +55,8 @@ export class AutoSizer extends React.PureComponent { - entries.forEach(entry => { + this.resizeObserver = new ResizeObserver((entries) => { + entries.forEach((entry) => { if (entry.target === this.element) { this.measure(entry); } diff --git a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx index 6bbd67ce932c6..96bba1b813746 100644 --- a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx +++ b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx @@ -304,11 +304,13 @@ const withUnfocused = (state: AutocompleteFieldState) => ({ isFocused: false, }); -const FixedEuiFieldSearch: React.FC & - EuiFieldSearchProps & { - inputRef?: (element: HTMLInputElement | null) => void; - onSearch: (value: string) => void; - }> = EuiFieldSearch as any; +const FixedEuiFieldSearch: React.FC< + React.InputHTMLAttributes & + EuiFieldSearchProps & { + inputRef?: (element: HTMLInputElement | null) => void; + onSearch: (value: string) => void; + } +> = EuiFieldSearch as any; const AutocompleteContainer = euiStyled.div` position: relative; @@ -323,6 +325,6 @@ const SuggestionsPanel = euiStyled(EuiPanel).attrs(() => ({ margin-top: 2px; overflow-x: hidden; overflow-y: scroll; - z-index: ${props => props.theme.eui.euiZLevel1}; + z-index: ${(props) => props.theme.eui.euiZLevel1}; max-height: 322px; `; diff --git a/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx b/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx index fb0c1127df3d1..f14494a8abc49 100644 --- a/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx +++ b/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx @@ -17,7 +17,7 @@ interface Props { suggestion: QuerySuggestion; } -export const SuggestionItem: React.FC = props => { +export const SuggestionItem: React.FC = (props) => { const { isSelected, onClick, onMouseEnter, suggestion } = props; return ( @@ -40,10 +40,10 @@ const SuggestionItemContainer = euiStyled.div<{ }>` display: flex; flex-direction: row; - font-size: ${props => props.theme.eui.euiFontSizeS}; - height: ${props => props.theme.eui.euiSizeXL}; + font-size: ${(props) => props.theme.eui.euiFontSizeS}; + height: ${(props) => props.theme.eui.euiSizeXL}; white-space: nowrap; - background-color: ${props => + background-color: ${(props) => props.isSelected ? props.theme.eui.euiColorLightestShade : 'transparent'}; `; @@ -52,24 +52,24 @@ const SuggestionItemField = euiStyled.div` cursor: pointer; display: flex; flex-direction: row; - height: ${props => props.theme.eui.euiSizeXL}; - padding: ${props => props.theme.eui.euiSizeXS}; + height: ${(props) => props.theme.eui.euiSizeXL}; + padding: ${(props) => props.theme.eui.euiSizeXS}; `; const SuggestionItemIconField = euiStyled(SuggestionItemField)<{ suggestionType: QuerySuggestionTypes; }>` - background-color: ${props => + background-color: ${(props) => transparentize(0.9, getEuiIconColor(props.theme, props.suggestionType))}; - color: ${props => getEuiIconColor(props.theme, props.suggestionType)}; + color: ${(props) => getEuiIconColor(props.theme, props.suggestionType)}; flex: 0 0 auto; justify-content: center; - width: ${props => props.theme.eui.euiSizeXL}; + width: ${(props) => props.theme.eui.euiSizeXL}; `; const SuggestionItemTextField = euiStyled(SuggestionItemField)` flex: 2 0 0; - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; `; const SuggestionItemDescriptionField = euiStyled(SuggestionItemField)` @@ -79,7 +79,7 @@ const SuggestionItemDescriptionField = euiStyled(SuggestionItemField)` display: inline; span { - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; } } `; diff --git a/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx b/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx index 8446587e8671d..912550b90b9b9 100644 --- a/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx +++ b/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx @@ -16,5 +16,5 @@ export const Toolbar = euiStyled(EuiPanel).attrs(() => ({ border-right: none; border-left: none; border-radius: 0; - padding: ${props => props.theme.eui.euiSizeS} ${props => props.theme.eui.euiSizeL}; + padding: ${(props) => props.theme.eui.euiSizeS} ${(props) => props.theme.eui.euiSizeL}; `; diff --git a/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx b/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx index 599969d9b15a8..3b22ee24cee07 100644 --- a/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx +++ b/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx @@ -10,10 +10,12 @@ import React from 'react'; import { euiStyled } from '../../../observability/public'; -export const LoadingOverlayWrapper: React.FC & { - isLoading: boolean; - loadingChildren?: React.ReactNode; -}> = ({ children, isLoading, loadingChildren, ...rest }) => { +export const LoadingOverlayWrapper: React.FC< + React.HTMLAttributes & { + isLoading: boolean; + loadingChildren?: React.ReactNode; + } +> = ({ children, isLoading, loadingChildren, ...rest }) => { return ( {children} @@ -32,7 +34,7 @@ const RelativeDiv = euiStyled.div` const OverlayDiv = euiStyled.div` align-items: center; - background-color: ${props => transparentize(0.3, props.theme.eui.euiColorEmptyShade)}; + background-color: ${(props) => transparentize(0.3, props.theme.eui.euiColorEmptyShade)}; display: flex; height: 100%; justify-content: center; @@ -40,5 +42,5 @@ const OverlayDiv = euiStyled.div` position: absolute; top: 0; width: 100%; - z-index: ${props => props.theme.eui.euiZLevel1}; + z-index: ${(props) => props.theme.eui.euiZLevel1}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx index 74e8d197ef455..4f7b5bc135a18 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx @@ -8,7 +8,7 @@ import { EuiButton, PropsOf } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; -export const RecreateJobButton: React.FunctionComponent> = props => ( +export const RecreateJobButton: React.FunctionComponent> = (props) => ( { onChangeSelectedIndices( - indices.map(index => { + indices.map((index) => { return index.name === indexName ? { ...index, isSelected } : index; }) ); @@ -39,7 +39,7 @@ export const AnalysisSetupIndicesForm: React.FunctionComponent<{ const changeDatasetFilter = useCallback( (indexName: string, datasetFilter) => { onChangeSelectedIndices( - indices.map(index => { + indices.map((index) => { return index.name === indexName ? { ...index, datasetFilter } : index; }) ); @@ -74,7 +74,7 @@ export const AnalysisSetupIndicesForm: React.FunctionComponent<{ labelType="legend" > <> - {indices.map(index => ( + {indices.map((index) => ( setStartTime(selectedDateToParam(date))} + onChange={(date) => setStartTime(selectedDateToParam(date))} placeholder={startTimeDefaultDescription} maxDate={now} /> @@ -132,20 +132,12 @@ export const AnalysisSetupTimerangeForm: React.FunctionComponent<{ disabled={disabled} showTimeSelect selected={endTimeValue} - onChange={date => setEndTime(selectedDateToParam(date))} + onChange={(date) => setEndTime(selectedDateToParam(date))} placeholder={endTimeDefaultDescription} openToDate={now} minDate={startTimeValue} - minTime={ - selectedEndTimeIsToday - ? now - : moment() - .hour(0) - .minutes(0) - } - maxTime={moment() - .hour(23) - .minutes(59)} + minTime={selectedEndTimeIsToday ? now : moment().hour(0).minutes(0)} + maxTime={moment().hour(23).minutes(59)} /> @@ -155,7 +147,7 @@ export const AnalysisSetupTimerangeForm: React.FunctionComponent<{ }; const getStartTimeValidationErrorMessages = (validationErrors: TimeRangeValidationError[]) => - validationErrors.flatMap(validationError => { + validationErrors.flatMap((validationError) => { switch (validationError.error) { case 'INVALID_TIME_RANGE': return [ @@ -169,7 +161,7 @@ const getStartTimeValidationErrorMessages = (validationErrors: TimeRangeValidati }); const getEndTimeValidationErrorMessages = (validationErrors: TimeRangeValidationError[]) => - validationErrors.flatMap(validationError => { + validationErrors.flatMap((validationError) => { switch (validationError.error) { case 'INVALID_TIME_RANGE': return [ diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx index b37c68f837876..d3ed8aeaf6155 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx @@ -42,7 +42,7 @@ export const IndexSetupDatasetFilter: React.FC<{ const selectableOptions: EuiSelectableOption[] = useMemo( () => - availableDatasets.map(datasetName => ({ + availableDatasets.map((datasetName) => ({ label: datasetName, checked: datasetFilter.type === 'includeSome' && datasetFilter.datasets.includes(datasetName) diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx index 2eb67e0c0ce76..92774dbd6838b 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx @@ -62,7 +62,7 @@ export const IndexSetupRow: React.FC<{ }; const formatValidationError = (errors: ValidationUIError[]): React.ReactNode => { - return errors.map(error => { + return errors.map((error) => { switch (error.error) { case 'INDEX_NOT_FOUND': return ( diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx index e045e78471513..49ab25297c687 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx @@ -9,7 +9,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; import { useLinkProps } from '../../../hooks/use_link_props'; -export const UserManagementLink: React.FunctionComponent = props => { +export const UserManagementLink: React.FunctionComponent = (props) => { const linkProps = useLinkProps({ app: 'kibana', hash: '/management/security/users', diff --git a/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx index febfdddfcfb0e..84074568bcfef 100644 --- a/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx @@ -32,7 +32,7 @@ export class LogCustomizationMenu extends React.Component<{}, LogCustomizationMe }; public toggleVisibility = () => { - this.setState(state => ({ + this.setState((state) => ({ isShown: !state.isShown, })); }; diff --git a/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx index a8597b7073c95..69c969ad65f4d 100644 --- a/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx @@ -99,7 +99,7 @@ const getUptimeLink = (logItem: LogEntriesItem): LinkDescriptor | undefined => { const { field, value } = fieldItem; try { const parsedValue = decodeOrThrow(rt.array(rt.string))(JSON.parse(value)); - return acc.concat(parsedValue.map(val => `${field}:${val}`)); + return acc.concat(parsedValue.map((val) => `${field}:${val}`)); } catch (e) { return acc.concat([`${field}:${value}`]); } diff --git a/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx index f51ed693e7d80..608a22a79c473 100644 --- a/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx @@ -51,8 +51,8 @@ export const LogHighlightsMenu: React.FC = ({ const debouncedOnChange = useMemo(() => debounce(onChange, 275), [onChange]); const setHighlightTerm = useCallback( - valueOrUpdater => - _setHighlightTerm(previousHighlightTerm => { + (valueOrUpdater) => + _setHighlightTerm((previousHighlightTerm) => { const newHighlightTerm = typeof valueOrUpdater === 'function' ? valueOrUpdater(previousHighlightTerm) @@ -67,7 +67,7 @@ export const LogHighlightsMenu: React.FC = ({ [debouncedOnChange] ); const changeHighlightTerm = useCallback( - e => { + (e) => { const value = e.target.value; setHighlightTerm(value); }, @@ -168,7 +168,7 @@ const ActiveHighlightsIndicator = euiStyled(EuiIcon).attrs(({ theme }) => ({ size: 'm', color: theme.eui.euiColorAccent, }))` - padding-left: ${props => props.theme.eui.paddingSizes.xs}; + padding-left: ${(props) => props.theme.eui.paddingSizes.xs}; `; const LogHighlightsMenuContent = euiStyled.div` diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx index 2bdb1f91a6dde..0528d59f0b3d5 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx @@ -31,20 +31,16 @@ export const DensityChart: React.FC = ({ return null; } - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); - const xMax = max(buckets.map(bucket => bucket.entriesCount)) || 0; - const xScale = scaleLinear() - .domain([0, xMax]) - .range([0, width]); + const xMax = max(buckets.map((bucket) => bucket.entriesCount)) || 0; + const xScale = scaleLinear().domain([0, xMax]).range([0, width]); const path = area() .x0(xScale(0)) - .x1(bucket => xScale(bucket.entriesCount)) - .y0(bucket => yScale(bucket.start)) - .y1(bucket => yScale(bucket.end)) + .x1((bucket) => xScale(bucket.entriesCount)) + .y0((bucket) => yScale(bucket.start)) + .y1((bucket) => yScale(bucket.end)) .curve(curveMonotoneY); const firstBucket = buckets[0]; @@ -69,14 +65,14 @@ export const DensityChart: React.FC = ({ }; const DensityChartPositiveBackground = euiStyled.rect` - fill: ${props => + fill: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorLightShade : props.theme.eui.euiColorLightestShade}; `; const PositiveAreaPath = euiStyled.path` - fill: ${props => + fill: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorMediumShade : props.theme.eui.euiColorLightShade}; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx index 975e83e0075ff..2869f8d0087c2 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx @@ -53,13 +53,13 @@ export const HighlightedInterval: React.FC = ({ HighlightedInterval.displayName = 'HighlightedInterval'; const HighlightTargetMarker = euiStyled.line` - stroke: ${props => props.theme.eui.euiColorPrimary}; + stroke: ${(props) => props.theme.eui.euiColorPrimary}; stroke-width: 1; `; const HighlightPolygon = euiStyled.polygon` - fill: ${props => props.theme.eui.euiColorPrimary}; + fill: ${(props) => props.theme.eui.euiColorPrimary}; fill-opacity: 0.3; - stroke: ${props => props.theme.eui.euiColorPrimary}; + stroke: ${(props) => props.theme.eui.euiColorPrimary}; stroke-width: 1; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx index c67674d198a3f..496d4ebf924a3 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx @@ -59,7 +59,7 @@ export class LogMinimap extends React.Component = event => { + public handleClick: React.MouseEventHandler = (event) => { const minimapTop = event.currentTarget.getBoundingClientRect().top; const clickedYPosition = event.clientY - minimapTop; @@ -80,7 +80,7 @@ export class LogMinimap extends React.Component = event => { + private updateTimeCursor: React.MouseEventHandler = (event) => { const svgPosition = event.currentTarget.getBoundingClientRect(); const timeCursorY = event.clientY - svgPosition.top; @@ -157,14 +157,14 @@ export class LogMinimap extends React.Component props.theme.eui.euiColorMediumShade}; + stroke: ${(props) => props.theme.eui.euiColorMediumShade}; stroke-width: 1px; `; const TimeCursor = euiStyled.line` pointer-events: none; stroke-width: 1px; - stroke: ${props => + stroke: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorDarkestShade : props.theme.eui.euiColorDarkShade}; @@ -172,7 +172,7 @@ const TimeCursor = euiStyled.line` const MinimapWrapper = euiStyled.svg` cursor: pointer; - fill: ${props => props.theme.eui.euiColorEmptyShade}; + fill: ${(props) => props.theme.eui.euiColorEmptyShade}; & ${TimeCursor} { visibility: hidden; } diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx index 18d4a3bbfc8b3..6271627589394 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx @@ -27,13 +27,13 @@ export class SearchMarker extends React.PureComponent = evt => { + public handleClick: React.MouseEventHandler = (evt) => { evt.stopPropagation(); this.props.jumpToTarget(this.props.bucket.representativeKey); }; - public handleMouseEnter: React.MouseEventHandler = evt => { + public handleMouseEnter: React.MouseEventHandler = (evt) => { this.setState({ hoveredPosition: evt.currentTarget.getBoundingClientRect(), }); @@ -102,13 +102,13 @@ const fadeInAnimation = keyframes` `; const SearchMarkerGroup = euiStyled.g` - animation: ${fadeInAnimation} ${props => props.theme.eui.euiAnimSpeedExtraSlow} ease-in both; + animation: ${fadeInAnimation} ${(props) => props.theme.eui.euiAnimSpeedExtraSlow} ease-in both; `; const SearchMarkerBackgroundRect = euiStyled.rect` - fill: ${props => props.theme.eui.euiColorAccent}; + fill: ${(props) => props.theme.eui.euiColorAccent}; opacity: 0; - transition: opacity ${props => props.theme.eui.euiAnimSpeedNormal} ease-in; + transition: opacity ${(props) => props.theme.eui.euiAnimSpeedNormal} ease-in; cursor: pointer; ${SearchMarkerGroup}:hover & { @@ -117,5 +117,5 @@ const SearchMarkerBackgroundRect = euiStyled.rect` `; const SearchMarkerForegroundRect = euiStyled.rect` - fill: ${props => props.theme.eui.euiColorAccent}; + fill: ${(props) => props.theme.eui.euiColorAccent}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx index 1e254d999036e..41323ff14dd32 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx @@ -31,13 +31,11 @@ export class SearchMarkers extends React.PureComponent { return null; } - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); return ( - {buckets.map(bucket => ( + {buckets.map((bucket) => ( = ({ end, height, start, tickCount, width }) => { - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); const ticks = yScale.ticks(tickCount); const formatTick = yScale.tickFormat(tickCount, getTimeLabelFormat(start, end)); @@ -48,14 +46,14 @@ TimeRuler.displayName = 'TimeRuler'; const TimeRulerTickLabel = euiStyled.text` font-size: 9px; - line-height: ${props => props.theme.eui.euiLineHeight}; - fill: ${props => props.theme.eui.textColors.subdued}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; + fill: ${(props) => props.theme.eui.textColors.subdued}; user-select: none; pointer-events: none; `; const TimeRulerGridLine = euiStyled.line` - stroke: ${props => + stroke: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorDarkestShade : props.theme.eui.euiColorDarkShade}; diff --git a/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx b/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx index a5277260d56e0..248dce8f6bf8c 100644 --- a/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx @@ -32,7 +32,7 @@ export const LogSearchInput = class extends React.PureComponent< query: '', }; - public handleSubmit: React.FormEventHandler = evt => { + public handleSubmit: React.FormEventHandler = (evt) => { evt.preventDefault(); const { query } = this.state; @@ -44,7 +44,7 @@ export const LogSearchInput = class extends React.PureComponent< } }; - public handleChangeQuery: React.ChangeEventHandler = evt => { + public handleChangeQuery: React.ChangeEventHandler = (evt) => { this.setState({ query: evt.target.value, }); @@ -81,6 +81,6 @@ const PlainSearchField = euiStyled(EuiFieldSearch)` box-shadow: none; &:focus { - box-shadow: inset 0 -2px 0 0 ${props => props.theme.eui.euiColorPrimary}; + box-shadow: inset 0 -2px 0 0 ${(props) => props.theme.eui.euiColorPrimary}; } `; diff --git a/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx b/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx index 8a0f1290c2af3..64dda6ce74d89 100644 --- a/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx @@ -13,11 +13,11 @@ export const LogStatusbar = euiStyled(EuiFlexGroup).attrs(() => ({ gutterSize: 'none', justifyContent: 'flexEnd', }))` - padding: ${props => props.theme.eui.euiSizeS}; - border-top: ${props => props.theme.eui.euiBorderThin}; + padding: ${(props) => props.theme.eui.euiSizeS}; + border-top: ${(props) => props.theme.eui.euiBorderThin}; max-height: 48px; min-height: 48px; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; flex-direction: row; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx index c713839a1bba8..71e1aacb734c1 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx @@ -31,7 +31,7 @@ export const LogColumnHeaders: React.FunctionComponent<{ const { firstVisiblePosition } = useContext(LogPositionState.Context); return ( - {columnConfigurations.map(columnConfiguration => { + {columnConfigurations.map((columnConfiguration) => { if (isTimestampLogColumnConfiguration(columnConfiguration)) { return ( ({ justify-content: flex-start; overflow: hidden; padding-right: ${ASSUMED_SCROLLBAR_WIDTH}px; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - box-shadow: 0 2px 2px -1px ${props => transparentize(0.3, props.theme.eui.euiColorLightShade)}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + box-shadow: 0 2px 2px -1px ${(props) => transparentize(0.3, props.theme.eui.euiColorLightShade)}; position: relative; z-index: 1; `; @@ -104,10 +104,10 @@ const LogColumnHeaderWrapper = euiStyled(LogEntryColumn).attrs(() => ({ `; const LogColumnHeaderContent = euiStyled(LogEntryColumnContent)` - color: ${props => props.theme.eui.euiTitleColor}; - font-size: ${props => props.theme.eui.euiFontSizeS}; - font-weight: ${props => props.theme.eui.euiFontWeightSemiBold}; - line-height: ${props => props.theme.eui.euiLineHeight}; + color: ${(props) => props.theme.eui.euiTitleColor}; + font-size: ${(props) => props.theme.eui.euiFontSizeS}; + font-weight: ${(props) => props.theme.eui.euiFontWeightSemiBold}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; text-overflow: clip; white-space: pre; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx index a6cb8def4f6c4..2af99e30ce44f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx @@ -10,27 +10,27 @@ import { euiStyled } from '../../../../../observability/public'; import { chooseLightOrDarkColor, tintOrShade } from '../../../utils/styles'; export const ActiveHighlightMarker = euiStyled.mark` - color: ${props => + color: ${(props) => chooseLightOrDarkColor( props.theme.eui.euiColorAccent, props.theme.eui.euiColorEmptyShade, props.theme.eui.euiColorDarkestShade )}; - background-color: ${props => props.theme.eui.euiColorAccent}; - outline: 1px solid ${props => props.theme.eui.euiColorAccent}; + background-color: ${(props) => props.theme.eui.euiColorAccent}; + outline: 1px solid ${(props) => props.theme.eui.euiColorAccent}; }; `; export const HighlightMarker = euiStyled.mark` - color: ${props => + color: ${(props) => chooseLightOrDarkColor( tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5), props.theme.eui.euiColorEmptyShade, props.theme.eui.euiColorDarkestShade )}; - background-color: ${props => + background-color: ${(props) => tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5)}; - outline: 1px solid ${props => + outline: 1px solid ${(props) => tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5)}; }; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx index 50595cfe971d8..78caa8054860f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx @@ -44,11 +44,11 @@ export class LogTextStreamJumpToTail extends React.PureComponent` align-items: center; display: flex; - min-height: ${props => props.theme.eui.euiSizeXXL}; - width: ${props => props.width}px; + min-height: ${(props) => props.theme.eui.euiSizeXXL}; + width: ${(props) => props.width}px; position: fixed; bottom: 0; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; `; const MessageWrapper = euiStyled.div` diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx index 5598528c0e0f5..eb187a7af03f6 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx @@ -97,10 +97,10 @@ const LoadingItemViewExtra = euiStyled(EuiFlexGroup)` `; const ProgressEntryWrapper = euiStyled.div<{ position: Position }>` - padding-left: ${props => props.theme.eui.euiSizeS}; - padding-top: ${props => + padding-left: ${(props) => props.theme.eui.euiSizeS}; + padding-top: ${(props) => props.position === 'start' ? props.theme.eui.euiSizeL : props.theme.eui.euiSizeM}; - padding-bottom: ${props => + padding-bottom: ${(props) => props.position === 'end' ? props.theme.eui.euiSizeL : props.theme.eui.euiSizeM}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx index 976e4165eb6d5..1ac2e00abca70 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx @@ -113,7 +113,7 @@ const ActionsColumnContent = euiStyled(LogEntryColumnContent)` `; const ButtonWrapper = euiStyled.div` - background: ${props => props.theme.eui.euiColorPrimary}; + background: ${(props) => props.theme.eui.euiColorPrimary}; border-radius: 50%; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx index b0518b96e758c..51488f088e75a 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx @@ -32,10 +32,10 @@ export const LogEntryColumn = euiStyled.div.attrs(() => ({ }))` align-items: stretch; display: flex; - flex-basis: ${props => props.baseWidth || '0%'}; + flex-basis: ${(props) => props.baseWidth || '0%'}; flex-direction: row; - flex-grow: ${props => props.growWeight || 0}; - flex-shrink: ${props => props.shrinkWeight || 0}; + flex-grow: ${(props) => props.growWeight || 0}; + flex-shrink: ${(props) => props.shrinkWeight || 0}; overflow: hidden; `; @@ -69,10 +69,10 @@ export const getColumnWidths = ( [column.timestampColumn.id]: { growWeight: 0, shrinkWeight: 0, - baseWidth: `${Math.ceil( - characterWidth * formattedDateWidth * DATE_COLUMN_SLACK_FACTOR - ) + - 2 * COLUMN_PADDING}px`, + baseWidth: `${ + Math.ceil(characterWidth * formattedDateWidth * DATE_COLUMN_SLACK_FACTOR) + + 2 * COLUMN_PADDING + }px`, }, }; } else if (isMessageLogColumnConfiguration(column)) { @@ -90,8 +90,9 @@ export const getColumnWidths = ( [column.fieldColumn.id]: { growWeight: 1, shrinkWeight: 0, - baseWidth: `${Math.ceil(characterWidth * FIELD_COLUMN_MIN_WIDTH_CHARACTERS) + - 2 * COLUMN_PADDING}px`, + baseWidth: `${ + Math.ceil(characterWidth * FIELD_COLUMN_MIN_WIDTH_CHARACTERS) + 2 * COLUMN_PADDING + }px`, }, }; } diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx index c73c9674f9683..4e9611f7a8d2f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx @@ -78,7 +78,7 @@ interface LogEntryColumnContentProps { const FieldColumnContent = euiStyled(LogEntryColumnContent)` text-overflow: ellipsis; - ${props => + ${(props) => props.wrapMode === 'long' ? longWrappedContentStyle : props.wrapMode === 'pre-wrapped' diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx index 0fe0cbdfac593..f83a0a222d3dc 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx @@ -52,7 +52,7 @@ interface MessageColumnContentProps { const MessageColumnContent = euiStyled(LogEntryColumnContent)` text-overflow: ellipsis; - ${props => + ${(props) => props.wrapMode === 'long' ? longWrappedContentStyle : props.wrapMode === 'pre-wrapped' @@ -68,7 +68,7 @@ const formatMessageSegments = ( messageSegments.map((messageSegment, index) => formatMessageSegment( messageSegment, - highlights.map(highlight => { + highlights.map((highlight) => { if (isHighlightMessageColumn(highlight)) { const segment = highlight.message[index]; if (isHighlightFieldSegment(segment)) { diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx index 5c20df000ae51..0d971151dd95c 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx @@ -120,7 +120,7 @@ export const LogEntryRow = memo( isHighlighted={isHighlighted} scale={scale} > - {columnConfigurations.map(columnConfiguration => { + {columnConfigurations.map((columnConfiguration) => { if (isTimestampLogColumnConfiguration(columnConfiguration)) { const column = logEntryColumnsById[columnConfiguration.timestampColumn.id]; const columnWidth = columnWidths[columnConfiguration.timestampColumn.id]; @@ -209,15 +209,15 @@ export const LogEntryRowWrapper = euiStyled.div.attrs(() => ({ role: 'row', }))` align-items: stretch; - color: ${props => props.theme.eui.euiTextColor}; + color: ${(props) => props.theme.eui.euiTextColor}; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; overflow: hidden; - ${props => monospaceTextStyle(props.scale)}; - ${props => (props.isHighlighted ? highlightedContentStyle : '')} + ${(props) => monospaceTextStyle(props.scale)}; + ${(props) => (props.isHighlighted ? highlightedContentStyle : '')} &:hover { ${hoveredContentStyle} diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx index cf9c75a361b55..5f07a6a1f78d6 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx @@ -24,7 +24,7 @@ export const LogEntryTimestampColumn = memo( ); const TimestampColumnContent = euiStyled(LogEntryColumnContent)` - color: ${props => props.theme.eui.euiColorDarkShade}; + color: ${(props) => props.theme.eui.euiColorDarkShade}; overflow: hidden; text-overflow: clip; white-space: pre; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx index f89aaf12db1bc..74d1878fc89c2 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx @@ -201,7 +201,7 @@ export class ScrollableLogTextStreamView extends React.PureComponent< isLocked={isScrollLocked} entriesCount={items.length} > - {registerChild => + {(registerChild) => items.length > 0 ? ( <> + onExtendRange={(newDateExpression) => updateDateRange({ startDateExpression: newDateExpression }) } /> @@ -232,7 +232,7 @@ export class ScrollableLogTextStreamView extends React.PureComponent< register={registerChild} registrationKey={getStreamItemId(item)} > - {itemMeasureRef => ( + {(itemMeasureRef) => ( + onExtendRange={(newDateExpression) => updateDateRange({ endDateExpression: newDateExpression }) } onStreamStart={() => startLiveStreaming()} diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx index 0eb6140c0de84..7fc97f949f068 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx @@ -12,8 +12,8 @@ import { TextScale } from '../../../../common/log_text_scale'; export type WrapMode = 'none' | 'pre-wrapped' | 'long'; export const monospaceTextStyle = (scale: TextScale) => css` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; - font-size: ${props => { + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; + font-size: ${(props) => { switch (scale) { case 'large': return props.theme.eui.euiFontSizeM; @@ -25,15 +25,15 @@ export const monospaceTextStyle = (scale: TextScale) => css` return props.theme.eui.euiFontSize; } }}; - line-height: ${props => props.theme.eui.euiLineHeight}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; `; export const hoveredContentStyle = css` - background-color: ${props => props.theme.eui.euiFocusBackgroundColor}; + background-color: ${(props) => props.theme.eui.euiFocusBackgroundColor}; `; export const highlightedContentStyle = css` - background-color: ${props => props.theme.eui.euiColorHighlight}; + background-color: ${(props) => props.theme.eui.euiColorHighlight}; `; export const longWrappedContentStyle = css` @@ -104,5 +104,5 @@ const MonospaceCharacterDimensionsProbe = euiStyled.div.attrs(() => ({ padding: 0; margin: 0; - ${props => monospaceTextStyle(props.scale)}; + ${(props) => monospaceTextStyle(props.scale)}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx index 199f24f5d3f53..9b8fecc7fb111 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx @@ -262,7 +262,7 @@ const ScrollPanelWrapper = euiStyled.div` overflow-x: hidden; overflow-y: scroll; position: relative; - padding-right: ${props => props.scrollbarOffset || 0}px; + padding-right: ${(props) => props.scrollbarOffset || 0}px; & * { overflow-anchor: none; diff --git a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx index b229fb4a6b494..eae39c9d1b253 100644 --- a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx +++ b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx @@ -22,9 +22,9 @@ export const AppNavigation = ({ 'aria-label': label, children }: AppNavigationPr ); const Nav = euiStyled.nav` - background: ${props => props.theme.eui.euiColorEmptyShade}; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding: ${props => + background: ${(props) => props.theme.eui.euiColorEmptyShade}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding: ${(props) => `${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL} ${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL}`}; .euiTabs { padding-left: 3px; diff --git a/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx b/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx index d9ea44e2f1f6a..29db3c893a460 100644 --- a/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx +++ b/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx @@ -27,7 +27,7 @@ const noop = () => {}; export const RoutedTabs = ({ tabs }: RoutedTabsProps) => { return ( - {tabs.map(tab => { + {tabs.map((tab) => { return ; })} diff --git a/x-pack/plugins/infra/public/components/page.tsx b/x-pack/plugins/infra/public/components/page.tsx index b51afdd8ca803..67e82310f0807 100644 --- a/x-pack/plugins/infra/public/components/page.tsx +++ b/x-pack/plugins/infra/public/components/page.tsx @@ -19,7 +19,7 @@ export const PageContent = euiStyled.div` flex: 1 0 0%; display: flex; flex-direction: row; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; `; export const FlexPage = euiStyled(EuiPage)` diff --git a/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx b/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx index 9b8907a1ff9e1..de5241c65ef45 100644 --- a/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx +++ b/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx @@ -31,8 +31,8 @@ interface Props { export const SavedViewCreateModal = ({ close, save, isInvalid }: Props) => { const [viewName, setViewName] = useState(''); const [includeTime, setIncludeTime] = useState(false); - const onCheckChange = useCallback(e => setIncludeTime(e.target.checked), []); - const textChange = useCallback(e => setViewName(e.target.value), []); + const onCheckChange = useCallback((e) => setIncludeTime(e.target.checked), []); + const textChange = useCallback((e) => setViewName(e.target.value), []); const saveView = useCallback(() => { save(viewName, includeTime); diff --git a/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx b/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx index 3c96d505dce4d..9f55126a1440a 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx @@ -58,7 +58,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ }, }, }, - ...availableFields.map(field => ({ + ...availableFields.map((field) => ({ optionProps: { 'data-test-subj': `addFieldLogColumn addFieldLogColumn:${field}`, // this key works around EuiSelectable using a lowercased label as @@ -79,7 +79,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ ); const availableOptions = useMemo( - () => availableColumnOptions.map(availableColumnOption => availableColumnOption.optionProps), + () => availableColumnOptions.map((availableColumnOption) => availableColumnOption.optionProps), [availableColumnOptions] ); @@ -88,7 +88,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ closePopover(); const selectedOptionIndex = selectedOptions.findIndex( - selectedOption => selectedOption.checked === 'on' + (selectedOption) => selectedOption.checked === 'on' ); const selectedOption = availableColumnOptions[selectedOptionIndex]; diff --git a/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts b/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts index eab1651f498e5..bb4da5cab203a 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts +++ b/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts @@ -45,7 +45,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.name), name: 'name', - onChange: name => setFormStateChanges(changes => ({ ...changes, name })), + onChange: (name) => setFormStateChanges((changes) => ({ ...changes, name })), value: formState.name, }), [formState.name] @@ -55,7 +55,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.logAlias), name: 'logAlias', - onChange: logAlias => setFormStateChanges(changes => ({ ...changes, logAlias })), + onChange: (logAlias) => setFormStateChanges((changes) => ({ ...changes, logAlias })), value: formState.logAlias, }), [formState.logAlias] @@ -65,7 +65,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.metricAlias), name: 'metricAlias', - onChange: metricAlias => setFormStateChanges(changes => ({ ...changes, metricAlias })), + onChange: (metricAlias) => setFormStateChanges((changes) => ({ ...changes, metricAlias })), value: formState.metricAlias, }), [formState.metricAlias] @@ -75,8 +75,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.containerField), name: `containerField`, - onChange: containerField => - setFormStateChanges(changes => ({ ...changes, containerField })), + onChange: (containerField) => + setFormStateChanges((changes) => ({ ...changes, containerField })), value: formState.containerField, }), [formState.containerField] @@ -86,7 +86,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.hostField), name: `hostField`, - onChange: hostField => setFormStateChanges(changes => ({ ...changes, hostField })), + onChange: (hostField) => setFormStateChanges((changes) => ({ ...changes, hostField })), value: formState.hostField, }), [formState.hostField] @@ -96,7 +96,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.podField), name: `podField`, - onChange: podField => setFormStateChanges(changes => ({ ...changes, podField })), + onChange: (podField) => setFormStateChanges((changes) => ({ ...changes, podField })), value: formState.podField, }), [formState.podField] @@ -106,8 +106,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.tiebreakerField), name: `tiebreakerField`, - onChange: tiebreakerField => - setFormStateChanges(changes => ({ ...changes, tiebreakerField })), + onChange: (tiebreakerField) => + setFormStateChanges((changes) => ({ ...changes, tiebreakerField })), value: formState.tiebreakerField, }), [formState.tiebreakerField] @@ -117,8 +117,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.timestampField), name: `timestampField`, - onChange: timestampField => - setFormStateChanges(changes => ({ ...changes, timestampField })), + onChange: (timestampField) => + setFormStateChanges((changes) => ({ ...changes, timestampField })), value: formState.timestampField, }), [formState.timestampField] diff --git a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx index 0b6a92ed98507..b7e7cb08ec633 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx @@ -68,9 +68,9 @@ export const useLogColumnsConfigurationFormState = ({ formState.logColumns.map( (logColumn): LogColumnConfigurationProps => { const remove = () => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, - logColumns: formState.logColumns.filter(item => item !== logColumn), + logColumns: formState.logColumns.filter((item) => item !== logColumn), })); if (isTimestampLogColumnConfiguration(logColumn)) { @@ -99,7 +99,7 @@ export const useLogColumnsConfigurationFormState = ({ const addLogColumn = useCallback( (logColumnConfiguration: LogColumnConfiguration) => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: [...formState.logColumns, logColumnConfiguration], })), @@ -111,7 +111,7 @@ export const useLogColumnsConfigurationFormState = ({ if (destinationIndex >= 0 && sourceIndex <= formState.logColumns.length - 1) { const newLogColumns = [...formState.logColumns]; newLogColumns.splice(destinationIndex, 0, newLogColumns.splice(sourceIndex, 1)[0]); - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: newLogColumns, })); diff --git a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx index 9ccd28f149ec7..46ab1e65c29d1 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx @@ -85,7 +85,7 @@ export const LogColumnsConfigurationPanel: React.FunctionComponent - {provided => ( + {(provided) => ( = props => ( +const LogColumnConfigurationPanel: React.FunctionComponent = ( + props +) => ( <> {props.logColumnConfigurationProps.type === 'timestamp' ? ( diff --git a/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx b/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx index 7f248cd103003..43bdc1f4cedcc 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx @@ -46,7 +46,7 @@ export const SourceConfigurationSettings = ({ } = useContext(Source.Context); const availableFields = useMemo( - () => (source && source.status ? source.status.indexFields.map(field => field.name) : []), + () => (source && source.status ? source.status.indexFields.map((field) => field.name) : []), [source] ); diff --git a/x-pack/plugins/infra/public/components/toolbar_panel.ts b/x-pack/plugins/infra/public/components/toolbar_panel.ts index 65cde03ec98e7..686b563068d60 100644 --- a/x-pack/plugins/infra/public/components/toolbar_panel.ts +++ b/x-pack/plugins/infra/public/components/toolbar_panel.ts @@ -15,5 +15,5 @@ export const ToolbarPanel = euiStyled(EuiPanel).attrs(() => ({ border-right: none; border-left: none; border-radius: 0; - padding: ${props => `12px ${props.theme.eui.paddingSizes.m}`}; + padding: ${(props) => `12px ${props.theme.eui.paddingSizes.m}`}; `; diff --git a/x-pack/plugins/infra/public/compose_libs.ts b/x-pack/plugins/infra/public/compose_libs.ts index debd83f43d52c..f2060983e95eb 100644 --- a/x-pack/plugins/infra/public/compose_libs.ts +++ b/x-pack/plugins/infra/public/compose_libs.ts @@ -40,7 +40,7 @@ export function composeLibs(core: CoreStart) { headers: undefined, asResponse: true, }) - .then(res => { + .then((res) => { if (!res.response) { return reject(); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts index 21ae7804292dd..6fa2ac175ace6 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts @@ -23,7 +23,7 @@ export const callDeleteJobs = async ( method: 'POST', body: JSON.stringify( deleteJobsRequestPayloadRT.encode({ - jobIds: jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)), + jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), }) ), }); @@ -53,7 +53,7 @@ export const callStopDatafeeds = async ( method: 'POST', body: JSON.stringify( stopDatafeedsRequestPayloadRT.encode({ - datafeedIds: jobTypes.map(jobType => getDatafeedId(spaceId, sourceId, jobType)), + datafeedIds: jobTypes.map((jobType) => getDatafeedId(spaceId, sourceId, jobType)), }) ), }); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts index c3c119f51ff7d..dbd75a646b532 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts @@ -22,7 +22,7 @@ export const callJobsSummaryAPI = async ( method: 'POST', body: JSON.stringify( fetchJobStatusRequestPayloadRT.encode({ - jobIds: jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)), + jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), }) ), }); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx index 7bee10c3bfaa7..9116900ec2196 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx @@ -33,7 +33,7 @@ export const useLogAnalysisCapabilities = () => { fold(throwErrors(createPlainError), identity) ); }, - onResolve: response => { + onResolve: (response) => { setMlCapabilities(response); }, }, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx index a37d18cc33cfd..522616f83d0cb 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx @@ -39,10 +39,10 @@ const waitUntilJobsAreDeleted = async ( sourceId: string, jobTypes: JobType[] ) => { - const moduleJobIds = jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)); + const moduleJobIds = jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)); while (true) { const { jobIds: jobIdsBeingDeleted } = await callGetJobDeletionTasks(); - const needToWait = jobIdsBeingDeleted.some(jobId => moduleJobIds.includes(jobId)); + const needToWait = jobIdsBeingDeleted.some((jobId) => moduleJobIds.includes(jobId)); if (needToWait) { await timeout(1000); @@ -52,4 +52,4 @@ const waitUntilJobsAreDeleted = async ( } }; -const timeout = (ms: number) => new Promise(res => setTimeout(res, ms)); +const timeout = (ms: number) => new Promise((res) => setTimeout(res, ms)); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx index cecfea28100ad..a70758e3aefd7 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx @@ -27,7 +27,7 @@ export const useLogAnalysisModule = ({ dispatchModuleStatus({ type: 'fetchingJobStatuses' }); return await moduleDescriptor.getJobSummary(spaceId, sourceId); }, - onResolve: jobResponse => { + onResolve: (jobResponse) => { dispatchModuleStatus({ type: 'fetchedJobStatuses', payload: jobResponse, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts index ba2185ff83784..353580f454aa3 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts @@ -48,5 +48,5 @@ export const isJobConfigurationOutdated = ( }; const isSubset = (subset: Set, superset: Set) => { - return Array.from(subset).every(subsetElement => superset.has(subsetElement)); + return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); }; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx index ea0cd32c0b93e..1f643d0e5eb34 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx @@ -42,7 +42,7 @@ export const useLogAnalysisModuleDefinition = ({ createPromise: async () => { return await moduleDescriptor.getModuleDefinition(); }, - onResolve: response => { + onResolve: (response) => { setModuleDefinition(response); }, onReject: () => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx index b5530f9ebf72e..0d478ddd0407a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx @@ -98,7 +98,7 @@ const createStatusReducer = (jobTypes: JobType[]) => ( {} as Record ); const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - jobState => jobState === 'started' + (jobState) => jobState === 'started' ) ? { type: 'succeeded' } : { @@ -106,10 +106,10 @@ const createStatusReducer = (jobTypes: JobType[]) => ( reasons: [ ...Object.values(datafeedSetupResults) .filter(hasError) - .map(datafeed => datafeed.error.msg), + .map((datafeed) => datafeed.error.msg), ...Object.values(jobSetupResults) .filter(hasError) - .map(job => job.error.msg), + .map((job) => job.error.msg), ], }; @@ -201,7 +201,7 @@ const hasSuccessfullyCreatedJob = (jobId: string) => ( jobSetupResponses: SetupMlModuleResponsePayload['jobs'] ) => jobSetupResponses.filter( - jobSetupResponse => + (jobSetupResponse) => jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error ).length > 0; @@ -209,7 +209,7 @@ const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] ) => datafeedSetupResponses.filter( - datafeedSetupResponse => + (datafeedSetupResponse) => datafeedSetupResponse.id === datafeedId && datafeedSetupResponse.success && datafeedSetupResponse.started && @@ -218,7 +218,7 @@ const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePayload): JobStatus => jobSummaries - .filter(jobSummary => jobSummary.id === jobId) + .filter((jobSummary) => jobSummary.id === jobId) .map( (jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts index 9f757497aff81..e6fe8f4e92cc4 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts @@ -52,7 +52,7 @@ export const useAnalysisSetupState = ({ ); const [validatedIndices, setValidatedIndices] = useState( - sourceConfiguration.indices.map(indexName => ({ + sourceConfiguration.indices.map((indexName) => ({ name: indexName, validity: 'unknown' as const, })) @@ -60,8 +60,8 @@ export const useAnalysisSetupState = ({ const updateIndicesWithValidationErrors = useCallback( (validationErrors: ValidationIndicesError[]) => - setValidatedIndices(availableIndices => - availableIndices.map(previousAvailableIndex => { + setValidatedIndices((availableIndices) => + availableIndices.map((previousAvailableIndex) => { const indexValiationErrors = validationErrors.filter( ({ index }) => index === previousAvailableIndex.name ); @@ -96,8 +96,8 @@ export const useAnalysisSetupState = ({ const updateIndicesWithAvailableDatasets = useCallback( (availableDatasets: Array<{ indexName: string; datasets: string[] }>) => - setValidatedIndices(availableIndices => - availableIndices.map(previousAvailableIndex => { + setValidatedIndices((availableIndices) => + availableIndices.map((previousAvailableIndex) => { if (previousAvailableIndex.validity !== 'valid') { return previousAvailableIndex; } @@ -112,7 +112,7 @@ export const useAnalysisSetupState = ({ // filter out datasets that have disappeared if this index' datasets were updated const newDatasetFilter: DatasetFilter = availableDatasetsForIndex.length > 0 - ? filterDatasetFilter(previousAvailableIndex.datasetFilter, dataset => + ? filterDatasetFilter(previousAvailableIndex.datasetFilter, (dataset) => newAvailableDatasets.includes(dataset) ) : previousAvailableIndex.datasetFilter; @@ -128,22 +128,22 @@ export const useAnalysisSetupState = ({ ); const validIndexNames = useMemo( - () => validatedIndices.filter(index => index.validity === 'valid').map(index => index.name), + () => validatedIndices.filter((index) => index.validity === 'valid').map((index) => index.name), [validatedIndices] ); const selectedIndexNames = useMemo( () => validatedIndices - .filter(index => index.validity === 'valid' && index.isSelected) - .map(i => i.name), + .filter((index) => index.validity === 'valid' && index.isSelected) + .map((i) => i.name), [validatedIndices] ); const datasetFilter = useMemo( () => validatedIndices - .flatMap(validatedIndex => + .flatMap((validatedIndex) => validatedIndex.validity === 'valid' ? validatedIndex.datasetFilter : { type: 'includeAll' as const } diff --git a/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts b/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts index b9a5c4068e166..a6d66d47975c0 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts @@ -98,8 +98,8 @@ export const logEntriesInitialState: LogEntriesStateParams = { }; const cleanDuplicateItems = (entriesA: LogEntry[], entriesB: LogEntry[]) => { - const ids = new Set(entriesB.map(item => item.id)); - return entriesA.filter(item => !ids.has(item.id)); + const ids = new Set(entriesB.map((item) => item.id)); + return entriesA.filter((item) => !ids.has(item.id)); }; const shouldFetchNewEntries = ({ @@ -280,7 +280,7 @@ const useFetchEntriesEffect = ( (async () => { if (props.isStreaming && !state.isLoadingMore && !state.isReloading) { if (startedStreaming) { - await new Promise(res => setTimeout(res, LIVE_STREAM_INTERVAL)); + await new Promise((res) => setTimeout(res, LIVE_STREAM_INTERVAL)); } else { const endTimestamp = Date.now(); props.jumpToTargetPosition({ tiebreaker: 0, time: endTimestamp }); @@ -335,7 +335,7 @@ const useFetchEntriesEffect = ( export const useLogEntriesState: ( props: LogEntriesProps -) => [LogEntriesStateParams, LogEntriesCallbacks] = props => { +) => [LogEntriesStateParams, LogEntriesCallbacks] = (props) => { const [state, dispatch] = useReducer(logEntriesStateReducer, logEntriesInitialState); const { fetchNewerEntries, checkForNewEntries } = useFetchEntriesEffect(state, dispatch, props); diff --git a/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts b/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts index dd1ba585061fe..7c903f59002dc 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts @@ -48,7 +48,7 @@ export const useLogFilterState: (props: { const setLogFilterQueryDraft = useMemo(() => { const setDraft = (payload: KueryFilterQuery) => - setState(prevState => ({ ...prevState, filterQueryDraft: payload })); + setState((prevState) => ({ ...prevState, filterQueryDraft: payload })); return (expression: string) => setDraft({ kind: 'kuery', @@ -57,7 +57,7 @@ export const useLogFilterState: (props: { }, []); const applyLogFilterQuery = useMemo(() => { const applyQuery = (payload: SerializedFilterQuery) => - setState(prevState => ({ + setState((prevState) => ({ ...prevState, filterQueryDraft: payload.query, filterQuery: payload, diff --git a/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx b/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx index d1da6c715cfc5..24c3f104c2369 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx @@ -17,12 +17,12 @@ export const WithLogFilterUrlState: React.FC = () => { urlState={filterQueryAsKuery} urlStateKey="logFilter" mapToUrlState={mapToFilterQuery} - onChange={urlState => { + onChange={(urlState) => { if (urlState) { applyLogFilterQuery(urlState.expression); } }} - onInitialize={urlState => { + onInitialize={(urlState) => { if (urlState) { applyLogFilterQuery(urlState.expression); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx b/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx index b0981f9b3c41f..0489892e58f2a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx @@ -41,7 +41,7 @@ export const useLogFlyout = () => { } return await fetchLogEntriesItem({ sourceId, id: flyoutId }); }, - onResolve: response => { + onResolve: (response) => { if (response) { const { data } = response; setFlyoutItem(data || null); @@ -94,7 +94,7 @@ export const WithFlyoutOptionsUrlState = () => { }} urlStateKey="flyoutOptions" mapToUrlState={mapToUrlState} - onChange={newUrlState => { + onChange={(newUrlState) => { if (newUrlState && newUrlState.flyoutId) { setFlyoutId(newUrlState.flyoutId); } @@ -108,7 +108,7 @@ export const WithFlyoutOptionsUrlState = () => { setFlyoutVisibility(false); } }} - onInitialize={initialUrlState => { + onInitialize={(initialUrlState) => { if (initialUrlState && initialUrlState.flyoutId) { setFlyoutId(initialUrlState.flyoutId); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx index 7701850443768..dbeb8c71c11eb 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx @@ -42,7 +42,7 @@ export const useLogEntryHighlights = ( highlightTerms, }); }, - onResolve: response => { + onResolve: (response) => { setLogEntryHighlights(response.data); }, }, @@ -55,7 +55,7 @@ export const useLogEntryHighlights = ( useEffect(() => { if ( - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length && + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length && startTimestamp && endTimestamp ) { diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts index 41ee63bf0e23d..6d982ee004ccc 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts @@ -43,7 +43,7 @@ export const useLogSummaryHighlights = ( highlightTerms, }); }, - onResolve: response => { + onResolve: (response) => { setLogSummaryHighlights(response.data); }, }, @@ -60,7 +60,7 @@ export const useLogSummaryHighlights = ( useEffect(() => { if ( - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length && + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length && startTimestamp && endTimestamp ) { diff --git a/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx b/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx index 94723125cc0ec..b83be77656863 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx @@ -23,7 +23,7 @@ export const useLogSummary = ( const bucketSize = useBucketSize(startTimestamp, endTimestamp); useCancellableEffect( - getIsCancelled => { + (getIsCancelled) => { if (startTimestamp === null || endTimestamp === null || bucketSize === null) { return; } @@ -34,7 +34,7 @@ export const useLogSummary = ( endTimestamp, bucketSize, query: filterQuery, - }).then(response => { + }).then((response) => { if (!getIsCancelled()) { setLogSummaryBuckets(response.data.buckets); } diff --git a/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx b/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx index fef7eb19fcf90..ad669e3fe7264 100644 --- a/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx +++ b/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx @@ -26,7 +26,7 @@ export const WithLogTextviewUrlState = () => { urlState={urlState} urlStateKey="logTextview" mapToUrlState={mapToUrlState} - onChange={newUrlState => { + onChange={(newUrlState) => { if (newUrlState && newUrlState.textScale) { setTextScale(newUrlState.textScale); } @@ -34,7 +34,7 @@ export const WithLogTextviewUrlState = () => { setTextWrap(newUrlState.wrap); } }} - onInitialize={newUrlState => { + onInitialize={(newUrlState) => { if (newUrlState && newUrlState.textScale) { setTextScale(newUrlState.textScale); } diff --git a/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts b/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts index 5c0e245448ce5..2b8986820d5a4 100644 --- a/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts +++ b/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts @@ -29,7 +29,7 @@ export const WithStreamItems: React.FunctionComponent<{ () => logEntries.isReloading ? [] - : logEntries.entries.map(logEntry => + : logEntries.entries.map((logEntry) => createLogEntryStreamItem(logEntry, logEntryHighlightsById[logEntry.id] || []) ), diff --git a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx index 04f518aa9080f..b0823f8717a84 100644 --- a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx +++ b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx @@ -81,7 +81,7 @@ function isMetricExplorerOptions(subject: any): subject is MetricsExplorerOption field: t.string, rate: t.boolean, color: t.keyof( - Object.fromEntries(values(MetricsExplorerColor).map(c => [c, null])) as Record + Object.fromEntries(values(MetricsExplorerColor).map((c) => [c, null])) as Record ), label: t.string, }); @@ -114,13 +114,13 @@ function isMetricExplorerOptions(subject: any): subject is MetricsExplorerOption function isMetricExplorerChartOptions(subject: any): subject is MetricsExplorerChartOptions { const ChartOptions = t.type({ yAxisMode: t.keyof( - Object.fromEntries(values(MetricsExplorerYAxisMode).map(v => [v, null])) as Record< + Object.fromEntries(values(MetricsExplorerYAxisMode).map((v) => [v, null])) as Record< string, null > ), type: t.keyof( - Object.fromEntries(values(MetricsExplorerChartType).map(v => [v, null])) as Record< + Object.fromEntries(values(MetricsExplorerChartType).map((v) => [v, null])) as Record< string, null > diff --git a/x-pack/plugins/infra/public/containers/source/source.tsx b/x-pack/plugins/infra/public/containers/source/source.tsx index c2206769ef0ef..96bbd858c3a4b 100644 --- a/x-pack/plugins/infra/public/containers/source/source.tsx +++ b/x-pack/plugins/infra/public/containers/source/source.tsx @@ -54,7 +54,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { setSource(response.data.source); }, }, @@ -82,7 +82,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { if (response.data) { setSource(response.data.createSource.source); } @@ -112,7 +112,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { if (response.data) { setSource(response.data.updateSource.source); } @@ -134,7 +134,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { loadSourceRequest.state, createSourceConfigurationRequest.state, updateSourceConfigurationRequest.state, - ].some(state => state === 'pending'), + ].some((state) => state === 'pending'), [ loadSourceRequest.state, createSourceConfigurationRequest.state, diff --git a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx index 98e59227bc6f0..a04897d9c738d 100644 --- a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx @@ -85,7 +85,7 @@ class WithKueryAutocompletionComponent extends React.Component< boolFilter: [], })) || []; - this.setState(state => + this.setState((state) => state.currentRequest && state.currentRequest.expression !== expression && state.currentRequest.cursorPosition !== cursorPosition diff --git a/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx b/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx index 2c553b57dcd48..2a70edc9b9a57 100644 --- a/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx +++ b/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx @@ -24,7 +24,7 @@ export const useBulkGetSavedObject = (type: string) => { if (!savedObjectsClient) { throw new Error('Saved objects client is unavailable'); } - const d = await savedObjectsClient.bulkGet(ids.map(i => ({ type, id: i }))); + const d = await savedObjectsClient.bulkGet(ids.map((i) => ({ type, id: i }))); setError(null); setLoading(false); setData(d); diff --git a/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx b/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx index 2b704e7984415..8b0ab45f6e6d1 100644 --- a/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx +++ b/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx @@ -48,7 +48,7 @@ export const useFindSavedObject = ({ type, }); - return objects.savedObjects.filter(o => o.attributes.name === name).length > 0; + return objects.savedObjects.filter((o) => o.attributes.name === name).length > 0; }; return { diff --git a/x-pack/plugins/infra/public/hooks/use_http_request.tsx b/x-pack/plugins/infra/public/hooks/use_http_request.tsx index 0a0c876bb63ce..943aa059d5951 100644 --- a/x-pack/plugins/infra/public/hooks/use_http_request.tsx +++ b/x-pack/plugins/infra/public/hooks/use_http_request.tsx @@ -16,7 +16,7 @@ export function useHTTPRequest( pathname: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD', body?: string | null, - decode: (response: any) => Response = response => response, + decode: (response: any) => Response = (response) => response, fetch?: HttpHandler, toastWarning?: (input: ToastInput) => void ) { @@ -37,7 +37,7 @@ export function useHTTPRequest( body, }); }, - onResolve: resp => setResponse(decode(resp)), + onResolve: (resp) => setResponse(decode(resp)), onReject: (e: unknown) => { const err = e as IHttpFetchError; setError(err); diff --git a/x-pack/plugins/infra/public/hooks/use_saved_view.ts b/x-pack/plugins/infra/public/hooks/use_saved_view.ts index 4b12b6c51ea0e..60869d8267b8c 100644 --- a/x-pack/plugins/infra/public/hooks/use_saved_view.ts +++ b/x-pack/plugins/infra/public/hooks/use_saved_view.ts @@ -65,7 +65,7 @@ export const useSavedView = (defaultViewState: ViewState, viewType: s ]; savedObjects.forEach( - o => + (o) => o.type === viewType && items.push({ ...o.attributes, diff --git a/x-pack/plugins/infra/public/pages/error.tsx b/x-pack/plugins/infra/public/pages/error.tsx index b8b598ba1a98b..c34af31ce28a7 100644 --- a/x-pack/plugins/infra/public/pages/error.tsx +++ b/x-pack/plugins/infra/public/pages/error.tsx @@ -21,7 +21,7 @@ import { ColumnarPage, PageContent } from '../components/page'; const DetailPageContent = euiStyled(PageContent)` overflow: auto; - background-color: ${props => props.theme.eui.euiColorLightestShade}; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; `; interface Props { diff --git a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx index 04d5c454a92cc..7a77b1525aea3 100644 --- a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx @@ -18,9 +18,9 @@ interface LinkToPageProps { }; } -const ITEM_TYPES = inventoryModels.map(m => m.id).join('|'); +const ITEM_TYPES = inventoryModels.map((m) => m.id).join('|'); -export const LinkToLogsPage: React.FC = props => { +export const LinkToLogsPage: React.FC = (props) => { return ( ; } -const ITEM_TYPES = inventoryModels.map(m => m.id).join('|'); +const ITEM_TYPES = inventoryModels.map((m) => m.id).join('|'); -export const LinkToMetricsPage: React.FC = props => { +export const LinkToMetricsPage: React.FC = (props) => { return ( - renderHook(props => useHostIpToName(props.ipAddress, props.indexPattern), { + renderHook((props) => useHostIpToName(props.ipAddress, props.indexPattern), { initialProps: { ipAddress: '127.0.0.1', indexPattern: 'metricbest-*' }, }); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts index 45cdd28bd943b..8d9b9130f74a4 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts @@ -39,7 +39,7 @@ const getJobSummary = async (spaceId: string, sourceId: string) => { const response = await callJobsSummaryAPI(spaceId, sourceId, logEntryCategoriesJobTypes); const jobIds = Object.values(getJobIds(spaceId, sourceId)); - return response.filter(jobSummary => jobIds.includes(jobSummary.id)); + return response.filter((jobSummary) => jobIds.includes(jobSummary.id)); }; const getModuleDefinition = async () => { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx index e304a8835e99c..73468dea5d949 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx @@ -89,7 +89,7 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent = () => { const handleQueryTimeRangeChange = useCallback( ({ start: startTime, end: endTime }: { start: string; end: string }) => { - setCategoryQueryTimeRange(previousQueryParameters => ({ + setCategoryQueryTimeRange((previousQueryParameters) => ({ ...previousQueryParameters, timeRange: stringToNumericTimeRange({ startTime, endTime }), lastChangedTime: Date.now(), diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx index 6035c032bdece..dafaa37006be0 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx @@ -14,7 +14,7 @@ export const AnomalySeverityIndicatorList: React.FunctionComponent<{ datasets: LogEntryCategoryDataset[]; }> = ({ datasets }) => (
      - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
    • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx index f6cf62421e2d5..be8281ce54556 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx @@ -48,12 +48,12 @@ export const RegularExpressionRepresentation: React.FunctionComponent<{ }); const CategoryPattern = euiStyled.span` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; word-break: break-all; `; const CategoryPatternWildcard = euiStyled.span` - color: ${props => props.theme.eui.euiColorMediumShade}; + color: ${(props) => props.theme.eui.euiColorMediumShade}; `; const CategoryPatternSegment = euiStyled.span` diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx index a3705cb28ed05..2321dafaead1c 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx @@ -18,7 +18,7 @@ export const DatasetActionsList: React.FunctionComponent<{ timeRange: TimeRange; }> = ({ categorizationJobId, categoryId, datasets, timeRange }) => (
        - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
      • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx index 6918ae0914cc6..748c82cc5cd5a 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx @@ -14,7 +14,7 @@ export const DatasetsList: React.FunctionComponent<{ datasets: LogEntryCategoryDataset[]; }> = ({ datasets }) => (
          - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
        • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx index c2087e9032f59..ab938ff1d1374 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx @@ -20,7 +20,7 @@ export const DatasetsSelector: React.FunctionComponent<{ }> = ({ availableDatasets, isLoading = false, onChangeDatasetSelection, selectedDatasets }) => { const options = useMemo( () => - availableDatasets.map(dataset => ({ + availableDatasets.map((dataset) => ({ value: dataset, label: getFriendlyNameForPartitionId(dataset), })), diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx index 7a29ea9aa0ebc..42d6509802ed4 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx @@ -19,7 +19,7 @@ export const LogEntryCountSparkline: React.FunctionComponent<{ const metric = useMemo( () => histograms - .find(histogram => histogram.histogramId === 'history') + .find((histogram) => histogram.histogramId === 'history') ?.buckets?.map(({ startTime: timestamp, logEntryCount: value }) => ({ timestamp, value, @@ -28,7 +28,7 @@ export const LogEntryCountSparkline: React.FunctionComponent<{ ); const referenceCount = useMemo( () => - histograms.find(histogram => histogram.histogramId === 'reference')?.buckets?.[0] + histograms.find((histogram) => histogram.histogramId === 'reference')?.buckets?.[0] ?.logEntryCount ?? 0, [histograms] ); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx index 811dcba7ff3ef..4fd8aa3cdc1dd 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx @@ -155,7 +155,7 @@ const createColumns = ( { actions: [ { - render: category => ( + render: (category) => ( Object.values(logAnalysisModule.jobStatus).some( - currentJobStatus => currentJobStatus === 'stopped' + (currentJobStatus) => currentJobStatus === 'stopped' ), [logAnalysisModule.jobStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts index 031479e66386f..51e049d576235 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts @@ -14,9 +14,9 @@ export const useLogEntryCategoriesQuality = ({ jobSummaries }: { jobSummaries: J () => jobSummaries .filter( - jobSummary => jobSummary.fullJob?.model_size_stats?.categorization_status === 'warn' + (jobSummary) => jobSummary.fullJob?.model_size_stats?.categorization_status === 'warn' ) - .map(jobSummary => ({ + .map((jobSummary) => ({ type: 'categoryQualityWarning', jobId: jobSummary.id, reasons: jobSummary.fullJob?.model_size_stats diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts index 2282582dc2bd6..123b188046b85 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts @@ -54,7 +54,7 @@ export const useLogEntryCategoriesResults = ({ onResolve: ({ data: { categories } }) => { setTopLogEntryCategories(categories); }, - onReject: error => { + onReject: (error) => { if ( error instanceof Error && !(error instanceof CanceledPromiseError) && @@ -76,7 +76,7 @@ export const useLogEntryCategoriesResults = ({ onResolve: ({ data: { datasets } }) => { setLogEntryCategoryDatasets(datasets); }, - onReject: error => { + onReject: (error) => { if ( error instanceof Error && !(error instanceof CanceledPromiseError) && diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts index dfd427138aaa6..6ca306f39e947 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts @@ -38,7 +38,7 @@ const getJobSummary = async (spaceId: string, sourceId: string) => { const response = await callJobsSummaryAPI(spaceId, sourceId, logEntryRateJobTypes); const jobIds = Object.values(getJobIds(spaceId, sourceId)); - return response.filter(jobSummary => jobIds.includes(jobSummary.id)); + return response.filter((jobSummary) => jobIds.includes(jobSummary.id)); }; const getModuleDefinition = async () => { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx index 46e41f227c08d..79ab4475ee5a3 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx @@ -80,7 +80,7 @@ export const AnomaliesChart: React.FunctionComponent<{ numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 + tickFormat={(value) => numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 /> = ({ isLoading, results, setTimeRange, timeRange, viewSetupForReconfiguration, jobId }) => { const hasAnomalies = useMemo(() => { return results && results.histogramBuckets - ? results.histogramBuckets.some(bucket => { - return bucket.partitions.some(partition => { + ? results.histogramBuckets.some((bucket) => { + return bucket.partitions.some((partition) => { return partition.anomalies.length > 0; }); }) diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx index e8e4c18e7420c..5f578eb1932e6 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx @@ -20,7 +20,7 @@ export const getLogEntryRatePartitionedSeries = (results: LogEntryRateResults) = (buckets, bucket) => { return [ ...buckets, - ...bucket.partitions.map(partition => ({ + ...bucket.partitions.map((partition) => ({ group: getFriendlyNameForPartitionId(partition.partitionId), time: bucket.startTime, value: partition.averageActualLogEntryRate, @@ -136,7 +136,7 @@ export const getAnnotationsForAll = (results: LogEntryRateResults) => { } const severityCategory = getSeverityCategoryForScore( Math.max( - ...maxAnomalyScoresByPartition.map(partitionScore => partitionScore.maximumAnomalyScore) + ...maxAnomalyScoresByPartition.map((partitionScore) => partitionScore.maximumAnomalyScore) ) ); if (!severityCategory) { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx index 263c888ca6000..498a9f88176f8 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx @@ -70,7 +70,7 @@ export const LogEntryRateBarChart: React.FunctionComponent<{ numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 + tickFormat={(value) => numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 /> Object.values(logAnalysisModule.jobStatus).some( - currentJobStatus => currentJobStatus === 'stopped' + (currentJobStatus) => currentJobStatus === 'stopped' ), [logAnalysisModule.jobStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx b/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx index 6e68debceac70..551d200f1895d 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx @@ -63,7 +63,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ }, }, }, - ...availableFields.map(field => ({ + ...availableFields.map((field) => ({ optionProps: { 'data-test-subj': `addFieldLogColumn addFieldLogColumn:${field}`, // this key works around EuiSelectable using a lowercased label as @@ -84,7 +84,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ ); const availableOptions = useMemo( - () => availableColumnOptions.map(availableColumnOption => availableColumnOption.optionProps), + () => availableColumnOptions.map((availableColumnOption) => availableColumnOption.optionProps), [availableColumnOptions] ); @@ -93,7 +93,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ closePopover(); const selectedOptionIndex = selectedOptions.findIndex( - selectedOption => selectedOption.checked === 'on' + (selectedOption) => selectedOption.checked === 'on' ); const selectedOption = availableColumnOptions[selectedOptionIndex]; diff --git a/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts b/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts index a97e38884a5bd..bf52243f89e59 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts +++ b/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts @@ -42,7 +42,7 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.name), name: 'name', - onChange: name => setFormStateChanges(changes => ({ ...changes, name })), + onChange: (name) => setFormStateChanges((changes) => ({ ...changes, name })), value: formState.name, }), [formState.name] @@ -52,7 +52,7 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.logAlias), name: 'logAlias', - onChange: logAlias => setFormStateChanges(changes => ({ ...changes, logAlias })), + onChange: (logAlias) => setFormStateChanges((changes) => ({ ...changes, logAlias })), value: formState.logAlias, }), [formState.logAlias] @@ -62,8 +62,8 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.tiebreakerField), name: `tiebreakerField`, - onChange: tiebreakerField => - setFormStateChanges(changes => ({ ...changes, tiebreakerField })), + onChange: (tiebreakerField) => + setFormStateChanges((changes) => ({ ...changes, tiebreakerField })), value: formState.tiebreakerField, }), [formState.tiebreakerField] @@ -73,8 +73,8 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.timestampField), name: `timestampField`, - onChange: timestampField => - setFormStateChanges(changes => ({ ...changes, timestampField })), + onChange: (timestampField) => + setFormStateChanges((changes) => ({ ...changes, timestampField })), value: formState.timestampField, }), [formState.timestampField] diff --git a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx index 0beccffe5f4e8..45c52617c77fc 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx @@ -66,9 +66,9 @@ export const useLogColumnsConfigurationFormState = ({ formState.logColumns.map( (logColumn): LogColumnConfigurationProps => { const remove = () => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, - logColumns: formState.logColumns.filter(item => item !== logColumn), + logColumns: formState.logColumns.filter((item) => item !== logColumn), })); if (isTimestampLogColumnConfiguration(logColumn)) { @@ -97,7 +97,7 @@ export const useLogColumnsConfigurationFormState = ({ const addLogColumn = useCallback( (logColumnConfiguration: LogColumnConfiguration) => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: [...formState.logColumns, logColumnConfiguration], })), @@ -109,7 +109,7 @@ export const useLogColumnsConfigurationFormState = ({ if (destinationIndex >= 0 && sourceIndex <= formState.logColumns.length - 1) { const newLogColumns = [...formState.logColumns]; newLogColumns.splice(destinationIndex, 0, newLogColumns.splice(sourceIndex, 1)[0]); - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: newLogColumns, })); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx index 777f611ef33f7..3f109e7383c0e 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx @@ -84,7 +84,7 @@ export const LogColumnsConfigurationPanel: React.FunctionComponent - {provided => ( + {(provided) => ( = props => ( +const LogColumnConfigurationPanel: React.FunctionComponent = ( + props +) => ( <> {props.logColumnConfigurationProps.type === 'timestamp' ? ( diff --git a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx index 363b1b7627104..34c4202ab8b65 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx @@ -41,7 +41,7 @@ export const LogsSettingsPage = () => { } = useLogSourceContext(); const availableFields = useMemo( - () => sourceStatus?.logIndexFields.map(field => field.name) ?? [], + () => sourceStatus?.logIndexFields.map((field) => field.name) ?? [], [sourceStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx index 88e6ea8be4325..9fc49073d5ee1 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx @@ -101,7 +101,7 @@ export const LogsToolbar = () => { onChange={setHighlightTerms} isLoading={loadLogEntryHighlightsRequest.state === 'pending'} activeHighlights={ - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length > 0 + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length > 0 } goToPreviousHighlight={goToPreviousHighlight} goToNextHighlight={goToNextHighlight} diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx index 9e0f7d5035aaf..b6e6710a0b3b4 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx @@ -39,7 +39,7 @@ export const PageViewLogInContext: React.FC = () => { const streamItems = useMemo( () => - entries.map(entry => ({ + entries.map((entry) => ({ kind: 'logEntry' as const, logEntry: entry, highlights: [], diff --git a/x-pack/plugins/infra/public/pages/metrics/index.tsx b/x-pack/plugins/infra/public/pages/metrics/index.tsx index 91362d9098e34..35a6cadc786f6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/index.tsx @@ -109,7 +109,7 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => { ( + render={(props) => ( {({ configuration, createDerivedIndexPattern }) => ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx index e89d533c9f10a..8b5b191ccfdd9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx @@ -133,13 +133,13 @@ const MainContainer = euiStyled.div` `; const TopActionContainer = euiStyled.div` - padding: ${props => `12px ${props.theme.eui.paddingSizes.m}`}; + padding: ${(props) => `12px ${props.theme.eui.paddingSizes.m}`}; `; const BottomActionContainer = euiStyled.div` - background-color: ${props => props.theme.eui.euiPageBackgroundColor}; - padding: ${props => props.theme.eui.paddingSizes.m} ${props => - props.theme.eui.paddingSizes.m} ${props => props.theme.eui.paddingSizes.s}; + background-color: ${(props) => props.theme.eui.euiPageBackgroundColor}; + padding: ${(props) => props.theme.eui.paddingSizes.m} ${(props) => + props.theme.eui.paddingSizes.m} ${(props) => props.theme.eui.paddingSizes.s}; position: absolute; left: 0; bottom: 4px; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx index 966a327f40bc1..db5949f916ff4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx @@ -37,8 +37,8 @@ interface Props { } export const calculateBoundsFromNodes = (nodes: SnapshotNode[]): InfraWaffleMapBounds => { - const maxValues = nodes.map(node => node.metric.max); - const minValues = nodes.map(node => node.metric.value); + const maxValues = nodes.map((node) => node.metric.max); + const minValues = nodes.map((node) => node.metric.value); // if there is only one value then we need to set the bottom range to zero for min // otherwise the legend will look silly since both values are the same for top and // bottom. @@ -136,7 +136,7 @@ export const NodesOverview = ({ }; const TableContainer = euiStyled.div` - padding: ${props => props.theme.eui.paddingSizes.l}; + padding: ${(props) => props.theme.eui.paddingSizes.l}; `; const MapContainer = euiStyled.div` diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx index 0557343e735f9..3b68ad314f7df 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx @@ -50,7 +50,7 @@ export const TableView = (props: Props) => { const closePopoverFor = useCallback( (id: string) => () => { if (openPopovers.includes(id)) { - setOpenPopovers(openPopovers.filter(subject => subject !== id)); + setOpenPopovers(openPopovers.filter((subject) => subject !== id)); } }, [openPopovers] @@ -79,7 +79,7 @@ export const TableView = (props: Props) => { // For the table we need to create a UniqueID that takes into to account the groupings // as well as the node name. There is the possibility that a node can be present in two // different groups and be on the screen at the same time. - const uniqueID = [...item.node.path.map(p => p.value), item.node.name].join(':'); + const uniqueID = [...item.node.path.map((p) => p.value), item.node.name].join(':'); return ( { }, ]; - const items = nodes.map(node => { + const items = nodes.map((node) => { const name = last(node.path); return { name: (name && name.label) || 'unknown', diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx index 6a68599aee38c..e9ffc56d8c47f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx @@ -42,7 +42,7 @@ const wrapToolbarItems = ( ) => { return ( - {props => ( + {(props) => ( <> diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx index 090d53f1ff737..4cb8a9dd6624f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx @@ -33,12 +33,12 @@ export const CustomFieldPanel = class extends React.PureComponent const { fields, currentOptions } = this.props; const options = fields .filter( - f => + (f) => f.aggregatable && f.type === 'string' && - !(currentOptions && currentOptions.some(o => o.field === f.name)) + !(currentOptions && currentOptions.some((o) => o.field === f.name)) ) - .map(f => ({ label: f.name })); + .map((f) => ({ label: f.name })); const isSubmitDisabled = !this.state.selectedOptions.length; return (
          diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx index 87f7e4cbff11e..953d94e51aad0 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx @@ -39,7 +39,7 @@ export const GradientLegend: React.FC = ({ legend, bounds, formatter }) = const maxValue = legend.rules.reduce((acc, rule) => { return acc < rule.value ? rule.value : acc; }, 0); - const colorStops = legend.rules.map(rule => { + const colorStops = legend.rules.map((rule) => { const percent = (rule.value / maxValue) * 100; return `${rule.color} ${percent}%`; }); @@ -69,7 +69,7 @@ const GradientLegendTick = euiStyled.div` const GradientLegendTickLine = euiStyled.div` position: absolute; - background-color: ${props => props.theme.eui.euiBorderColor}; + background-color: ${(props) => props.theme.eui.euiBorderColor}; width: 1px; left: 0; top: 15px; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx index 308460203b132..75a023d49d4aa 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx @@ -66,11 +66,11 @@ interface InnerProps { } const Inner = euiStyled.div` - border: 1px solid ${props => props.theme.eui.euiBorderColor}; - background-color: ${props => + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; + background-color: ${(props) => props.isChild ? props.theme.eui.euiColorLightestShade : props.theme.eui.euiColorEmptyShade}; border-radius: 4px; - box-shadow: 0px 2px 0px 0px ${props => props.theme.eui.euiBorderColor}; + box-shadow: 0px 2px 0px 0px ${(props) => props.theme.eui.euiBorderColor}; display: flex; align-items: center; justify-content: center; @@ -87,7 +87,7 @@ const Name = euiStyled.div` const Count = euiStyled.div` flex: 0 0 auto; - border-left: 1px solid ${props => props.theme.eui.euiBorderColor}; + border-left: 1px solid ${(props) => props.theme.eui.euiBorderColor}; padding: 6px 10px; font-size: 0.85em; font-weight: normal; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx index 6b3f22007f580..760dae169d000 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx @@ -26,12 +26,12 @@ interface Props { currentTime: number; } -export const GroupOfGroups: React.FC = props => { +export const GroupOfGroups: React.FC = (props) => { return ( - {props.group.groups.map(group => ( + {props.group.groups.map((group) => ( props.theme.eui.euiBorderColor}; + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; box-shadow: 0 1px 7px rgba(0, 0, 0, 0.1); `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx index fc438ed4ca0a2..a6c9efb5e17d1 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx @@ -42,7 +42,7 @@ export const GroupOfNodes: React.FC = ({ - {group.nodes.map(node => ( + {group.nodes.map((node) => ( props.theme.eui.euiBorderColor}; + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; box-shadow: 0 1px 7px rgba(0, 0, 0, 0.1); `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx index e5ee19e48884c..7929cf8292cb6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx @@ -55,7 +55,7 @@ const PALETTE_NAMES: InventoryColorPalette[] = [ 'negative', ]; -const PALETTE_OPTIONS = PALETTE_NAMES.map(name => ({ text: PALETTES[name], value: name })); +const PALETTE_OPTIONS = PALETTE_NAMES.map((name) => ({ text: PALETTES[name], value: name })); export const LegendControls = ({ autoBounds, @@ -99,7 +99,7 @@ export const LegendControls = ({ const handleReverseColors = useCallback( (e: EuiSwitchEvent) => { - setLegendOptions(previous => ({ ...previous, reverseColors: e.target.checked })); + setLegendOptions((previous) => ({ ...previous, reverseColors: e.target.checked })); }, [setLegendOptions] ); @@ -140,15 +140,15 @@ export const LegendControls = ({ }, [autoBounds, boundsOverride, options]); const handleStepsChange = useCallback( - e => { - setLegendOptions(previous => ({ ...previous, steps: parseInt(e.target.value, 10) })); + (e) => { + setLegendOptions((previous) => ({ ...previous, steps: parseInt(e.target.value, 10) })); }, [setLegendOptions] ); const handlePaletteChange = useCallback( - e => { - setLegendOptions(previous => ({ ...previous, palette: e.target.value })); + (e) => { + setLegendOptions((previous) => ({ ...previous, palette: e.target.value })); }, [setLegendOptions] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx index eee8c69091ef0..5838317f07100 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx @@ -47,7 +47,7 @@ export const Map: React.FC = ({ return ( measureRef(el)} data-test-subj="waffleMap"> - {groupsWithLayout.map(group => { + {groupsWithLayout.map((group) => { if (isWaffleMapGroupWithGroups(group)) { return ( { + (e) => { setLabel(e.target.value); }, [setLabel] @@ -103,7 +103,7 @@ export const CustomMetricForm = withTheme( ); const handleAggregationChange = useCallback( - e => { + (e) => { const value = e.target.value; const aggValue: SnapshotCustomAggregation = SnapshotCustomAggregationRT.is(value) ? value @@ -114,10 +114,10 @@ export const CustomMetricForm = withTheme( ); const fieldOptions = fields - .filter(f => f.aggregatable && f.type === 'number' && !(field && field === f.name)) - .map(f => ({ label: f.name })); + .filter((f) => f.aggregatable && f.type === 'number' && !(field && field === f.name)) + .map((f) => ({ label: f.name })); - const aggregationOptions = SNAPSHOT_CUSTOM_AGGREGATIONS.map(k => ({ + const aggregationOptions = SNAPSHOT_CUSTOM_AGGREGATIONS.map((k) => ({ text: AGGREGATION_LABELS[k as SnapshotCustomAggregation], value: k, })); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx index 0cf1faec06c11..aae787c8c0395 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx @@ -84,7 +84,7 @@ export const WaffleMetricControls = ({ onChange({ type: options[0].value as SnapshotMetricType }); } // Filter out the deleted metric from the editbale. - const newMetrics = editModeCustomMetrics.filter(v => v.id !== m.id); + const newMetrics = editModeCustomMetrics.filter((v) => v.id !== m.id); setEditModeCustomMetrics(newMetrics); }, [editModeCustomMetrics, metric, onChange, options] @@ -92,7 +92,9 @@ export const WaffleMetricControls = ({ const handleEditCustomMetric = useCallback( (currentMetric: SnapshotCustomMetricInput) => { - const newMetrics = customMetrics.map(m => (m.id === currentMetric.id && currentMetric) || m); + const newMetrics = customMetrics.map( + (m) => (m.id === currentMetric.id && currentMetric) || m + ); onChangeCustomMetrics(newMetrics); setModeToPick(); setEditCustomMetric(void 0); @@ -125,7 +127,7 @@ export const WaffleMetricControls = ({ const id = SnapshotCustomMetricInputRT.is(metric) && metric.id ? metric.id : metric.type; const currentLabel = SnapshotCustomMetricInputRT.is(metric) ? getCustomMetricLabel(metric) - : options.find(o => o.value === id)?.text; + : options.find((o) => o.value === id)?.text; if (!currentLabel) { return null; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx index 1cdef493aee4f..7ab90297ebbb3 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx @@ -36,7 +36,7 @@ export const MetricsContextMenu = ({ const handleClick = useCallback( (val: string) => { if (!SnapshotMetricTypeRT.is(val)) { - const selectedMetric = customMetrics.find(m => m.id === val); + const selectedMetric = customMetrics.find((m) => m.id === val); if (selectedMetric) { onChange(selectedMetric); } @@ -53,12 +53,12 @@ export const MetricsContextMenu = ({ id: 0, title: '', items: [ - ...options.map(o => { + ...options.map((o) => { const icon = o.value === id ? 'check' : 'empty'; const panel = { name: o.text, onClick: () => handleClick(o.value), icon }; return panel; }), - ...customMetrics.map(m => { + ...customMetrics.map((m) => { const icon = m.id === id ? 'check' : 'empty'; const panel = { name: getCustomMetricLabel(m), diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx index 4d1bc906de0b9..89edaacdb8a1d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx @@ -26,12 +26,12 @@ export const MetricsEditMode = withTheme( ({ theme, customMetrics, options, onEdit, onDelete }: Props) => { return (
          - {options.map(option => ( + {options.map((option) => (
          {option.text}
          ))} - {customMetrics.map(metric => ( + {customMetrics.map((metric) => ( { } private togglePopover = () => { - this.setState(prevState => ({ isPopoverOpen: !prevState.isPopoverOpen })); + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen })); }; private closePopover = () => { @@ -119,7 +119,7 @@ const SquareOuter = euiStyled.div` left: 4px; bottom: 4px; right: 4px; - background-color: ${props => darken(0.1, props.color)}; + background-color: ${(props) => darken(0.1, props.color)}; border-radius: 3px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2); `; @@ -132,7 +132,7 @@ const SquareInner = euiStyled.div` bottom: 2px; left: 0; border-radius: 3px; - background-color: ${props => props.color}; + background-color: ${(props) => props.color}; `; const ValueInner = euiStyled.button` @@ -152,8 +152,8 @@ const ValueInner = euiStyled.button` border: none; &:focus { outline: none !important; - border: ${params => params.theme.eui.euiFocusRingSize} solid - ${params => params.theme.eui.euiFocusRingColor}; + border: ${(params) => params.theme.eui.euiFocusRingSize} solid + ${(params) => params.theme.eui.euiFocusRingColor}; box-shadow: none; } `; @@ -165,7 +165,7 @@ const SquareTextContent = euiStyled.div` text-overflow: ellipsis; white-space: nowrap; flex: 1 0 auto; - color: ${props => readableColor(props.color)}; + color: ${(props) => readableColor(props.color)}; `; const Value = euiStyled(SquareTextContent)` diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx index cfcdad2d8927c..18f15ba7ab81f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx @@ -19,7 +19,7 @@ export const PalettePreview = ({ steps, palette, reverse }: Props) => { const colors = getColorPalette(palette, steps, reverse); return ( - {colors.map(color => ( + {colors.map((color) => ( ))} @@ -31,11 +31,11 @@ const Swatch = euiStyled.div` height: 12px; flex: 0 0 auto; &:first-child { - border-radius: ${props => props.theme.eui.euiBorderRadius} 0 0 ${props => + border-radius: ${(props) => props.theme.eui.euiBorderRadius} 0 0 ${(props) => props.theme.eui.euiBorderRadius}; } &:last-child { - border-radius: 0 ${props => props.theme.eui.euiBorderRadius} ${props => + border-radius: 0 ${(props) => props.theme.eui.euiBorderRadius} ${(props) => props.theme.eui.euiBorderRadius} 0; `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx index 2facef521c393..fadf6b139a3e8 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx @@ -51,14 +51,14 @@ const TickLabel = ({ value, bounds, formatter }: TickProps) => { }; const GradientStep = euiStyled.div` - height: ${props => props.theme.eui.paddingSizes.s}; + height: ${(props) => props.theme.eui.paddingSizes.s}; flex: 1 1 auto; &:first-child { - border-radius: ${props => props.theme.eui.euiBorderRadius} 0 0 ${props => + border-radius: ${(props) => props.theme.eui.euiBorderRadius} 0 0 ${(props) => props.theme.eui.euiBorderRadius}; } &:last-child { - border-radius: 0 ${props => props.theme.eui.euiBorderRadius} ${props => + border-radius: 0 ${(props) => props.theme.eui.euiBorderRadius} ${(props) => props.theme.eui.euiBorderRadius} 0; } `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx index 5ac6320510257..565b22a77ea5d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx @@ -28,7 +28,7 @@ export const WaffleAccountsControls = (props: Props) => { setIsOpen(false); }, [setIsOpen]); - const currentLabel = options.find(o => o.value === accountId); + const currentLabel = options.find((o) => o.value === accountId); const changeAccount = useCallback( (val: string) => { @@ -47,7 +47,7 @@ export const WaffleAccountsControls = (props: Props) => { { id: 0, title: '', - items: options.map(o => { + items: options.map((o) => { const icon = o.value === accountId ? 'check' : 'empty'; const panel = { name: o.name, onClick: () => changeAccount(o.value), icon }; return panel; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx index cc09ce226b2fe..8d2f289621b12 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx @@ -44,7 +44,7 @@ export const WaffleGroupByControls = class extends React.PureComponent ({ + const customOptions = this.props.customOptions.map((option) => ({ ...option, toolTipContent: option.text, })); @@ -80,8 +80,8 @@ export const WaffleGroupByControls = class extends React.PureComponent { - const icon = groupBy.some(g => g.field === o.field) ? 'check' : 'empty'; + ...options.map((o) => { + const icon = groupBy.some((g) => g.field === o.field) ? 'check' : 'empty'; const panel = { name: o.text, onClick: this.handleClick(o.field), @@ -116,11 +116,11 @@ export const WaffleGroupByControls = class extends React.PureComponent 0 ? ( groupBy - .map(g => options.find(o => o.field === g.field)) - .filter(o => o != null) + .map((g) => options.find((o) => o.field === g.field)) + .filter((o) => o != null) // In this map the `o && o.field` is totally unnecessary but Typescript is // too stupid to realize that the filter above prevents the next map from being null - .map(o => ( + .map((o) => ( {o && o.text} @@ -153,8 +153,8 @@ export const WaffleGroupByControls = class extends React.PureComponent () => { const { groupBy } = this.props; - this.props.onChange(groupBy.filter(g => g.field !== field)); - const options = this.props.customOptions.filter(g => g.field !== field); + this.props.onChange(groupBy.filter((g) => g.field !== field)); + const options = this.props.customOptions.filter((g) => g.field !== field); this.props.onChangeCustomOptions(options); // We need to close the panel after we rmeove the pill icon otherwise // it will remain open because the click is still captured by the EuiFilterButton @@ -166,7 +166,7 @@ export const WaffleGroupByControls = class extends React.PureComponent { - this.setState(state => ({ isPopoverOpen: !state.isPopoverOpen })); + this.setState((state) => ({ isPopoverOpen: !state.isPopoverOpen })); }; private handleCustomField = (field: string) => { @@ -184,7 +184,7 @@ export const WaffleGroupByControls = class extends React.PureComponent () => { const { groupBy } = this.props; - if (groupBy.some(g => g.field === field)) { + if (groupBy.some((g) => g.field === field)) { this.handleRemove(field)(); } else if (this.props.groupBy.length < 2) { this.props.onChange([...groupBy, { field }]); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx index 9c28f0798b519..575b1f9a73aa4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx @@ -27,7 +27,7 @@ export const WaffleRegionControls = (props: Props) => { setIsOpen(false); }, [setIsOpen]); - const currentLabel = options.find(o => region === o); + const currentLabel = options.find((o) => region === o); const changeRegion = useCallback( (val: string) => { @@ -46,7 +46,7 @@ export const WaffleRegionControls = (props: Props) => { { id: 0, title: '', - items: options.map(o => { + items: options.map((o) => { const icon = o === region ? 'check' : 'empty'; const panel = { name: o, onClick: () => changeRegion(o), icon }; return panel; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts index f6cbb59779039..63d9d08796f05 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts @@ -50,7 +50,7 @@ export const useWaffleFilters = () => { const applyFilterQueryFromKueryExpression = useCallback( (expression: string) => { - setState(previous => ({ + setState((previous) => ({ ...previous, kind: 'kuery', expression, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts index 1e99e909cbb3d..975e33cf2415f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts @@ -54,68 +54,69 @@ export const useWaffleOptions = () => { useEffect(() => setUrlState(state), [setUrlState, state]); const changeMetric = useCallback( - (metric: SnapshotMetricInput) => setState(previous => ({ ...previous, metric })), + (metric: SnapshotMetricInput) => setState((previous) => ({ ...previous, metric })), [setState] ); const changeGroupBy = useCallback( - (groupBy: SnapshotGroupBy) => setState(previous => ({ ...previous, groupBy })), + (groupBy: SnapshotGroupBy) => setState((previous) => ({ ...previous, groupBy })), [setState] ); const changeNodeType = useCallback( - (nodeType: InventoryItemType) => setState(previous => ({ ...previous, nodeType })), + (nodeType: InventoryItemType) => setState((previous) => ({ ...previous, nodeType })), [setState] ); - const changeView = useCallback((view: string) => setState(previous => ({ ...previous, view })), [ - setState, - ]); + const changeView = useCallback( + (view: string) => setState((previous) => ({ ...previous, view })), + [setState] + ); const changeCustomOptions = useCallback( (customOptions: Array<{ text: string; field: string }>) => - setState(previous => ({ ...previous, customOptions })), + setState((previous) => ({ ...previous, customOptions })), [setState] ); const changeAutoBounds = useCallback( - (autoBounds: boolean) => setState(previous => ({ ...previous, autoBounds })), + (autoBounds: boolean) => setState((previous) => ({ ...previous, autoBounds })), [setState] ); const changeBoundsOverride = useCallback( (boundsOverride: { min: number; max: number }) => - setState(previous => ({ ...previous, boundsOverride })), + setState((previous) => ({ ...previous, boundsOverride })), [setState] ); const changeAccount = useCallback( - (accountId: string) => setState(previous => ({ ...previous, accountId })), + (accountId: string) => setState((previous) => ({ ...previous, accountId })), [setState] ); const changeRegion = useCallback( - (region: string) => setState(previous => ({ ...previous, region })), + (region: string) => setState((previous) => ({ ...previous, region })), [setState] ); const changeCustomMetrics = useCallback( (customMetrics: SnapshotCustomMetricInput[]) => { - setState(previous => ({ ...previous, customMetrics })); + setState((previous) => ({ ...previous, customMetrics })); }, [setState] ); const changeLegend = useCallback( (legend: WaffleLegendOptions) => { - setState(previous => ({ ...previous, legend })); + setState((previous) => ({ ...previous, legend })); }, [setState] ); const changeSort = useCallback( (sort: WaffleSortOption) => { - setState(previous => ({ ...previous, sort })); + setState((previous) => ({ ...previous, sort })); }, [setState] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts index db3abd37b58dd..91cf405dcc759 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts @@ -31,16 +31,16 @@ export const useWaffleTime = () => { const { currentTime, isAutoReloading } = urlState; const startAutoReload = useCallback(() => { - setState(previous => ({ ...previous, isAutoReloading: true })); + setState((previous) => ({ ...previous, isAutoReloading: true })); }, [setState]); const stopAutoReload = useCallback(() => { - setState(previous => ({ ...previous, isAutoReloading: false })); + setState((previous) => ({ ...previous, isAutoReloading: false })); }, [setState]); const jumpToTime = useCallback( (time: number) => { - setState(previous => ({ ...previous, currentTime: time })); + setState((previous) => ({ ...previous, currentTime: time })); }, [setState] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts index 68600ac5d2ce4..5b749fab5839f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts @@ -66,14 +66,14 @@ export function applyWaffleMapLayout( const largestCount = getLargestCount(groups); return sortBy(groups, getTotalItemsOfGroup) .reverse() - .map(group => { + .map((group) => { if (isWaffleMapGroupWithGroups(group)) { const columns = getColumns(largestCount, width, height); const groupOfNodes = group.groups; const subGroups = sortBy(groupOfNodes, getTotalItemsOfGroup) .reverse() .filter(isWaffleMapGroupWithNodes) - .map(subGroup => { + .map((subGroup) => { return { ...subGroup, count: subGroup.nodes.length, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts index 9cdd2032b73d9..c6a7eaf5fdc63 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts @@ -117,7 +117,7 @@ export const calculateGradientColor = ( } return acc; }, first(sortedRules)); - const endRule = sortedRules.filter(r => r !== startRule).find(r => r.value >= normValue); + const endRule = sortedRules.filter((r) => r !== startRule).find((r) => r.value >= normValue); if (!endRule) { return startRule.color; } diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts index 469b54b2d9d68..a6a356a78be44 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts @@ -16,7 +16,7 @@ import { isWaffleMapGroupWithGroups, isWaffleMapGroupWithNodes } from './type_gu import { SnapshotNodePath, SnapshotNode } from '../../../../../common/http_api/snapshot_api'; export function createId(path: SnapshotNodePath[]) { - return path.map(p => p.value).join('/'); + return path.map((p) => p.value).join('/'); } function findOrCreateGroupWithNodes( @@ -31,16 +31,16 @@ function findOrCreateGroupWithNodes( */ if (path.length === 2) { const parentId = first(path).value; - const existingParentGroup = groups.find(g => g.id === parentId); + const existingParentGroup = groups.find((g) => g.id === parentId); if (isWaffleMapGroupWithGroups(existingParentGroup)) { - const existingSubGroup = existingParentGroup.groups.find(g => g.id === id); + const existingSubGroup = existingParentGroup.groups.find((g) => g.id === id); if (isWaffleMapGroupWithNodes(existingSubGroup)) { return existingSubGroup; } } } const lastPath = last(path); - const existingGroup = groups.find(g => g.id === id); + const existingGroup = groups.find((g) => g.id === id); if (isWaffleMapGroupWithNodes(existingGroup)) { return existingGroup; } @@ -65,7 +65,7 @@ function findOrCreateGroupWithGroups( ): InfraWaffleMapGroupOfGroups { const id = path.length === 0 ? '__all__' : createId(path); const lastPath = last(path); - const existingGroup = groups.find(g => g.id === id); + const existingGroup = groups.find((g) => g.id === id); if (isWaffleMapGroupWithGroups(existingGroup)) { return existingGroup; } @@ -90,7 +90,7 @@ export function createWaffleMapNode(node: SnapshotNode): InfraWaffleMapNode { throw new Error('There must be at least one node path item'); } return { - pathId: node.path.map(p => p.value).join('/'), + pathId: node.path.map((p) => p.value).join('/'), path: node.path, id: nodePathItem.value, ip: nodePathItem.ip, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx index 7bf5dd6caae48..6a4d6521855a9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx @@ -117,7 +117,7 @@ export const ChartSectionVis = ({ /> {metric && - metric.series.map(series => ( + metric.series.map((series) => ( - {metric.series.map(series => { + {metric.series.map((series) => { const lastDataPoint = last(series.data); if (!lastDataPoint) { return null; @@ -67,7 +67,7 @@ export const GaugesSectionVis = ({ ); const value = formatterFn(lastDataPoint.value || 0); const name = getChartName(seriesOverrides, series.id, series.id); - const dataMax = max(series.data.map(d => d.value || 0)); + const dataMax = max(series.data.map((d) => d.value || 0)); const gaugeMax = get(seriesOverrides, [series.id, 'gaugeMax'], dataMax); return ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx index 7ca69dd56251d..656378fbc0610 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx @@ -83,7 +83,7 @@ const FIELDS = [ ] as FieldDef[]; const getLabelForField = ({ field }: FieldDef) => { - const fieldDef = FIELDS.find(f => f.field === field); + const fieldDef = FIELDS.find((f) => f.field === field); if (!fieldDef) return field; return fieldDef.label; }; @@ -115,13 +115,13 @@ export const MetadataDetails = (props: Props) => { const filteredFields = useMemo(() => { if (props.fields && props.fields.length) { return props.fields - .map(field => { - const fieldDef = FIELDS.find(f => f.field === field); + .map((field) => { + const fieldDef = FIELDS.find((f) => f.field === field); if (fieldDef) { return fieldDef; } }) - .filter(f => f) as FieldDef[]; + .filter((f) => f) as FieldDef[]; } else { return FIELDS; } @@ -150,7 +150,7 @@ export const MetadataDetails = (props: Props) => { ) : null} - {fields.map(field => ( + {fields.map((field) => (
          {getLabelForField(field)}
          @@ -164,17 +164,17 @@ export const MetadataDetails = (props: Props) => { }; const MetadataContainer = euiStyled.div` -border-top: ${props => props.theme.eui.euiBorderWidthThin} solid ${props => +border-top: ${(props) => props.theme.eui.euiBorderWidthThin} solid ${(props) => props.theme.eui.euiBorderColor}; -border-bottom: ${props => props.theme.eui.euiBorderWidthThin} solid ${props => +border-bottom: ${(props) => props.theme.eui.euiBorderWidthThin} solid ${(props) => props.theme.eui.euiBorderColor}; -padding: ${props => props.theme.eui.paddingSizes.m} 0; -margin-bottom: ${props => props.theme.eui.paddingSizes.m}; +padding: ${(props) => props.theme.eui.paddingSizes.m} 0; +margin-bottom: ${(props) => props.theme.eui.paddingSizes.m}; display: flex; `; const Controls = euiStyled.div` flex-grow: 0; -margin-right: ${props => props.theme.eui.paddingSizes.m}; +margin-right: ${(props) => props.theme.eui.paddingSizes.m}; min-width: 0px; `; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx index 68003737a1f14..5e040c536985b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx @@ -37,7 +37,7 @@ export const Section: FunctionComponent = ({ if (!isValidElement(child)) { return accumulatedChildren; } - const metric = metrics?.find(m => m.id === child.props.id) ?? null; + const metric = metrics?.find((m) => m.id === child.props.id) ?? null; if (metric === null) { return accumulatedChildren; } @@ -61,7 +61,7 @@ export const Section: FunctionComponent = ({ [] ); - const childrenWithProps = Children.map(children, child => + const childrenWithProps = Children.map(children, (child) => isValidElement(child) ? cloneElement(child, { metrics, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx index 7b269adc96638..4c75003616117 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx @@ -23,13 +23,13 @@ export const SubSection: FunctionComponent = ({ isLiveStreaming, stopLiveStreaming, }) => { - const metric = useMemo(() => metrics?.find(m => m.id === id), [id, metrics]); + const metric = useMemo(() => metrics?.find((m) => m.id === id), [id, metrics]); if (!children || !metric) { return null; } - const childrenWithProps = Children.map(children, child => { + const childrenWithProps = Children.map(children, (child) => { if (isValidElement(child)) { return cloneElement(child, { metric, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts index 98803ef2e69c6..5f695f31fc180 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts @@ -20,11 +20,7 @@ const parseRange = (range: MetricsTimeInput) => { const parsedTo = dateMath.parse(range.to.toString(), { roundUp: true }); return { ...range, - from: - (parsedFrom && parsedFrom.valueOf()) || - moment() - .subtract(1, 'hour') - .valueOf(), + from: (parsedFrom && parsedFrom.valueOf()) || moment().subtract(1, 'hour').valueOf(), to: (parsedTo && parsedTo.valueOf()) || moment().valueOf(), }; }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx index 197a735f7fd1f..4ae96f733382f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx @@ -23,7 +23,7 @@ import { useLinkProps } from '../../../hooks/use_link_props'; const DetailPageContent = euiStyled(PageContent)` overflow: auto; - background-color: ${props => props.theme.eui.euiColorLightestShade}; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; `; interface Props { @@ -65,7 +65,7 @@ export const MetricDetail = withMetricPageProviders( const addNavItem = React.useCallback( (item: NavItem) => { - if (!sideNav.some(n => n.id === item.id)) { + if (!sideNav.some((n) => n.id === item.id)) { setSideNav([item, ...sideNav]); } }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts index 57ff182f01963..7dc2f2b0ccd1f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts @@ -13,13 +13,13 @@ export const getFilteredMetrics = ( metadata: Array ) => { const metricMetadata = metadata - .filter(data => data && data.source === 'metrics') - .map(data => data && data.name); - return requiredMetrics.filter(metric => { + .filter((data) => data && data.source === 'metrics') + .map((data) => data && data.name); + return requiredMetrics.filter((metric) => { const metricModelCreator = metrics.tsvb[metric]; // We just need to get a dummy version of the model so we can filter // using the `requires` attribute. const metricModel = metricModelCreator('@timestamp', 'test', '>=1m'); - return metricMetadata.some(m => m && metricModel.requires.includes(m)); + return metricMetadata.some((m) => m && metricModel.requires.includes(m)); }); }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx index 8d397d9f96b59..02d3d2c583a7f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx @@ -53,7 +53,7 @@ export const MetricsExplorerAggregationPicker = ({ options, onChange }: Props) = }; const handleChange = useCallback( - e => { + (e) => { const aggregation = (metricsExplorerAggregationRT.is(e.target.value) && e.target.value) || 'avg'; onChange(aggregation); @@ -71,7 +71,7 @@ export const MetricsExplorerAggregationPicker = ({ options, onChange }: Props) = placeholder={placeholder} fullWidth value={options.aggregation} - options={METRIC_EXPLORER_AGGREGATIONS.map(k => ({ + options={METRIC_EXPLORER_AGGREGATIONS.map((k) => ({ text: AGGREGATION_LABELS[k as MetricsExplorerAggregation], value: k, }))} diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx index ba28075ededb6..d21454dba5178 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx @@ -103,7 +103,7 @@ export const MetricsExplorerChartOptions = ({ chartOptions, onChange }: Props) = ); const handleStackChange = useCallback( - e => { + (e) => { onChange({ ...chartOptions, stack: e.target.checked, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx index 2929a7316bd79..b9595548debf2 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx @@ -81,7 +81,7 @@ export const MetricsExplorerCharts = ({ return (
          - {data.series.map(series => ( + {data.series.map((series) => ( { const handleChange = useCallback( (selectedOptions: Array<{ label: string }>) => { - const groupBy = selectedOptions.map(option => option.label); + const groupBy = selectedOptions.map((option) => option.label); onChange(groupBy); }, [onChange] ); const selectedOptions = Array.isArray(options.groupBy) - ? options.groupBy.map(field => ({ label: field })) + ? options.groupBy.map((field) => ({ label: field })) : options.groupBy ? [{ label: options.groupBy }] : []; @@ -44,8 +44,8 @@ export const MetricsExplorerGroupBy = ({ options, onChange, fields }: Props) => singleSelection={false} selectedOptions={selectedOptions} options={fields - .filter(f => f.aggregatable && f.type === 'string') - .map(f => ({ label: f.name }))} + .filter((f) => f.aggregatable && f.type === 'string') + .map((f) => ({ label: f.name }))} onChange={handleChange} isClearable={true} /> diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts index 5cfc8c366b444..85cdbb6731c59 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts @@ -29,13 +29,13 @@ export const calculateDomain = ( .map((m, index) => { return (row[getMetricId(m, index)] as number) || null; }) - .filter(v => isNumber(v)); + .filter((v) => isNumber(v)); const minValue = getMin(rowValues); // For stacked domains we want to add 10% head room so the charts have // enough room to draw the 2 pixel line as well. const maxValue = stacked ? sum(rowValues) * 1.1 : getMax(rowValues); return acc.concat([minValue || null, maxValue || null]); }, [] as Array) - .filter(v => isNumber(v)); + .filter((v) => isNumber(v)); return { min: getMin(values) || 0, max: getMax(values) || 0 }; }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx index 612735e2ba772..8be03a7096f08 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx @@ -41,7 +41,7 @@ export const MetricsExplorerMetrics = ({ options, onChange, fields, autoFocus = ); const handleChange = useCallback( - selectedOptions => { + (selectedOptions) => { onChange( selectedOptions.map((opt: SelectedOption, index: number) => ({ aggregation: options.aggregation, @@ -53,10 +53,10 @@ export const MetricsExplorerMetrics = ({ options, onChange, fields, autoFocus = [onChange, options.aggregation, colors] ); - const comboOptions = fields.map(field => ({ label: field.name, value: field.name })); + const comboOptions = fields.map((field) => ({ label: field.name, value: field.name })); const selectedOptions = options.metrics - .filter(m => m.aggregation !== 'count') - .map(metric => ({ + .filter((m) => m.aggregation !== 'count') + .map((metric) => ({ label: metric.field || '', value: metric.field || '', color: colorTransformer(metric.color || MetricsExplorerColor.color0), diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx index 223318da8cf46..9b594ef5e630f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx @@ -46,11 +46,11 @@ export const MetricsExplorerAreaChart = ({ metric, id, series, type, stack, opac colorTransformer(MetricsExplorerColor.color0); const yAccessors = Array.isArray(id) - ? id.map(i => getMetricId(metric, i)).slice(id.length - 1, id.length) + ? id.map((i) => getMetricId(metric, i)).slice(id.length - 1, id.length) : [getMetricId(metric, id)]; const y0Accessors = Array.isArray(id) && id.length > 1 - ? id.map(i => getMetricId(metric, i)).slice(0, 1) + ? id.map((i) => getMetricId(metric, i)).slice(0, 1) : undefined; const chartId = `series-${series.id}-${yAccessors.join('-')}`; @@ -89,7 +89,7 @@ export const MetricsExplorerBarChart = ({ metric, id, series, stack }: Props) => colorTransformer(MetricsExplorerColor.color0); const yAccessors = Array.isArray(id) - ? id.map(i => getMetricId(metric, i)).slice(id.length - 1, id.length) + ? id.map((i) => getMetricId(metric, i)).slice(id.length - 1, id.length) : [getMetricId(metric, id)]; const chartId = `series-${series.id}-${yAccessors.join('-')}`; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx index f0734f76cfacd..e312fe2dc1d9d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx @@ -16,7 +16,7 @@ import { } from '../../../../utils/fixtures/metrics_explorer'; const renderUseMetricsExplorerStateHook = () => - renderHook(props => useMetricsExplorerState(props.source, props.derivedIndexPattern), { + renderHook((props) => useMetricsExplorerState(props.source, props.derivedIndexPattern), { initialProps: { source, derivedIndexPattern }, wrapper: ({ children }) => ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts index 936c6e456beb7..66cc77a576f99 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts @@ -102,8 +102,8 @@ export const useMetricsExplorerState = ( aggregation === 'count' ? [{ aggregation }] : options.metrics - .filter(metric => metric.aggregation !== 'count') - .map(metric => ({ + .filter((metric) => metric.aggregation !== 'count') + .map((metric) => ({ ...metric, aggregation, })); diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx index f0b2627288d45..b33fe5c232f01 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx @@ -31,7 +31,7 @@ const renderUseMetricsExplorerDataHook = () => { return {children}; }; return renderHook( - props => + (props) => useMetricsExplorerData( props.options, props.source, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts index 3a767b94d00c7..5ed710414718a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts @@ -64,7 +64,7 @@ export function useMetricsExplorerData( metrics: options.aggregation === 'count' ? [{ aggregation: 'count' }] - : options.metrics.map(metric => ({ + : options.metrics.map((metric) => ({ aggregation: metric.aggregation, field: metric.field, })), diff --git a/x-pack/plugins/infra/public/utils/datemath.ts b/x-pack/plugins/infra/public/utils/datemath.ts index 7331a2450956f..f2bd5d94ac2c3 100644 --- a/x-pack/plugins/infra/public/utils/datemath.ts +++ b/x-pack/plugins/infra/public/utils/datemath.ts @@ -218,8 +218,8 @@ export function convertDate(value: number, from: Unit, to: Unit): number { } const ratioScale = getRatioScale(from, to); - const fromIdx = ratioScale.findIndex(ratio => ratio[0] === from); - const toIdx = ratioScale.findIndex(ratio => ratio[0] === to); + const fromIdx = ratioScale.findIndex((ratio) => ratio[0] === from); + const toIdx = ratioScale.findIndex((ratio) => ratio[0] === to); let convertedValue = value; @@ -246,7 +246,7 @@ export function normalizeDate(amount: number, unit: Unit): { amount: number; uni const nextUnit = dateMath.unitsAsc[dateMath.unitsAsc.indexOf(unit) + 1]; const ratioScale = getRatioScale(unit, nextUnit); - const ratio = ratioScale.find(r => r[0] === unit)![1]; + const ratio = ratioScale.find((r) => r[0] === unit)![1]; const newAmount = amount / ratio; diff --git a/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx b/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx index 12770492697b6..3e1d437ae3f0e 100644 --- a/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx +++ b/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx @@ -44,7 +44,7 @@ export const mountHook = ( const hookValueCallback = jest.fn(); let component!: ReactWrapper; - const act: ReactHookWrapper['act'] = actor => { + const act: ReactHookWrapper['act'] = (actor) => { reactAct(() => { actor(getLastHookValue(), (args: Args) => component.setProps(args)); component.update(); @@ -63,7 +63,7 @@ export const mountHook = ( hookValueCallback(body(props)); return null; }; - const TestComponent: React.FunctionComponent = args => + const TestComponent: React.FunctionComponent = (args) => WrapperComponent ? ( diff --git a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts index e48b04743c811..bd4a78fc77d5e 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts @@ -81,7 +81,7 @@ export const createFailureResult = ( }); export const createFailureResultReducer = ( - convertErrorToString: (error: ErrorPayload) => string = error => `${error}` + convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` ) => ( state: LoadingResult, { params, error }: { params: Parameters; error: ErrorPayload } diff --git a/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts b/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts index 68fac1ef6c084..ce36848205cf5 100644 --- a/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts +++ b/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts @@ -11,7 +11,7 @@ export const mapKibanaQuickRangesToDatePickerRanges = ( timepickerQuickRanges: TimePickerQuickRange[] | undefined ): EuiSuperDatePickerCommonRange[] => timepickerQuickRanges - ? timepickerQuickRanges.map(r => ({ + ? timepickerQuickRanges.map((r) => ({ start: r.from, end: r.to, label: r.display, diff --git a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx index 4ca4aedb4a08b..1cff3663280fd 100644 --- a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx +++ b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx @@ -19,7 +19,7 @@ interface Props { triggersActionsUI: TriggersAndActionsUIPublicPluginSetup; } -export const TriggersActionsProvider: React.FC = props => { +export const TriggersActionsProvider: React.FC = (props) => { return ( { activeSpaceRT.decode(activeSpace), fold( () => 'default', - decodedActiveSpace => decodedActiveSpace.space.id + (decodedActiveSpace) => decodedActiveSpace.space.id ) ); }; diff --git a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts index e9a966b97e4dd..9951b62fa64a3 100644 --- a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts +++ b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts @@ -99,7 +99,7 @@ export const useTrackedPromise = ( const previousPendingPromises = pendingPromises.current; const cancelPreviousPendingPromises = () => { - previousPendingPromises.forEach(promise => promise.cancel()); + previousPendingPromises.forEach((promise) => promise.cancel()); }; const newPromise = createPromise(...args); @@ -123,8 +123,8 @@ export const useTrackedPromise = ( rejectCancellationPromise(new SilentCanceledPromiseError()); }, promise: newCancelablePromise.then( - value => { - setPromiseState(previousPromiseState => + (value) => { + setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { @@ -141,7 +141,7 @@ export const useTrackedPromise = ( // remove itself from the list of pending promises pendingPromises.current = pendingPromises.current.filter( - pendingPromise => pendingPromise.promise !== newPendingPromise.promise + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise ); if (onResolve) { @@ -150,9 +150,9 @@ export const useTrackedPromise = ( return value; }, - value => { + (value) => { if (!(value instanceof SilentCanceledPromiseError)) { - setPromiseState(previousPromiseState => + setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { @@ -170,7 +170,7 @@ export const useTrackedPromise = ( // remove itself from the list of pending promises pendingPromises.current = pendingPromises.current.filter( - pendingPromise => pendingPromise.promise !== newPendingPromise.promise + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise ); if (onReject) { @@ -201,7 +201,7 @@ export const useTrackedPromise = ( */ useEffect( () => () => { - pendingPromises.current.forEach(promise => promise.cancelSilently()); + pendingPromises.current.forEach((promise) => promise.cancelSilently()); }, [] ); diff --git a/x-pack/plugins/infra/public/utils/use_visibility_state.ts b/x-pack/plugins/infra/public/utils/use_visibility_state.ts index f4d8b572e4f7f..69068a630dbe5 100644 --- a/x-pack/plugins/infra/public/utils/use_visibility_state.ts +++ b/x-pack/plugins/infra/public/utils/use_visibility_state.ts @@ -11,7 +11,7 @@ export const useVisibilityState = (initialState: boolean) => { const hide = useCallback(() => setIsVisible(false), []); const show = useCallback(() => setIsVisible(true), []); - const toggle = useCallback(() => setIsVisible(state => !state), []); + const toggle = useCallback(() => setIsVisible((state) => !state), []); return useMemo( () => ({ diff --git a/x-pack/plugins/infra/server/graphql/sources/resolvers.ts b/x-pack/plugins/infra/server/graphql/sources/resolvers.ts index cffab4ba4f6f0..15c4a6677946d 100644 --- a/x-pack/plugins/infra/server/graphql/sources/resolvers.ts +++ b/x-pack/plugins/infra/server/graphql/sources/resolvers.ts @@ -191,10 +191,10 @@ const compactObject = (obj: T): CompactObject => const decodeLogColumns = (logColumns?: UpdateSourceLogColumnInput[] | null) => logColumns - ? logColumns.map(logColumn => + ? logColumns.map((logColumn) => pipe( SavedSourceConfigurationColumnRuntimeType.decode(logColumn), - fold(errors => { + fold((errors) => { throw new UserInputError(failure(errors).join('\n')); }, identity) ) diff --git a/x-pack/plugins/infra/server/kibana.index.ts b/x-pack/plugins/infra/server/kibana.index.ts index b4301b3edf367..e47f27117b309 100644 --- a/x-pack/plugins/infra/server/kibana.index.ts +++ b/x-pack/plugins/infra/server/kibana.index.ts @@ -19,9 +19,7 @@ export const getConfigSchema = (Joi: typeof JoiNamespace) => { fields: Joi.object({ container: Joi.string(), host: Joi.string(), - message: Joi.array() - .items(Joi.string()) - .single(), + message: Joi.array().items(Joi.string()).single(), pod: Joi.string(), tiebreaker: Joi.string(), timestamp: Joi.string(), diff --git a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts index 8119c06dedaef..8a9389ed585eb 100644 --- a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts @@ -23,7 +23,7 @@ export class FrameworkFieldsAdapter implements FieldsAdapter { const response = await indexPatternsService.getFieldsForWildcard({ pattern: indices, }); - return response.map(field => ({ + return response.map((field) => ({ ...field, displayable: true, })); diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index b8513541be7ae..939498305eb98 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -139,7 +139,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { date_range: { field: sourceConfiguration.fields.timestamp, format: TIMESTAMP_FORMAT, - ranges: bucketIntervalStarts.map(bucketIntervalStart => ({ + ranges: bucketIntervalStarts.map((bucketIntervalStart) => ({ from: bucketIntervalStart.getTime(), to: bucketIntervalStart.getTime() + bucketSize, })), @@ -183,7 +183,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { return pipe( LogSummaryResponseRuntimeType.decode(response), - map(logSummaryResponse => + map((logSummaryResponse) => logSummaryResponse.aggregations.count_by_date.buckets.map( convertDateRangeBucketToSummaryBucket ) @@ -227,7 +227,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { } function mapHitsToLogEntryDocuments(hits: SortedSearchHit[], fields: string[]): LogEntryDocument[] { - return hits.map(hit => { + return hits.map((hit) => { const logFields = fields.reduce<{ [fieldName: string]: JsonValue }>( (flattenedFields, field) => { if (has(hit._source, field)) { @@ -253,7 +253,7 @@ const convertDateRangeBucketToSummaryBucket = ( entriesCount: bucket.doc_count, start: bucket.from || 0, end: bucket.to || 0, - topEntryKeys: bucket.top_hits_by_key.hits.hits.map(hit => ({ + topEntryKeys: bucket.top_hits_by_key.hits.hits.map((hit) => ({ tiebreaker: hit.sort[1], time: hit.sort[0], })), diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts index 62f324e01f8d9..5718d49ae79d6 100644 --- a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts @@ -51,15 +51,15 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { ); } - const requests = options.metrics.map(metricId => + const requests = options.metrics.map((metricId) => this.makeTSVBRequest(metricId, options, nodeField, requestContext, rawRequest) ); return Promise.all(requests) - .then(results => { - return results.map(result => { + .then((results) => { + return results.map((result) => { const metricIds = Object.keys(result).filter( - k => !['type', 'uiRestrictions'].includes(k) + (k) => !['type', 'uiRestrictions'].includes(k) ); return metricIds.map((id: string) => { @@ -76,18 +76,18 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { const panel = result[id]; return { id, - series: panel.series.map(series => { + series: panel.series.map((series) => { return { id: series.id, label: series.label, - data: series.data.map(point => ({ timestamp: point[0], value: point[1] })), + data: series.data.map((point) => ({ timestamp: point[0], value: point[1] })), }; }), }; }); }); }) - .then(result => flatten(result)); + .then((result) => flatten(result)); } async makeTSVBRequest( diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 635f6ff9762c5..9bc58604f12a5 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -50,8 +50,8 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA terminate_after: 1, }) .then( - response => response._shards.total > 0, - err => { + (response) => response._shards.total > 0, + (err) => { if (err.status === 404) { return false; } diff --git a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts index 5ca65b667ae11..100260c499673 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts @@ -8,7 +8,7 @@ import { schema } from '@kbn/config-schema'; export const oneOfLiterals = (arrayOfLiterals: Readonly) => schema.string({ - validate: value => + validate: (value) => arrayOfLiterals.includes(value) ? undefined : `must be one of ${arrayOfLiterals.join(' | ')}`, }); diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index cc8a35f6e47a1..b36de2a3bd091 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -41,29 +41,29 @@ export const createInventoryMetricThresholdExecutor = ( ); const results = await Promise.all( - criteria.map(c => evaluateCondtion(c, nodeType, source.configuration, services, filterQuery)) + criteria.map((c) => evaluateCondtion(c, nodeType, source.configuration, services, filterQuery)) ); const invenotryItems = Object.keys(results[0]); for (const item of invenotryItems) { const alertInstance = services.alertInstanceFactory(`${alertId}-${item}`); // AND logic; all criteria must be across the threshold - const shouldAlertFire = results.every(result => result[item].shouldFire); + const shouldAlertFire = results.every((result) => result[item].shouldFire); // AND logic; because we need to evaluate all criteria, if one of them reports no data then the // whole alert is in a No Data/Error state - const isNoData = results.some(result => result[item].isNoData); - const isError = results.some(result => result[item].isError); + const isNoData = results.some((result) => result[item].isNoData); + const isError = results.some((result) => result[item].isError); if (shouldAlertFire) { alertInstance.scheduleActions(FIRED_ACTIONS.id, { group: item, item, - valueOf: mapToConditionsLookup(results, result => + valueOf: mapToConditionsLookup(results, (result) => formatMetric(result[item].metric, result[item].currentValue) ), - thresholdOf: mapToConditionsLookup(criteria, c => c.threshold), - metricOf: mapToConditionsLookup(criteria, c => c.metric), + thresholdOf: mapToConditionsLookup(criteria, (c) => c.threshold), + metricOf: mapToConditionsLookup(criteria, (c) => c.metric), }); } @@ -102,21 +102,18 @@ const evaluateCondtion = async ( metric, { to: Date.now(), - from: moment() - .subtract(condition.timeSize, condition.timeUnit) - .toDate() - .getTime(), + from: moment().subtract(condition.timeSize, condition.timeUnit).toDate().getTime(), interval: condition.timeUnit, }, sourceConfiguration, filterQuery ); - threshold = threshold.map(n => convertMetricValue(metric, n)); + threshold = threshold.map((n) => convertMetricValue(metric, n)); const comparisonFunction = comparatorMap[comparator]; - return mapValues(currentValues, value => ({ + return mapValues(currentValues, (value) => ({ shouldFire: value !== undefined && value !== null && comparisonFunction(value, threshold), metric, currentValue: value, @@ -196,8 +193,8 @@ const convertMetricValue = (metric: SnapshotMetricType, value: number) => { } }; const converters: Record number> = { - cpu: n => Number(n) / 100, - memory: n => Number(n) / 100, + cpu: (n) => Number(n) / 100, + memory: (n) => Number(n) / 100, }; const formatMetric = (metric: SnapshotMetricType, value: number) => { diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index cdec04ab81a8e..eedaf4202b37d 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -26,7 +26,7 @@ const checkValueAgainstComparatorMap: { }; export const createLogThresholdExecutor = (alertUUID: string, libs: InfraBackendLibs) => - async function({ services, params }: AlertExecutorOptions) { + async function ({ services, params }: AlertExecutorOptions) { const { count, criteria } = params as LogDocumentCountAlertParams; const { alertInstanceFactory, savedObjectsClient, callCluster } = services; const { sources } = libs; @@ -90,10 +90,10 @@ const getESQuery = ( const positiveComparators = getPositiveComparators(); const negativeComparators = getNegativeComparators(); - const positiveCriteria = criteria.filter(criterion => + const positiveCriteria = criteria.filter((criterion) => positiveComparators.includes(criterion.comparator) ); - const negativeCriteria = criteria.filter(criterion => + const negativeCriteria = criteria.filter((criterion) => negativeComparators.includes(criterion.comparator) ); // Positive assertions (things that "must" match) @@ -122,7 +122,7 @@ type Filter = { const buildFiltersForCriteria = (criteria: LogDocumentCountAlertParams['criteria']) => { let filters: Filter[] = []; - criteria.forEach(criterion => { + criteria.forEach((criterion) => { const criterionQuery = buildCriterionQuery(criterion); if (criterionQuery) { filters = [...filters, criterionQuery]; diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index 9738acd13eb6e..d1cb60112aa42 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -66,7 +66,7 @@ const getCurrentValueFromAggregations = ( const getParsedFilterQuery: ( filterQuery: string | undefined -) => Record | Array> = filterQuery => { +) => Record | Array> = (filterQuery) => { if (!filterQuery) return {}; return JSON.parse(filterQuery).bool; }; @@ -194,7 +194,7 @@ const getMetric: ( timefield: string, groupBy: string | undefined | string[], filterQuery: string | undefined -) => Promise> = async function( +) => Promise> = async function ( { callCluster }, params, index, @@ -212,10 +212,10 @@ const getMetric: ( ) => response.aggregations?.groupings?.buckets || []; const afterKeyHandler = createAfterKeyHandler( 'aggs.groupings.composite.after', - response => response.aggregations?.groupings?.after_key + (response) => response.aggregations?.groupings?.after_key ); const compositeBuckets = (await getAllCompositeData( - body => callCluster('search', { body, index }), + (body) => callCluster('search', { body, index }), searchBody, bucketSelector, afterKeyHandler @@ -224,7 +224,7 @@ const getMetric: ( (result, bucket) => ({ ...result, [Object.values(bucket.key) - .map(value => value) + .map((value) => value) .join(', ')]: getCurrentValueFromAggregations(bucket, aggType), }), {} @@ -254,7 +254,7 @@ const comparatorMap = { }; export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: string) => - async function({ services, params }: AlertExecutorOptions) { + async function ({ services, params }: AlertExecutorOptions) { const { criteria, groupBy, filterQuery, sourceId, alertOnNoData } = params as { criteria: MetricExpressionParams[]; groupBy: string | undefined | string[]; @@ -269,7 +269,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s ); const config = source.configuration; const alertResults = await Promise.all( - criteria.map(criterion => { + criteria.map((criterion) => { return (async () => { const currentValues = await getMetric( services, @@ -281,7 +281,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s ); const { threshold, comparator } = criterion; const comparisonFunction = comparatorMap[comparator]; - return mapValues(currentValues, value => ({ + return mapValues(currentValues, (value) => ({ ...criterion, metric: criterion.metric ?? DOCUMENT_COUNT_I18N, currentValue: value, @@ -300,11 +300,11 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s const alertInstance = services.alertInstanceFactory(`${alertId}-${group}`); // AND logic; all criteria must be across the threshold - const shouldAlertFire = alertResults.every(result => result[group].shouldFire); + const shouldAlertFire = alertResults.every((result) => result[group].shouldFire); // AND logic; because we need to evaluate all criteria, if one of them reports no data then the // whole alert is in a No Data/Error state - const isNoData = alertResults.some(result => result[group].isNoData); - const isError = alertResults.some(result => result[group].isError); + const isNoData = alertResults.some((result) => result[group].isNoData); + const isError = alertResults.some((result) => result[group].isError); const nextState = isError ? AlertStates.ERROR @@ -316,18 +316,18 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s let reason; if (nextState === AlertStates.ALERT) { - reason = alertResults.map(result => buildFiredAlertReason(result[group])).join('\n'); + reason = alertResults.map((result) => buildFiredAlertReason(result[group])).join('\n'); } if (alertOnNoData) { if (nextState === AlertStates.NO_DATA) { reason = alertResults - .filter(result => result[group].isNoData) - .map(result => buildNoDataAlertReason(result[group])) + .filter((result) => result[group].isNoData) + .map((result) => buildNoDataAlertReason(result[group])) .join('\n'); } else if (nextState === AlertStates.ERROR) { reason = alertResults - .filter(result => result[group].isError) - .map(result => buildErrorAlertReason(result[group].metric)) + .filter((result) => result[group].isError) + .map((result) => buildErrorAlertReason(result[group].metric)) .join('\n'); } } diff --git a/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts b/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts index 44d30d7281f20..ae74ed82038fd 100644 --- a/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts +++ b/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts @@ -16,7 +16,7 @@ const registerAlertTypes = (alertingPlugin: PluginSetupContract, libs: InfraBack alertingPlugin.registerType(registerMetricInventoryThresholdAlertType(libs)); const registerFns = [registerLogThresholdAlertType]; - registerFns.forEach(fn => { + registerFns.forEach((fn) => { fn(alertingPlugin, libs); }); } diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts index 15bfbce6d512e..9b3e31f4da87a 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -143,7 +143,7 @@ export class InfraLogEntriesDomain { params ); - const entries = documents.map(doc => { + const entries = documents.map((doc) => { return { id: doc.id, cursor: doc.cursor, @@ -218,7 +218,7 @@ export class InfraLogEntriesDomain { const requiredFields = getRequiredFields(configuration, messageFormattingRules); const summaries = await Promise.all( - highlightQueries.map(async highlightQueryPhrase => { + highlightQueries.map(async (highlightQueryPhrase) => { const highlightQuery = createHighlightQueryDsl(highlightQueryPhrase, requiredFields); const query = filterQuery ? { diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts index 58cffc7584979..b8cadaa06f61b 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts @@ -74,7 +74,7 @@ const compileExistsCondition = (condition: LogMessageFormattingCondition) => ? { conditionFields: condition.exists, fulfillsCondition: (fields: Fields) => - condition.exists.every(fieldName => fieldName in fields), + condition.exists.every((fieldName) => fieldName in fields), } : null; diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index f17d665e209ec..d0a6ae0fc9357 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -108,7 +108,7 @@ export class LogEntryCategoriesAnalysis { const topLogEntryCategoriesSpan = finalizeTopLogEntryCategoriesSpan(); return { - data: topLogEntryCategories.map(topCategory => ({ + data: topLogEntryCategories.map((topCategory) => ({ ...topCategory, regularExpression: logEntryCategoriesById[topCategory.categoryId]?._source.regex ?? '', histograms: categoryHistogramsById[topCategory.categoryId] ?? [], @@ -183,7 +183,9 @@ export class LogEntryCategoriesAnalysis { const logEntryDatasetsSpan = finalizeLogEntryDatasetsSpan(); return { - data: logEntryDatasetBuckets.map(logEntryDatasetBucket => logEntryDatasetBucket.key.dataset), + data: logEntryDatasetBuckets.map( + (logEntryDatasetBucket) => logEntryDatasetBucket.key.dataset + ), timing: { spans: [logEntryDatasetsSpan, ...esSearchSpans], }, @@ -297,7 +299,7 @@ export class LogEntryCategoriesAnalysis { } const topLogEntryCategories = topLogEntryCategoriesResponse.aggregations.terms_category_id.buckets.map( - topCategoryBucket => { + (topCategoryBucket) => { const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< Record >( @@ -312,7 +314,7 @@ export class LogEntryCategoriesAnalysis { categoryId: parseCategoryId(topCategoryBucket.key), logEntryCount: topCategoryBucket.filter_model_plot.sum_actual.value ?? 0, datasets: topCategoryBucket.filter_model_plot.terms_dataset.buckets - .map(datasetBucket => ({ + .map((datasetBucket) => ({ name: datasetBucket.key, maximumAnomalyScore: maximumAnomalyScoresByDataset[datasetBucket.key] ?? 0, })) @@ -403,7 +405,7 @@ export class LogEntryCategoriesAnalysis { ) ) .then(decodeOrThrow(logEntryCategoryHistogramsResponseRT)) - .then(response => ({ + .then((response) => ({ histogramId, histogramBuckets: response.aggregations.filters_categories.buckets, })) @@ -435,7 +437,7 @@ export class LogEntryCategoriesAnalysis { ...(innerAccumulatedHistograms[categoryId] ?? []), { histogramId, - buckets: categoryBucket.histogram_timestamp.buckets.map(bucket => ({ + buckets: categoryBucket.histogram_timestamp.buckets.map((bucket) => ({ bucketDuration: categoryBucket.histogram_timestamp.meta.bucketDuration, logEntryCount: bucket.sum_actual.value, startTime: bucket.key, @@ -518,7 +520,7 @@ export class LogEntryCategoriesAnalysis { const esSearchSpan = finalizeEsSearchSpan(); return { - examples: hits.map(hit => ({ + examples: hits.map((hit) => ({ dataset: hit._source.event?.dataset ?? '', message: hit._source.message ?? '', timestamp: hit.sort[0], diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts index f60f758053c47..28c1674841973 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts @@ -68,7 +68,7 @@ export class LogEntryRateAnalysis { const { after_key: afterKey, buckets: latestBatchBuckets } = pipe( logRateModelPlotResponseRT.decode(mlModelPlotResponse), - map(response => response.aggregations.timestamp_partition_buckets), + map((response) => response.aggregations.timestamp_partition_buckets), fold(throwErrors(createPlainError), identity) ); diff --git a/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts b/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts index c75ee6d644044..924d12bec0c5c 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts @@ -47,16 +47,16 @@ const aggregationsToModules = async ( const uniqueFields = Object.values(aggregations) .reduce>((fields, agg) => { if (SnapshotModelMetricAggRT.is(agg)) { - return uniq(fields.concat(Object.values(agg).map(a => a?.field))); + return uniq(fields.concat(Object.values(agg).map((a) => a?.field))); } return fields; }, []) - .filter(v => v) as string[]; + .filter((v) => v) as string[]; const fields = await Promise.all( uniqueFields.map( - async field => + async (field) => await getDatasetForField(client, field as string, options.sourceConfiguration.metricAlias) ) ); - return fields.filter(f => f) as string[]; + return fields.filter((f) => f) as string[]; }; diff --git a/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts b/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts index 82a393079745f..916c2795c0745 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts @@ -35,7 +35,7 @@ export const getFieldByNodeType = (options: InfraSnapshotRequestOptions) => { export const getGroupedNodesSources = (options: InfraSnapshotRequestOptions) => { const fields = findInventoryFields(options.nodeType, options.sourceConfiguration.fields); - const sources: GroupBySource[] = options.groupBy.map(gb => { + const sources: GroupBySource[] = options.groupBy.map((gb) => { return { [`${gb.field}`]: { terms: { field: gb.field } } }; }); sources.push({ diff --git a/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts b/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts index 12f284c363bd5..031eb881c91aa 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts @@ -90,7 +90,7 @@ export const getNodePath = ( options: InfraSnapshotRequestOptions ): SnapshotNodePath[] => { const node = groupBucket.key; - const path = options.groupBy.map(gb => { + const path = options.groupBy.map((gb) => { return { value: node[`${gb.field}`], label: node[`${gb.field}`] } as SnapshotNodePath; }); const ip = getIPFromBucket(options.nodeType, groupBucket); @@ -158,9 +158,9 @@ const getMetricValueFromBucket = (type: SnapshotMetricType, bucket: InfraSnapsho }; function calculateMax(buckets: InfraSnapshotMetricsBucket[], type: SnapshotMetricType) { - return max(buckets.map(bucket => getMetricValueFromBucket(type, bucket))) || 0; + return max(buckets.map((bucket) => getMetricValueFromBucket(type, bucket))) || 0; } function calculateAvg(buckets: InfraSnapshotMetricsBucket[], type: SnapshotMetricType) { - return sum(buckets.map(bucket => getMetricValueFromBucket(type, bucket))) / buckets.length || 0; + return sum(buckets.map((bucket) => getMetricValueFromBucket(type, bucket))) / buckets.length || 0; } diff --git a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts index 4057ed246ccaf..7dd1c3de5be5b 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts @@ -60,7 +60,7 @@ const bucketSelector = ( const handleAfterKey = createAfterKeyHandler( 'body.aggregations.nodes.composite.after', - input => input?.aggregations?.nodes?.after_key + (input) => input?.aggregations?.nodes?.after_key ); const callClusterFactory = (search: ESSearchClient) => (opts: any) => @@ -176,7 +176,7 @@ const mergeNodeBuckets = ( ): SnapshotNode[] => { const nodeMetricsForLookup = getNodeMetricsForLookup(nodeMetricsBuckets); - return nodeGroupByBuckets.map(node => { + return nodeGroupByBuckets.map((node) => { return { path: getNodePath(node, options), metric: getNodeMetrics(nodeMetricsForLookup[node.key.id], options), diff --git a/x-pack/plugins/infra/server/lib/sources/sources.ts b/x-pack/plugins/infra/server/lib/sources/sources.ts index 50f725cc6e099..65acc2b2756bd 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.ts @@ -42,7 +42,7 @@ export class InfraSources { ): Promise { const staticDefaultSourceConfiguration = await this.getStaticDefaultSourceConfiguration(); const savedSourceConfiguration = await this.getInternalSourceConfiguration(sourceId) - .then(internalSourceConfiguration => ({ + .then((internalSourceConfiguration) => ({ id: sourceId, version: undefined, updatedAt: undefined, @@ -52,9 +52,9 @@ export class InfraSources { internalSourceConfiguration ), })) - .catch(err => + .catch((err) => err instanceof NotFoundError - ? this.getSavedSourceConfiguration(savedObjectsClient, sourceId).then(result => ({ + ? this.getSavedSourceConfiguration(savedObjectsClient, sourceId).then((result) => ({ ...result, configuration: mergeSourceConfiguration( staticDefaultSourceConfiguration, @@ -63,7 +63,7 @@ export class InfraSources { })) : Promise.reject(err) ) - .catch(err => + .catch((err) => savedObjectsClient.errors.isNotFoundError(err) ? Promise.resolve({ id: sourceId, @@ -85,7 +85,7 @@ export class InfraSources { savedObjectsClient ); - return savedSourceConfigurations.map(savedSourceConfiguration => ({ + return savedSourceConfigurations.map((savedSourceConfiguration) => ({ ...savedSourceConfiguration, configuration: mergeSourceConfiguration( staticDefaultSourceConfiguration, @@ -242,14 +242,14 @@ const mergeSourceConfiguration = ( export const convertSavedObjectToSavedSourceConfiguration = (savedObject: unknown) => pipe( SourceConfigurationSavedObjectRuntimeType.decode(savedObject), - map(savedSourceConfiguration => ({ + map((savedSourceConfiguration) => ({ id: savedSourceConfiguration.id, version: savedSourceConfiguration.version, updatedAt: savedSourceConfiguration.updated_at, origin: 'stored' as 'stored', configuration: savedSourceConfiguration.attributes, })), - fold(errors => { + fold((errors) => { throw new Error(failure(errors).join('\n')); }, identity) ); diff --git a/x-pack/plugins/infra/server/plugin.ts b/x-pack/plugins/infra/server/plugin.ts index 496c2b32373a8..a265d53fc1bf8 100644 --- a/x-pack/plugins/infra/server/plugin.ts +++ b/x-pack/plugins/infra/server/plugin.ts @@ -89,8 +89,8 @@ export class InfraServerPlugin { } async setup(core: CoreSetup, plugins: InfraServerPluginDeps) { - await new Promise(resolve => { - this.config$.subscribe(configValue => { + await new Promise((resolve) => { + this.config$.subscribe((configValue) => { this.config = configValue; resolve(); }); diff --git a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts index dcac23d1a3d9d..b4288dae0c221 100644 --- a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts +++ b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts @@ -90,7 +90,7 @@ export const getCloudMetadata = async ( const accounts: InventoryCloudAccount[] = []; if (response.aggregations && response.aggregations.accounts) { - response.aggregations.accounts.buckets.forEach(b => { + response.aggregations.accounts.buckets.forEach((b) => { if (b.accountNames.buckets.length) { accounts.push({ value: b.key, @@ -102,7 +102,7 @@ export const getCloudMetadata = async ( } return { accounts, - projects: projectBuckets.map(b => b.key), - regions: regionBuckets.map(b => b.key), + projects: projectBuckets.map((b) => b.key), + regions: regionBuckets.map((b) => b.key), }; }; diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts index 6852a102afc86..d335774c85f38 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts @@ -60,7 +60,7 @@ export const initGetLogEntryCategoriesRoute = ({ endTime, categoryCount, datasets ?? [], - histograms.map(histogram => ({ + histograms.map((histogram) => ({ bucketCount: histogram.bucketCount, endTime: histogram.timeRange.endTime, id: histogram.id, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts index d772c000986fc..ba83f7e3f02fa 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts @@ -33,7 +33,7 @@ export const initValidateLogAnalysisDatasetsRoute = ({ } = request.body; const datasets = await Promise.all( - indices.map(async indexName => { + indices.map(async (indexName) => { const indexDatasets = await logEntries.getLogEntryDatasets( requestContext, timestampField, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts index 54ae0b4529daa..9b8219e514c13 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts @@ -40,10 +40,10 @@ export const initValidateLogAnalysisIndicesRoute = ({ framework }: InfraBackendL // Query each pattern individually, to map correctly the errors await Promise.all( - indices.map(async index => { + indices.map(async (index) => { const fieldCaps = await framework.callWithRequest(requestContext, 'fieldCaps', { allow_no_indices: true, - fields: fields.map(field => field.name), + fields: fields.map((field) => field.name), ignore_unavailable: true, index, }); @@ -68,7 +68,7 @@ export const initValidateLogAnalysisIndicesRoute = ({ framework }: InfraBackendL } else { const fieldTypes = Object.keys(fieldMetadata); - if (!fieldTypes.every(fieldType => validTypes.includes(fieldType))) { + if (!fieldTypes.every((fieldType) => validTypes.includes(fieldType))) { errors.push({ error: `FIELD_NOT_VALID`, index, diff --git a/x-pack/plugins/infra/server/routes/log_entries/highlights.ts b/x-pack/plugins/infra/server/routes/log_entries/highlights.ts index 9a61c8fa5aa9b..c95032f56987d 100644 --- a/x-pack/plugins/infra/server/routes/log_entries/highlights.ts +++ b/x-pack/plugins/infra/server/routes/log_entries/highlights.ts @@ -44,7 +44,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa if ('center' in payload) { entriesPerHighlightTerm = await Promise.all( - highlightTerms.map(highlightTerm => + highlightTerms.map((highlightTerm) => logEntries.getLogEntriesAround(requestContext, sourceId, { startTimestamp, endTimestamp, @@ -64,7 +64,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa } entriesPerHighlightTerm = await Promise.all( - highlightTerms.map(highlightTerm => + highlightTerms.map((highlightTerm) => logEntries.getLogEntries(requestContext, sourceId, { startTimestamp, endTimestamp, @@ -79,7 +79,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa return response.ok({ body: logEntriesHighlightsResponseRT.encode({ - data: entriesPerHighlightTerm.map(entries => ({ + data: entriesPerHighlightTerm.map((entries) => ({ entries, topCursor: entries[0].cursor, bottomCursor: entries[entries.length - 1].cursor, diff --git a/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts b/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts index d92cddcdc415d..20f572787e5a4 100644 --- a/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts +++ b/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts @@ -60,7 +60,7 @@ export const initLogEntriesSummaryHighlightsRoute = ({ return response.ok({ body: logEntriesSummaryHighlightsResponseRT.encode({ - data: bucketsPerHighlightTerm.map(buckets => ({ + data: bucketsPerHighlightTerm.map((buckets) => ({ start: startTimestamp, end: endTimestamp, buckets, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts index 54a1ca0aaa7e0..82427a833a20c 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts @@ -43,7 +43,7 @@ export const getCloudMetricsMetadata = async ( }, }, ], - should: CLOUD_METRICS_MODULES.map(module => ({ match: { 'event.module': module } })), + should: CLOUD_METRICS_MODULES.map((module) => ({ match: { 'event.module': module } })), }, }, size: 0, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts index 751e494164756..8a21a97631fbb 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts @@ -61,11 +61,11 @@ export const getNodeInfo = async ( }, }, }; - if (!CLOUD_METRICS_MODULES.some(m => startsWith(nodeType, m))) { + if (!CLOUD_METRICS_MODULES.some((m) => startsWith(nodeType, m))) { set( params, 'body.query.bool.must_not', - CLOUD_METRICS_MODULES.map(module => ({ match: { 'event.module': module } })) + CLOUD_METRICS_MODULES.map((module) => ({ match: { 'event.module': module } })) ); } const response = await framework.callWithRequest<{ _source: InfraMetadataInfo }, {}>( diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts b/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts index 8b6bb49d9f645..9076451b534ee 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts @@ -8,7 +8,7 @@ import { InfraMetadataAggregationBucket } from '../../../lib/adapters/framework' export const pickFeatureName = (buckets: InfraMetadataAggregationBucket[]): string[] => { if (buckets) { - const metadata = buckets.map(bucket => bucket.key); + const metadata = buckets.map((bucket) => bucket.key); return metadata; } else { return []; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts index a6510b2ba1478..f4f877c188d0d 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts @@ -60,7 +60,7 @@ export const getGroupings = async ( }, }, }, - ...groupBy.map(field => ({ exists: { field } })), + ...groupBy.map((field) => ({ exists: { field } })), ]; const params = { allowNoIndices: true, @@ -72,8 +72,8 @@ export const getGroupings = async ( bool: { should: [ ...options.metrics - .filter(m => m.field) - .map(m => ({ + .filter((m) => m.field) + .map((m) => ({ exists: { field: m.field }, })), ], @@ -83,7 +83,7 @@ export const getGroupings = async ( aggs: { groupingsCount: { cardinality: { - script: { source: groupBy.map(field => `doc['${field}'].value`).join('+') }, + script: { source: groupBy.map((field) => `doc['${field}'].value`).join('+') }, }, }, groupings: { @@ -136,7 +136,7 @@ export const getGroupings = async ( const { groupings, groupingsCount } = response.aggregations; const { after_key: afterKey } = groupings; return { - series: groupings.buckets.map(bucket => { + series: groupings.buckets.map((bucket) => { const keys = Object.values(bucket.key); const id = keys.join(' / '); return { id, keys, rows: [], columns: [] }; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts index ea77050112e19..ce4a9c71b74e6 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts @@ -48,7 +48,7 @@ export const populateSeriesWithTSVBData = ( const filters: JsonObject[] = isGroupBySet ? isArray(options.groupBy) ? options.groupBy - .filter(f => f) + .filter((f) => f) .map((field, index) => ({ match: { [field as string]: series.keys?.[index] || '' } })) : [{ match: { [options.groupBy as string]: series.id } }] : []; @@ -76,8 +76,8 @@ export const populateSeriesWithTSVBData = ( // Create the TSVB model based on the request options const model = createMetricModel(options); const modules = await Promise.all( - uniq(options.metrics.filter(m => m.field)).map( - async m => await getDatasetForField(client, m.field as string, options.indexPattern) + uniq(options.metrics.filter((m) => m.field)).map( + async (m) => await getDatasetForField(client, m.field as string, options.indexPattern) ) ); @@ -88,7 +88,7 @@ export const populateSeriesWithTSVBData = ( timestampField: options.timerange.field, timerange: options.timerange, }, - modules.filter(m => m) as string[] + modules.filter((m) => m) as string[] ); if (calculatedInterval) { @@ -133,15 +133,15 @@ export const populateSeriesWithTSVBData = ( (currentTimestamps, tsvbSeries) => union( currentTimestamps, - tsvbSeries.data.map(row => row[0]) + tsvbSeries.data.map((row) => row[0]) ).sort(), [] as number[] ); // Combine the TSVB series for multiple metrics. - const rows = timestamps.map(timestamp => { + const rows = timestamps.map((timestamp) => { return tsvbResults.custom.series.reduce( (currentRow, tsvbSeries) => { - const matches = tsvbSeries.data.find(d => d[0] === timestamp); + const matches = tsvbSeries.data.find((d) => d[0] === timestamp); if (matches) { return { ...currentRow, [tsvbSeries.id]: matches[1] }; } diff --git a/x-pack/plugins/infra/server/usage/usage_collector.ts b/x-pack/plugins/infra/server/usage/usage_collector.ts index 26578bfd2b794..7be7364c331fa 100644 --- a/x-pack/plugins/infra/server/usage/usage_collector.ts +++ b/x-pack/plugins/infra/server/usage/usage_collector.ts @@ -79,7 +79,7 @@ export class UsageCollector { // only keep the newest BUCKET_NUMBER buckets const cutoff = this.getBucket() - this.BUCKET_SIZE * (this.BUCKET_NUMBER - 1); - keys.forEach(key => { + keys.forEach((key) => { if (parseInt(key, 10) < cutoff) { delete this.counters[key]; } diff --git a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts index 43e109b009f48..a3d674b324ae8 100644 --- a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts +++ b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts @@ -80,7 +80,7 @@ export const calculateMetricInterval = async ( return; } - const intervals = resp.aggregations.modules.buckets.map(a => a.period.value).filter(v => !!v); + const intervals = resp.aggregations.modules.buckets.map((a) => a.period.value).filter((v) => !!v); if (!intervals.length) { return; } diff --git a/x-pack/plugins/ingest_manager/common/services/agent_status.ts b/x-pack/plugins/ingest_manager/common/services/agent_status.ts index d12f1001d1ece..cc1c2da710516 100644 --- a/x-pack/plugins/ingest_manager/common/services/agent_status.ts +++ b/x-pack/plugins/ingest_manager/common/services/agent_status.ts @@ -42,23 +42,23 @@ export function getAgentStatus(agent: Agent, now: number = Date.now()): AgentSta } export function buildKueryForOnlineAgents() { - return `(${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(4 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_EPHEMERAL} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s)`; + return `(${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (4 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_EPHEMERAL} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s)`; } export function buildKueryForOfflineAgents() { - return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s`; + return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s`; } export function buildKueryForErrorAgents() { - return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${(4 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s`; + return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${ + (4 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s`; } diff --git a/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts b/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts index 620b663451ea3..2a8b687675bf9 100644 --- a/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts +++ b/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts @@ -18,8 +18,8 @@ export const storedDatasourceToAgentDatasource = ( enabled, use_output: DEFAULT_OUTPUT.name, // TODO: hardcoded to default output for now inputs: inputs - .filter(input => input.enabled) - .map(input => { + .filter((input) => input.enabled) + .map((input) => { const fullInput = { ...input, ...Object.entries(input.config || {}).reduce((acc, [key, { value }]) => { @@ -27,8 +27,8 @@ export const storedDatasourceToAgentDatasource = ( return acc; }, {} as { [k: string]: any }), streams: input.streams - .filter(stream => stream.enabled) - .map(stream => { + .filter((stream) => stream.enabled) + .map((stream) => { const fullStream = { ...stream, ...stream.agent_stream, diff --git a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts b/x-pack/plugins/ingest_manager/common/services/package_to_config.ts index e7a912ddf1741..dc0f73b47c599 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_to_config.ts @@ -28,7 +28,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas // Create datasource input property if (packageDatasource?.inputs?.length) { // Map each package datasource input to agent config datasource input - packageDatasource.inputs.forEach(packageInput => { + packageDatasource.inputs.forEach((packageInput) => { // Reduces registry var def into config object entry const varsReducer = ( configObject: DatasourceConfigRecord, @@ -46,7 +46,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas // Map each package input stream into datasource input stream const streams: DatasourceInputStream[] = packageInput.streams - ? packageInput.streams.map(packageStream => { + ? packageInput.streams.map((packageStream) => { const stream: DatasourceInputStream = { id: `${packageInput.type}-${packageStream.dataset}`, enabled: packageStream.enabled === false ? false : true, @@ -61,7 +61,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas const input: DatasourceInput = { type: packageInput.type, - enabled: streams.length ? !!streams.find(stream => stream.enabled) : true, + enabled: streams.length ? !!streams.find((stream) => stream.enabled) : true, streams, }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx index 5a06a9a879441..2b80ab9f0068e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx @@ -9,12 +9,12 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiText, EuiLink } from '@elastic/eui'; import { AlphaFlyout } from './alpha_flyout'; -const Message = styled(EuiText).attrs(props => ({ +const Message = styled(EuiText).attrs((props) => ({ color: 'subdued', textAlign: 'center', size: 's', }))` - padding: ${props => props.theme.eui.paddingSizes.m}; + padding: ${(props) => props.theme.eui.paddingSizes.m}; `; export const AlphaMessaging: React.FC<{}> = () => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx index 5d2938f3e9fa0..78f4f73cf18be 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx @@ -42,7 +42,7 @@ export const ManualInstructions: React.FunctionComponent = ({ - {copy => ( + {(copy) => ( props.theme.eui.euiBorderThin}; - background-color: ${props => props.theme.eui.euiPageBackgroundColor}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + background-color: ${(props) => props.theme.eui.euiPageBackgroundColor}; `; const Wrapper = styled.div<{ maxWidth?: number }>` - max-width: ${props => props.maxWidth || 1200}px; + max-width: ${(props) => props.maxWidth || 1200}px; margin-left: auto; margin-right: auto; - padding-top: ${props => props.theme.eui.paddingSizes.xl}; - padding-left: ${props => props.theme.eui.paddingSizes.m}; - padding-right: ${props => props.theme.eui.paddingSizes.m}; + padding-top: ${(props) => props.theme.eui.paddingSizes.xl}; + padding-left: ${(props) => props.theme.eui.paddingSizes.m}; + padding-right: ${(props) => props.theme.eui.paddingSizes.m}; `; const Tabs = styled(EuiTabs)` @@ -66,7 +66,7 @@ export const Header: React.FC = ({ - {tabs.map(props => ( + {tabs.map((props) => ( {props.name} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx index de0dd75f635cf..7c32dfe39a0b4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx @@ -7,8 +7,9 @@ import React from 'react'; import { EuiIcon, EuiIconProps } from '@elastic/eui'; import { usePackageIconType, UsePackageIconType } from '../hooks'; -export const PackageIcon: React.FunctionComponent> = ({ packageName, version, icons, tryApi, ...euiIconProps }) => { +export const PackageIcon: React.FunctionComponent< + UsePackageIconType & Omit +> = ({ packageName, version, icons, tryApi, ...euiIconProps }) => { const iconType = usePackageIconType({ packageName, version, icons, tryApi }); return ; }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx index 579a59cb909c6..9069cc0f73806 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx @@ -67,7 +67,7 @@ export const SearchBar: React.FunctionComponent = ({ } onInputChange={onChangeSearch} onItemClick={onAutocompleteClick} - suggestions={suggestions.map(suggestion => { + suggestions={suggestions.map((suggestion) => { return { ...suggestion, // For type @@ -124,7 +124,7 @@ function useSuggestions(fieldPrefix: string, search: string) { selectionEnd: query.length, }) ) - .filter(suggestion => { + .filter((suggestion) => { if (suggestion.type === 'conjunction') { return true; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx index 9863463e68a01..cbd0b056eaaf1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx @@ -110,7 +110,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { }, ]} idSelected={'enabled'} - onChange={id => {}} + onChange={(id) => {}} legend={{ children: ( @@ -149,7 +149,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { }, ]} idSelected={'enabled'} - onChange={id => {}} + onChange={(id) => {}} legend={{ children: ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx index 207c757fd5b16..0c858cd2b305d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx @@ -215,13 +215,13 @@ const breadcrumbGetters: { export function useBreadcrumbs(page: Page, values: DynamicPagePathValues = {}) { const { chrome, http } = useCore(); - const breadcrumbs: ChromeBreadcrumb[] = breadcrumbGetters[page](values).map(breadcrumb => ({ + const breadcrumbs: ChromeBreadcrumb[] = breadcrumbGetters[page](values).map((breadcrumb) => ({ ...breadcrumb, href: breadcrumb.href ? http.basePath.prepend(`${BASE_PATH}#${breadcrumb.href}`) : undefined, })); const docTitle: string[] = [...breadcrumbs] .reverse() - .map(breadcrumb => breadcrumb.text as string); + .map((breadcrumb) => breadcrumb.text as string); chrome.docTitle.change(docTitle); chrome.setBreadcrumbs(breadcrumbs); } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx index ef40c171b9ca3..8290dfb8691cf 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx @@ -31,20 +31,20 @@ export const FleetStatusProvider: React.FC = ({ children }) => { }); async function sendGetStatus() { try { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); const res = await sendGetFleetStatus(); if (res.error) { throw res.error; } - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, isReady: res.data?.isReady ?? false, missingRequirements: res.data?.missing_requirements, })); } catch (error) { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); } } useEffect(() => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts index c535dc899638d..630adaefa7424 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts @@ -34,7 +34,7 @@ export function useComboInput(defaultValue = []) { setValue([...value, newVal]); }, onChange: (newVals: any[]) => { - setValue(newVals.map(val => val.label)); + setValue(newVals.map((val) => val.label)); }, }, value, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts index 5f231b5cc9ec9..011e0c69f2683 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts @@ -39,7 +39,9 @@ export const usePackageIconType = ({ setIconType(CACHED_ICONS.get(pkgKey) || ''); return; } - const svgIcons = (paramIcons || iconList)?.filter(iconDef => iconDef.type === 'image/svg+xml'); + const svgIcons = (paramIcons || iconList)?.filter( + (iconDef) => iconDef.type === 'image/svg+xml' + ); const localIconSrc = Array.isArray(svgIcons) && svgIcons[0]?.src; if (localIconSrc) { CACHED_ICONS.set(pkgKey, toImage(localIconSrc)); @@ -47,7 +49,7 @@ export const usePackageIconType = ({ return; } - const euiLogoIcon = ICON_TYPES.find(key => key.toLowerCase() === `logo${packageName}`); + const euiLogoIcon = ICON_TYPES.find((key) => key.toLowerCase() === `logo${packageName}`); if (euiLogoIcon) { CACHED_ICONS.set(pkgKey, euiLogoIcon); setIconType(euiLogoIcon); @@ -56,8 +58,8 @@ export const usePackageIconType = ({ if (tryApi && !paramIcons && !iconList) { sendGetPackageInfoByKey(pkgKey) - .catch(error => undefined) // Ignore API errors - .then(res => { + .catch((error) => undefined) // Ignore API errors + .then((res) => { CACHED_ICONS.delete(pkgKey); setIconList(res?.data?.response?.icons); }); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx index fbe7c736e2df4..72b12260a1a12 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx @@ -18,14 +18,14 @@ interface Props { } const Container = styled.div` - min-height: calc(100vh - ${props => props.theme.eui.euiHeaderChildSize}); - background: ${props => props.theme.eui.euiColorEmptyShade}; + min-height: calc(100vh - ${(props) => props.theme.eui.euiHeaderChildSize}); + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; const Nav = styled.nav` - background: ${props => props.theme.eui.euiColorEmptyShade}; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding: ${props => + background: ${(props) => props.theme.eui.euiColorEmptyShade}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding: ${(props) => `${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL} ${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL}`}; .euiTabs { padding-left: 3px; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx index d5ce5e17ad84e..ac7f85bf5f594 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx @@ -9,7 +9,7 @@ import { EuiPage, EuiPageBody, EuiSpacer } from '@elastic/eui'; import { Header, HeaderProps } from '../components'; const Page = styled(EuiPage)` - background: ${props => props.theme.eui.euiColorEmptyShade}; + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; interface Props extends HeaderProps { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx index cad98c5a0a7e1..08f6244242a3d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx @@ -8,7 +8,7 @@ import styled from 'styled-components'; import { EuiPage, EuiPageBody, EuiSpacer } from '@elastic/eui'; const Page = styled(EuiPage)` - background: ${props => props.theme.eui.euiColorEmptyShade}; + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; interface Props { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx index c55d6009074b0..30996931ba67a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx @@ -32,7 +32,7 @@ interface ValidationResults { const StyledEuiAccordion = styled(EuiAccordion)` .ingest-active-button { - color: ${props => props.theme.eui.euiColorPrimary}; + color: ${(props) => props.theme.eui.euiColorPrimary}; } `; @@ -143,7 +143,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ updateAgentConfig({ [name]: e.target.value })} + onChange={(e) => updateAgentConfig({ [name]: e.target.value })} isInvalid={Boolean(touchedFields[name] && validation[name])} onBlur={() => setTouchedFields({ ...touchedFields, [name]: true })} placeholder={placeholder} @@ -202,7 +202,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ onCreateOption={(value: string) => { updateAgentConfig({ namespace: value }); }} - onChange={selectedOptions => { + onChange={(selectedOptions) => { updateAgentConfig({ namespace: (selectedOptions.length ? selectedOptions[0] : '') as string, }); @@ -254,7 +254,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ }, { logs: false, metrics: false } )} - onChange={id => { + onChange={(id) => { if (id !== 'logs' && id !== 'metrics') { return; } @@ -265,7 +265,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ const previousValues = agentConfig.monitoring_enabled || []; updateAgentConfig({ monitoring_enabled: hasLogs - ? previousValues.filter(type => type !== id) + ? previousValues.filter((type) => type !== id) : [...previousValues, id], }); }} @@ -289,7 +289,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ /> - {deleteAgentConfigPrompt => { + {(deleteAgentConfigPrompt) => { return ( props.theme.eui.textColors.danger}; + color: ${(props) => props.theme.eui.textColors.danger}; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx index df679d33e0324..86186f7f0a6dd 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx @@ -89,8 +89,8 @@ export const DatasourceDeleteProvider: React.FunctionComponent = ({ try { const { data } = await sendDeleteDatasource({ datasourceIds: datasources }); - const successfulResults = data?.filter(result => result.success) || []; - const failedResults = data?.filter(result => !result.success) || []; + const successfulResults = data?.filter((result) => result.success) || []; + const failedResults = data?.filter((result) => !result.success) || []; if (successfulResults.length) { const hasMultipleSuccesses = successfulResults.length > 1; @@ -133,7 +133,7 @@ export const DatasourceDeleteProvider: React.FunctionComponent = ({ } if (onSuccessCallback.current) { - onSuccessCallback.current(successfulResults.map(result => result.id)); + onSuccessCallback.current(successfulResults.map((result) => result.id)); } } catch (e) { notifications.toasts.addDanger( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx index 36e987d007679..6eed7e74d6bc6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx @@ -42,7 +42,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{ const advancedVars: RegistryVarsEntry[] = []; if (packageInputVars) { - packageInputVars.forEach(varDef => { + packageInputVars.forEach((varDef) => { if (isAdvancedVar(varDef)) { advancedVars.push(varDef); } else { @@ -95,7 +95,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{ - {requiredVars.map(varDef => { + {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInput.vars![varName].value; return ( @@ -139,7 +139,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{
          {isShowingAdvanced - ? advancedVars.map(varDef => { + ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInput.vars![varName].value; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx index 586fc6b1d4138..db704d8b1d0f3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx @@ -25,8 +25,8 @@ import { DatasourceInputConfig } from './datasource_input_config'; import { DatasourceInputStreamConfig } from './datasource_input_stream_config'; const FlushHorizontalRule = styled(EuiHorizontalRule)` - margin-left: -${props => props.theme.eui.paddingSizes.m}; - margin-right: -${props => props.theme.eui.paddingSizes.m}; + margin-left: -${(props) => props.theme.eui.paddingSizes.m}; + margin-right: -${(props) => props.theme.eui.paddingSizes.m}; width: auto; `; @@ -84,11 +84,11 @@ export const DatasourceInputPanel: React.FunctionComponent<{
          } checked={datasourceInput.enabled} - onChange={e => { + onChange={(e) => { const enabled = e.target.checked; updateDatasourceInput({ enabled, - streams: datasourceInput.streams.map(stream => ({ + streams: datasourceInput.streams.map((stream) => ({ ...stream, enabled, })), @@ -107,7 +107,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ count: ( - {datasourceInput.streams.filter(stream => stream.enabled).length} + {datasourceInput.streams.filter((stream) => stream.enabled).length} ), @@ -168,9 +168,9 @@ export const DatasourceInputPanel: React.FunctionComponent<{ {/* Per-stream configuration */} {isShowingStreams ? ( - {packageInput.streams.map(packageInputStream => { + {packageInput.streams.map((packageInputStream) => { const datasourceInputStream = datasourceInput.streams.find( - stream => stream.dataset === packageInputStream.dataset + (stream) => stream.dataset === packageInputStream.dataset ); return datasourceInputStream ? ( @@ -179,7 +179,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ datasourceInputStream={datasourceInputStream} updateDatasourceInputStream={(updatedStream: Partial) => { const indexOfUpdatedStream = datasourceInput.streams.findIndex( - stream => stream.dataset === packageInputStream.dataset + (stream) => stream.dataset === packageInputStream.dataset ); const newStreams = [...datasourceInput.streams]; newStreams[indexOfUpdatedStream] = { @@ -196,7 +196,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ updatedInput.enabled = true; } else if ( datasourceInput.enabled && - !newStreams.find(stream => stream.enabled) + !newStreams.find((stream) => stream.enabled) ) { updatedInput.enabled = false; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx index 7e32936a6fffa..978ad83cd5c3c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx @@ -43,7 +43,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ const advancedVars: RegistryVarsEntry[] = []; if (packageInputStream.vars && packageInputStream.vars.length) { - packageInputStream.vars.forEach(varDef => { + packageInputStream.vars.forEach((varDef) => { if (isAdvancedVar(varDef)) { advancedVars.push(varDef); } else { @@ -81,7 +81,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ } checked={datasourceInputStream.enabled} - onChange={e => { + onChange={(e) => { const enabled = e.target.checked; updateDatasourceInputStream({ enabled, @@ -99,7 +99,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ - {requiredVars.map(varDef => { + {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInputStream.vars![varName].value; return ( @@ -143,7 +143,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{
          {isShowingAdvanced - ? advancedVars.map(varDef => { + ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInputStream.vars![varName].value; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx index 846a807f9240d..f5f21f685f180 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx @@ -35,7 +35,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ onChange([...value, newVal]); }} onChange={(newVals: any[]) => { - onChange(newVals.map(val => val.label)); + onChange(newVals.map((val) => val.label)); }} onBlur={() => setIsDirty(true)} /> @@ -54,7 +54,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ showGutter: false, }} value={value} - onChange={newVal => onChange(newVal)} + onChange={(newVal) => onChange(newVal)} onBlur={() => setIsDirty(true)} /> ); @@ -63,7 +63,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} onBlur={() => setIsDirty(true)} /> ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts index b970a7d222001..992ace3530f40 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts @@ -314,18 +314,18 @@ describe('Ingest Manager - validateDatasource()', () => { }); it('returns no errors for disabled inputs', () => { - const disabledInputs = invalidDatasource.inputs.map(input => ({ ...input, enabled: false })); + const disabledInputs = invalidDatasource.inputs.map((input) => ({ ...input, enabled: false })); expect(validateDatasource({ ...validDatasource, inputs: disabledInputs }, mockPackage)).toEqual( noErrorsValidationResults ); }); it('returns only datasource and input-level errors for disabled streams', () => { - const inputsWithDisabledStreams = invalidDatasource.inputs.map(input => + const inputsWithDisabledStreams = invalidDatasource.inputs.map((input) => input.streams ? { ...input, - streams: input.streams.map(stream => ({ ...stream, enabled: false })), + streams: input.streams.map((stream) => ({ ...stream, enabled: false })), } : input ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts index 3a712b072dac1..61273e1fb3db9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts @@ -76,7 +76,7 @@ export const validateDatasource = ( }, {} as Record); // Validate each datasource input with either its own config fields or streams - datasource.inputs.forEach(input => { + datasource.inputs.forEach((input) => { if (!input.vars && !input.streams) { return; } @@ -109,7 +109,7 @@ export const validateDatasource = ( // Validate each input stream with config fields if (input.streams.length) { - input.streams.forEach(stream => { + input.streams.forEach((stream) => { if (!stream.vars) { return; } @@ -121,7 +121,7 @@ export const validateDatasource = ( const streamVarsByName = ( ( registryInputsByType[input.type].streams.find( - registryStream => registryStream.dataset === stream.dataset + (registryStream) => registryStream.dataset === stream.dataset ) || {} ).vars || [] ).reduce((vars, registryVar) => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx index 118c7e30f13f4..58a98f86de426 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx @@ -37,8 +37,10 @@ export const StepConfigureDatasource: React.FunctionComponent<{ packageInfo.datasources[0].inputs && packageInfo.datasources[0].inputs.length ? ( - {packageInfo.datasources[0].inputs.map(packageInput => { - const datasourceInput = datasource.inputs.find(input => input.type === packageInput.type); + {packageInfo.datasources[0].inputs.map((packageInput) => { + const datasourceInput = datasource.inputs.find( + (input) => input.type === packageInput.type + ); return datasourceInput ? ( ) => { const indexOfUpdatedInput = datasource.inputs.findIndex( - input => input.type === packageInput.type + (input) => input.type === packageInput.type ); const newInputs = [...datasource.inputs]; newInputs[indexOfUpdatedInput] = { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx index c4d602c2c2081..3b22756409330 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx @@ -41,8 +41,8 @@ export const StepDefineDatasource: React.FunctionComponent<{ // Existing datasources on the agent config using the package name, retrieve highest number appended to datasource name const dsPackageNamePattern = new RegExp(`${packageInfo.name}-(\\d+)`); const dsWithMatchingNames = (agentConfig.datasources as Datasource[]) - .filter(ds => Boolean(ds.name.match(dsPackageNamePattern))) - .map(ds => parseInt(ds.name.match(dsPackageNamePattern)![1], 10)) + .filter((ds) => Boolean(ds.name.match(dsPackageNamePattern))) + .map((ds) => parseInt(ds.name.match(dsPackageNamePattern)![1], 10)) .sort(); updateDatasource({ @@ -83,7 +83,7 @@ export const StepDefineDatasource: React.FunctionComponent<{ > + onChange={(e) => updateDatasource({ name: e.target.value, }) @@ -112,7 +112,7 @@ export const StepDefineDatasource: React.FunctionComponent<{ > + onChange={(e) => updateDatasource({ description: e.target.value, }) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx index 6cbe56e628903..22cb219f911f6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx @@ -115,7 +115,7 @@ export const StepSelectConfig: React.FunctionComponent<{ checked: selectedConfigId === id ? 'on' : undefined, }; })} - renderOption={option => ( + renderOption={(option) => ( {option.label} @@ -148,8 +148,8 @@ export const StepSelectConfig: React.FunctionComponent<{ ), }} height={240} - onChange={options => { - const selectedOption = options.find(option => option.checked === 'on'); + onChange={(options) => { + const selectedOption = options.find((option) => option.checked === 'on'); if (selectedOption) { setSelectedConfigId(selectedOption.key); } else { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx index 8dabb3bc98110..12f5bf9eec1d0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx @@ -131,8 +131,8 @@ export const StepSelectPackage: React.FunctionComponent<{ ), }} height={240} - onChange={options => { - const selectedOption = options.find(option => option.checked === 'on'); + onChange={(options) => { + const selectedOption = options.find((option) => option.checked === 'on'); if (selectedOption) { setSelectedPkgKey(selectedOption.key); } else { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx index 3ad862c5e43fd..316b7eed491b9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx @@ -67,7 +67,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ ] => { const namespacesValues: string[] = []; const inputTypesValues: string[] = []; - const mappedDatasources = originalDatasources.map(datasource => { + const mappedDatasources = originalDatasources.map((datasource) => { if (datasource.namespace && !namespacesValues.includes(datasource.namespace)) { namespacesValues.push(datasource.namespace); } @@ -84,7 +84,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ streamSummary.total += input.streams.length; streamSummary.enabled += input.enabled - ? input.streams.filter(stream => stream.enabled).length + ? input.streams.filter((stream) => stream.enabled).length : 0; return streamSummary; @@ -233,7 +233,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ // /> // , - {deleteDatasourcePrompt => { + {(deleteDatasourcePrompt) => { return ( ( agentConfig={agentConfig} updateAgentConfig={updateAgentConfig} withSysMonitoring={withSysMonitoring} - updateSysMonitoring={newValue => setWithSysMonitoring(newValue)} + updateSysMonitoring={(newValue) => setWithSysMonitoring(newValue)} validation={validation} isEditing={true} onDelete={() => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx index f80b981b69d3b..3f886645b5339 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx @@ -35,7 +35,7 @@ import { ConfigSettingsView } from './components/settings'; const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; `; export const AgentConfigDetailsPage: React.FunctionComponent = () => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx index 92be20a2761e2..7be955bc9f4f3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx @@ -105,11 +105,11 @@ export const EditDatasourcePage: React.FunctionComponent = () => { // Remove `agent_stream` from all stream info, we assign this after saving const newDatasource = { ...restOfDatasource, - inputs: inputs.map(input => { + inputs: inputs.map((input) => { const { streams, ...restOfInput } = input; return { ...restOfInput, - streams: streams.map(stream => { + streams: streams.map((stream) => { const { agent_stream, ...restOfStream } = stream; return restOfStream; }), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx index 9f582e7e2fbe6..349ebe1151c80 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx @@ -76,7 +76,7 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClos agentConfig={agentConfig} updateAgentConfig={updateAgentConfig} withSysMonitoring={withSysMonitoring} - updateSysMonitoring={newValue => setWithSysMonitoring(newValue)} + updateSysMonitoring={(newValue) => setWithSysMonitoring(newValue)} validation={validation} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx index ff3124d574857..5b4066e53f0c8 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx @@ -249,7 +249,7 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { // If Fleet is not enabled, then remove the `agents` column if (!isFleetEnabled) { - return cols.filter(col => ('field' in col ? col.field !== 'agents' : true)); + return cols.filter((col) => ('field' in col ? col.field !== 'agents' : true)); } return cols; @@ -303,7 +303,7 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx index ac47387cd7ab3..b87ae4c4561ff 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx @@ -68,7 +68,7 @@ export const DataStreamRowActions = memo<{ datastream: DataStream }>(({ datastre panels.push({ id: 1, title: panelTitle, - items: dashboards.map(dashboard => { + items: dashboards.map((dashboard) => { return { icon: 'dashboardApp', href: useKibanaLink(`/dashboard/${dashboard.id || ''}`), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx index 09873a3cdaa87..e1583d2e426bc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx @@ -194,7 +194,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { }; if (dataStreamsData && dataStreamsData.data_streams.length) { - dataStreamsData.data_streams.forEach(stream => { + dataStreamsData.data_streams.forEach((stream) => { const { dataset, type, namespace, package: pkg } = stream; if (!filterOptions.dataset.includes(dataset)) { filterOptions.dataset.push(dataset); @@ -270,7 +270,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Dataset', }), multiSelect: 'or', - options: filterOptions.dataset.map(option => ({ + options: filterOptions.dataset.map((option) => ({ value: option, name: option, })), @@ -282,7 +282,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Type', }), multiSelect: 'or', - options: filterOptions.type.map(option => ({ + options: filterOptions.type.map((option) => ({ value: option, name: option, })), @@ -294,7 +294,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Namespace', }), multiSelect: 'or', - options: filterOptions.namespace.map(option => ({ + options: filterOptions.namespace.map((option) => ({ value: option, name: option, })), @@ -306,7 +306,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Integration', }), multiSelect: 'or', - options: filterOptions.package.map(option => ({ + options: filterOptions.package.map((option) => ({ value: option, name: option, })), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx index 219896dd27ef7..ac74b09ab4391 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx @@ -32,11 +32,11 @@ import { export function AssetsFacetGroup({ assets }: { assets: AssetsGroupedByServiceByType }) { const FirstHeaderRow = styled(EuiFlexGroup)` - padding: 0 0 ${props => props.theme.eui.paddingSizes.m} 0; + padding: 0 0 ${(props) => props.theme.eui.paddingSizes.m} 0; `; const HeaderRow = styled(EuiFlexGroup)` - padding: ${props => props.theme.eui.paddingSizes.m} 0; + padding: ${(props) => props.theme.eui.paddingSizes.m} 0; `; const FacetGroup = styled(EuiFacetGroup)` @@ -78,7 +78,7 @@ export function AssetsFacetGroup({ assets }: { assets: AssetsGroupedByServiceByT const iconType = type in AssetIcons && AssetIcons[type]; const iconNode = iconType ? : ''; const FacetButton = styled(EuiFacetButton)` - padding: '${props => props.theme.eui.paddingSizes.xs} 0'; + padding: '${(props) => props.theme.eui.paddingSizes.xs} 0'; height: 'unset'; `; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx index 684b158b5da86..7e4337f59d650 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx @@ -15,11 +15,11 @@ export function IconPanel({ iconType }: { iconType: IconType }) { position: absolute; text-align: center; vertical-align: middle; - padding: ${props => props.theme.eui.spacerSizes.xl}; + padding: ${(props) => props.theme.eui.spacerSizes.xl}; svg, img { - height: ${props => props.theme.eui.euiKeyPadMenuSize}; - width: ${props => props.theme.eui.euiKeyPadMenuSize}; + height: ${(props) => props.theme.eui.euiKeyPadMenuSize}; + width: ${(props) => props.theme.eui.euiKeyPadMenuSize}; } } `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx index 64223efefaab8..acdcd5b9a3406 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx @@ -8,7 +8,7 @@ import React from 'react'; import styled from 'styled-components'; export const StyledAlert = styled(EuiIcon)` - color: ${props => props.theme.eui.euiColorWarning}; + color: ${(props) => props.theme.eui.euiColorWarning}; padding: 0 5px; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx index 0c01bb72b339a..3fcf9758368de 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx @@ -9,7 +9,7 @@ import styled from 'styled-components'; export function NavButtonBack({ href, text }: { href: string; text: string }) { const ButtonEmpty = styled(EuiButtonEmpty)` - margin-right: ${props => props.theme.eui.spacerSizes.xl}; + margin-right: ${(props) => props.theme.eui.spacerSizes.xl}; `; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx index 2f06d1d8703c2..dbf454acd2b74 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx @@ -65,9 +65,9 @@ export function PackageListGrid({ gridContent = ; } else { const filteredList = searchTerm - ? list.filter(item => + ? list.filter((item) => (localSearchRef.current!.search(searchTerm) as PackageList) - .map(match => match[searchIdField]) + .map((match) => match[searchIdField]) .includes(item[searchIdField]) ) : list; @@ -123,7 +123,7 @@ function GridColumn({ list }: GridColumnProps) { return ( {list.length ? ( - list.map(item => ( + list.map((item) => ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx index f60d2d83ed45e..3d6cd2bc61e72 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx @@ -16,11 +16,11 @@ export interface RequirementsProps { } const FlexGroup = styled(EuiFlexGroup)` - padding: 0 0 ${props => props.theme.eui.paddingSizes.m} 0; + padding: 0 0 ${(props) => props.theme.eui.paddingSizes.m} 0; margin: 0; `; const StyledVersion = styled(Version)` - font-size: ${props => props.theme.eui.euiFontSizeXS}; + font-size: ${(props) => props.theme.eui.euiFontSizeXS}; `; export function Requirements(props: RequirementsProps) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx index 537f6201dea06..d15eee55b9f75 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx @@ -9,7 +9,7 @@ import styled from 'styled-components'; import { RequirementVersion } from '../../../types'; const CodeText = styled.span` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; `; export function Version({ className, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx index c81dc15f569fa..4cfae0eac5442 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx @@ -16,7 +16,7 @@ export function useLocalSearch(packageList: PackageList) { useEffect(() => { const localSearch = new LocalSearch(searchIdField); - fieldsToSearch.forEach(field => localSearch.addIndex(field)); + fieldsToSearch.forEach((field) => localSearch.addIndex(field)); localSearch.addDocuments(packageList); localSearchRef.current = localSearch; }, [packageList]); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx index 36b81e786b935..2342a79932c85 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx @@ -181,8 +181,8 @@ export const [ useUninstallPackage, ] = createContainer( usePackageInstall, - value => value.installPackage, - value => value.setPackageInstallStatus, - value => value.getPackageInstallStatus, - value => value.uninstallPackage + (value) => value.installPackage, + (value) => value.setPackageInstallStatus, + (value) => value.getPackageInstallStatus, + (value) => value.uninstallPackage ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx index 9d5614debb42b..482c5970ce93d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx @@ -9,10 +9,10 @@ import styled from 'styled-components'; const BottomFade = styled.div` width: 100%; - background: ${props => + background: ${(props) => `linear-gradient(${props.theme.eui.euiColorEmptyShade}00 0%, ${props.theme.eui.euiColorEmptyShade} 100%)`}; - margin-top: -${props => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; - height: ${props => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; + margin-top: -${(props) => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; + height: ${(props) => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; position: absolute; `; const ContentCollapseContainer = styled.div` @@ -20,11 +20,11 @@ const ContentCollapseContainer = styled.div` `; const CollapseButtonContainer = styled.div` display: inline-block; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; position: absolute; left: 50%; transform: translateX(-50%); - top: ${props => parseInt(props.theme.eui.euiButtonHeight, 10) / 2}px; + top: ${(props) => parseInt(props.theme.eui.euiButtonHeight, 10) / 2}px; `; const CollapseButtonTop = styled(EuiButtonEmpty)` float: right; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx index 5c2d1373d0b0e..318bab6c44951 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx @@ -21,7 +21,7 @@ const FullWidthNavRow = styled(EuiPage)` `; const Text = styled.span` - margin-right: ${props => props.theme.eui.euiSizeM}; + margin-right: ${(props) => props.theme.eui.euiSizeM}; `; type HeaderProps = PackageInfo & { iconType?: IconType }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx index 0c91413f6e210..505687068cf42 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx @@ -27,7 +27,7 @@ export function Detail() { const [info, setInfo] = useState(null); const setPackageInstallStatus = useSetPackageInstallStatus(); useEffect(() => { - sendGetPackageInfoByKey(pkgkey).then(response => { + sendGetPackageInfoByKey(pkgkey).then((response) => { const packageInfo = response.data?.response; const title = packageInfo?.title; const name = packageInfo?.name; @@ -53,13 +53,13 @@ export function Detail() { } const FullWidthHeader = styled(EuiPage)` - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding-bottom: ${props => props.theme.eui.paddingSizes.xl}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding-bottom: ${(props) => props.theme.eui.paddingSizes.xl}; `; const FullWidthContent = styled(EuiPage)` - background-color: ${props => props.theme.eui.euiColorEmptyShade}; - padding-top: ${props => parseInt(props.theme.eui.paddingSizes.xl, 10) * 1.25}px; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; + padding-top: ${(props) => parseInt(props.theme.eui.paddingSizes.xl, 10) * 1.25}px; flex-grow: 1; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx index 72e2d779c39be..c8fa2184d8f9b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx @@ -33,7 +33,7 @@ export function Readme({ ); useEffect(() => { - sendGetFileByPath(readmePath).then(res => { + sendGetFileByPath(readmePath).then((res) => { setMarkdown(res.data || ''); }); }, [readmePath]); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx index 10cf9c97723c0..696af14604c5b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx @@ -34,10 +34,10 @@ export function Screenshots(props: ScreenshotProps) { const ScreenshotsContainer = styled(EuiFlexGroup)` background: linear-gradient(360deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%), - ${styledProps => styledProps.theme.eui.euiColorPrimary}; - padding: ${styledProps => getPadding(styledProps)}; + ${(styledProps) => styledProps.theme.eui.euiColorPrimary}; + padding: ${(styledProps) => getPadding(styledProps)}; flex: 0 0 auto; - border-radius: ${styledProps => styledProps.theme.eui.euiBorderRadius}; + border-radius: ${(styledProps) => styledProps.theme.eui.euiBorderRadius}; `; // fixes ie11 problems with nested flex items diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx index 4d4dba2a64e5a..5d24c180268a7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx @@ -17,12 +17,12 @@ import { InstallationButton } from './installation_button'; import { UpdateIcon } from '../../components/icons'; const SettingsTitleCell = styled.td` - padding-right: ${props => props.theme.eui.spacerSizes.xl}; - padding-bottom: ${props => props.theme.eui.spacerSizes.m}; + padding-right: ${(props) => props.theme.eui.spacerSizes.xl}; + padding-bottom: ${(props) => props.theme.eui.spacerSizes.m}; `; const UpdatesAvailableMsgContainer = styled.span` - padding-left: ${props => props.theme.eui.spacerSizes.s}; + padding-left: ${(props) => props.theme.eui.spacerSizes.s}; `; const NoteLabel = () => ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx index 65a437269ec6a..1aa491498c466 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx @@ -38,7 +38,7 @@ export function SideNavLinks({ name, version, active }: NavLinkProps) { const Link = styled(EuiButtonEmpty).attrs({ href: getHref('integration_details', { pkgkey: `${name}-${version}`, panel }), })` - font-weight: ${p => + font-weight: ${(p) => active === panel ? p.theme.eui.euiFontWeightSemiBold : p.theme.eui.euiFontWeightRegular}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx index 52730664aac05..8ce43b0b62f40 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx @@ -24,7 +24,7 @@ export function CategoryFacets({ {isLoading ? ( ) : ( - categories.map(category => ( + categories.map((category) => ( { const { uiSettings } = useCore(); const IS_DARK_THEME = uiSettings.get('theme:darkMode'); - const Illustration = styled(EuiImage).attrs(props => ({ + const Illustration = styled(EuiImage).attrs((props) => ({ alt: i18n.translate('xpack.ingestManager.epm.illustrationAltText', { defaultMessage: 'Illustration of an Elastic integration', }), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx index 84ad3593a5bf1..e00b63e29019e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx @@ -70,11 +70,11 @@ function InstalledPackages() { const allInstalledPackages = allPackages && allPackages.response - ? allPackages.response.filter(pkg => pkg.status === 'installed') + ? allPackages.response.filter((pkg) => pkg.status === 'installed') : []; const updatablePackages = allInstalledPackages.filter( - item => 'savedObject' in item && item.version > item.savedObject.attributes.version + (item) => 'savedObject' in item && item.version > item.savedObject.attributes.version ); const categories = [ diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx index adffdefd30a4f..99df334884a1f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx @@ -26,8 +26,8 @@ export function SearchPackages({ searchTerm, localSearchRef, allPackages }: Sear if (!localSearchRef.current) return
          Still fetching matches. Try again in a moment.
          ; const matches = localSearchRef.current.search(searchTerm) as PackageList; - const matchingIds = matches.map(match => match[searchIdField]); - const filtered = allPackages.filter(item => matchingIds.includes(item[searchIdField])); + const matchingIds = matches.map((match) => match[searchIdField]); + const filtered = allPackages.filter((item) => matchingIds.includes(item[searchIdField])); return ; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx index 37fb556b94282..34a7ad8eb1efc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx @@ -60,7 +60,7 @@ export const AgentDetailsActionMenu: React.FunctionComponent<{ /> , - {unenrollAgentsPrompt => ( + {(unenrollAgentsPrompt) => ( { + keyParts.forEach((keyPart) => { if (!metadataPart[keyPart]) { metadataPart[keyPart] = {}; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx index aa6da36f8fb6c..96c09677a677f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx @@ -26,7 +26,7 @@ interface Props { export const AgentMetadataFlyout: React.FunctionComponent = ({ agent, flyout }) => { const mapMetadata = (obj: { [key: string]: string } | undefined) => { - return Object.keys(obj || {}).map(key => ({ + return Object.keys(obj || {}).map((key) => ({ title: key, description: obj ? obj[key] : '', })); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx index 2ebc495d5dda7..1a7681584ff15 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx @@ -31,7 +31,7 @@ import { AgentEventsTable, AgentDetailsActionMenu, AgentDetailsContent } from '. const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; `; export const AgentDetailsPage: React.FunctionComponent = () => { @@ -140,9 +140,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => {
          ))}
          - ) : ( - undefined - ), + ) : undefined, [agentConfigData, agentData, getHref, isAgentConfigLoading] ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx index 56cc0028f0cf9..d5b8b393e7ed9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx @@ -123,7 +123,7 @@ const RowActions = React.memo<{ agent: Agent; onReassignClick: () => void; refre , - {unenrollAgentsPrompt => ( + {(unenrollAgentsPrompt) => ( = () => { // Remove a config id from current search const removeConfigFilter = (configId: string) => { - setSelectedConfigs(selectedConfigs.filter(config => config !== configId)); + setSelectedConfigs(selectedConfigs.filter((config) => config !== configId)); }; // Agent enrollment flyout state @@ -196,7 +196,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { kuery = `(${kuery}) and`; } kuery = `${kuery} ${AGENT_SAVED_OBJECT_TYPE}.config_id : (${selectedConfigs - .map(config => `"${config}"`) + .map((config) => `"${config}"`) .join(' or ')})`; } @@ -206,7 +206,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { } kuery = selectedStatus - .map(status => { + .map((status) => { switch (status) { case 'online': return AgentStatusKueryHelper.buildKueryForOnlineAgents(); @@ -271,7 +271,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Configuration', }), render: (configId: string, agent: Agent) => { - const configName = agentConfigs.find(p => p.id === configId)?.name; + const configName = agentConfigs.find((p) => p.id === configId)?.name; return ( @@ -376,7 +376,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { /> ); - const agentToReassign = agentToReassignId && agents.find(a => a.id === agentToReassignId); + const agentToReassign = agentToReassignId && agents.find((a) => a.id === agentToReassignId); return ( <> @@ -401,7 +401,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, @@ -441,7 +441,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { checked={selectedStatus.includes(status) ? 'on' : undefined} onClick={() => { if (selectedStatus.includes(status)) { - setSelectedStatus([...selectedStatus.filter(s => s !== status)]); + setSelectedStatus([...selectedStatus.filter((s) => s !== status)]); } else { setSelectedStatus([...selectedStatus, status]); } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx index a8cebfdf899a6..6e7427c6ab55e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx @@ -36,7 +36,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey } return enrollmentAPIKeysRequest.data.list.filter( - key => key.config_id === selectedState.agentConfigId + (key) => key.config_id === selectedState.agentConfigId ); }, [enrollmentAPIKeysRequest.data, selectedState.agentConfigId]); @@ -65,12 +65,12 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey /> } - options={agentConfigs.map(config => ({ + options={agentConfigs.map((config) => ({ value: config.id, text: config.name, }))} value={selectedState.agentConfigId || undefined} - onChange={e => + onChange={(e) => setSelectedState({ agentConfigId: e.target.value, enrollmentAPIKeyId: undefined, @@ -101,7 +101,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey ({ + options={filteredEnrollmentAPIKeys.map((key) => ({ value: key.id, text: key.name, }))} @@ -114,7 +114,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey /> } - onChange={e => { + onChange={(e) => { setSelectedState({ ...selectedState, enrollmentAPIKeyId: e.target.value, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx index 2c103ade31f5b..abb8212e4c83a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx @@ -100,12 +100,12 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl > ({ + options={agentConfigs.map((config) => ({ value: config.id, text: config.name, }))} value={selectedAgentConfigId} - onChange={e => setSelectedAgentConfigId(e.target.value)} + onChange={(e) => setSelectedAgentConfigId(e.target.value)} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx index fd6b80310a874..cc12ea19fbecf 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx @@ -31,7 +31,7 @@ const REFRESH_INTERVAL_MS = 5000; const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; height: 45px; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx index b9c07c800635d..5ab4ed978819f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx @@ -80,7 +80,7 @@ export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ onClose, agentConfigs = [], }) => { - const configDefaultValue = agentConfigs.find(config => config.is_default)?.id; + const configDefaultValue = agentConfigs.find((config) => config.is_default)?.id; const form = useCreateApiKeyForm(configDefaultValue, () => { onClose(); }); @@ -110,7 +110,7 @@ export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ required={true} defaultValue={configDefaultValue} {...form.configIdInput.props} - options={agentConfigs.map(config => ({ value: config.id, text: config.name }))} + options={agentConfigs.map((config) => ({ value: config.id, text: config.name }))} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx index add495ce0c194..800d4abfd45ed 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx @@ -178,7 +178,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Config', }), render: (configId: string) => { - const config = agentConfigs.find(c => c.id === configId); + const config = agentConfigs.find((c) => c.id === configId); return <>{config ? config.name : configId}; }, }, @@ -246,7 +246,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx index 94d1395700ab5..87906afb4122a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx @@ -29,7 +29,7 @@ export const OverviewDatastreamSection: React.FC = () => { let sizeBytes = 0; const namespaces = new Set(); if (datastreamRequest.data) { - datastreamRequest.data.data_streams.forEach(val => { + datastreamRequest.data.data_streams.forEach((val) => { namespaces.add(val.namespace); sizeBytes += val.size_in_bytes; }); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx index b73fa3559c954..b4669b0a0569b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx @@ -24,10 +24,11 @@ export const OverviewIntegrationSection: React.FC = () => { const packagesRequest = useGetPackages(); const res = packagesRequest.data?.response; const total = res?.length ?? 0; - const installed = res?.filter(p => p.status === InstallationStatus.installed)?.length ?? 0; + const installed = res?.filter((p) => p.status === InstallationStatus.installed)?.length ?? 0; const updatablePackages = - res?.filter(item => 'savedObject' in item && item.version > item.savedObject.attributes.version) - ?.length ?? 0; + res?.filter( + (item) => 'savedObject' in item && item.version > item.savedObject.attributes.version + )?.length ?? 0; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx index 41d7a7a5f0bc3..2e75d1e4690d6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx @@ -7,20 +7,22 @@ import styled from 'styled-components'; import { EuiPanel } from '@elastic/eui'; -export const OverviewPanel = styled(EuiPanel).attrs(props => ({ +export const OverviewPanel = styled(EuiPanel).attrs((props) => ({ paddingSize: 'm', }))` header { display: flex; align-items: center; justify-content: space-between; - border-bottom: 1px solid ${props => props.theme.eui.euiColorLightShade}; - margin: -${props => props.theme.eui.paddingSizes.m} -${props => props.theme.eui.paddingSizes.m} - ${props => props.theme.eui.paddingSizes.m}; - padding: ${props => props.theme.eui.paddingSizes.s} ${props => props.theme.eui.paddingSizes.m}; + border-bottom: 1px solid ${(props) => props.theme.eui.euiColorLightShade}; + margin: -${(props) => props.theme.eui.paddingSizes.m} -${(props) => + props.theme.eui.paddingSizes.m} + ${(props) => props.theme.eui.paddingSizes.m}; + padding: ${(props) => props.theme.eui.paddingSizes.s} + ${(props) => props.theme.eui.paddingSizes.m}; } h2 { - padding: ${props => props.theme.eui.paddingSizes.xs} 0; + padding: ${(props) => props.theme.eui.paddingSizes.xs} 0; } `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx index 04de22c34fe6f..d3bfc5398e7b2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx @@ -7,13 +7,13 @@ import styled from 'styled-components'; import { EuiDescriptionList } from '@elastic/eui'; -export const OverviewStats = styled(EuiDescriptionList).attrs(props => ({ +export const OverviewStats = styled(EuiDescriptionList).attrs((props) => ({ compressed: true, textStyle: 'reverse', type: 'column', }))` & > * { - margin-top: ${props => props.theme.eui.paddingSizes.s} !important; + margin-top: ${(props) => props.theme.eui.paddingSizes.s} !important; &:first-child, &:nth-child(2) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx index 93db262714cef..ca4151fa5c46f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx @@ -25,7 +25,7 @@ import { OverviewDatastreamSection } from './components/datastream_section'; const AlphaBadge = styled(EuiBetaBadge)` vertical-align: top; - margin-left: ${props => props.theme.eui.paddingSizes.s}; + margin-left: ${(props) => props.theme.eui.paddingSizes.s}; `; export const IngestManagerOverview: React.FunctionComponent = () => { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts index 13dcea75f31d0..83d894295c312 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts @@ -14,7 +14,7 @@ import { AcksService } from '../../services/agents'; import { AgentEvent } from '../../../common/types/models'; import { PostAgentAcksResponse } from '../../../common/types/rest_spec'; -export const postAgentAcksHandlerBuilder = function( +export const postAgentAcksHandlerBuilder = function ( ackService: AcksService ): RequestHandler< TypeOf, @@ -30,7 +30,7 @@ export const postAgentAcksHandlerBuilder = function( // validate that all events are for the authorized agent obtained from the api key const notAuthorizedAgentEvent = agentEvents.filter( - agentEvent => agentEvent.agent_id !== agent.id + (agentEvent) => agentEvent.agent_id !== agent.id ); if (notAuthorizedAgentEvent && notAuthorizedAgentEvent.length > 0) { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts index 8eb427e5739b0..81893b1e78338 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts @@ -13,7 +13,7 @@ import { ActionsService } from '../../services/agents'; import { NewAgentAction } from '../../../common/types/models'; import { PostNewAgentActionResponse } from '../../../common/types/rest_spec'; -export const postNewAgentActionHandlerBuilder = function( +export const postNewAgentActionHandlerBuilder = function ( actionsService: ActionsService ): RequestHandler< TypeOf, diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts index 5820303e2a1a7..ae833b55137cc 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts @@ -188,7 +188,7 @@ export const postAgentCheckinHandler: RequestHandler< const body: PostAgentCheckinResponse = { action: 'checkin', success: true, - actions: actions.map(a => ({ + actions: actions.map((a) => ({ agent_id: agent.id, type: a.type, data: a.data, @@ -277,7 +277,7 @@ export const getAgentsHandler: RequestHandler< }); const body: GetAgentsResponse = { - list: agents.map(agent => ({ + list: agents.map((agent) => ({ ...agent, status: AgentService.getAgentStatus(agent), })), diff --git a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts index 666d46f030780..9b36edd0a961c 100644 --- a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts @@ -98,7 +98,7 @@ export const getListHandler: RequestHandler = async (context, request, response) const packageSavedObjects = await getPackageSavedObjects(context.core.savedObjects.client); const packageMetadata: any = {}; - const dataStreamsPromises = (indexResults as any[]).map(async result => { + const dataStreamsPromises = (indexResults as any[]).map(async (result) => { const { key: indexName, dataset: { buckets: datasetBuckets }, @@ -113,7 +113,7 @@ export const getListHandler: RequestHandler = async (context, request, response) const pkg = datasetBuckets.length ? datasetBuckets[0].key.split('.')[0] : indexName.split('-')[1].split('.')[0]; - const pkgSavedObject = packageSavedObjects.saved_objects.filter(p => p.id === pkg); + const pkgSavedObject = packageSavedObjects.saved_objects.filter((p) => p.id === pkg); // if // - the datastream is associated with a package @@ -123,7 +123,7 @@ export const getListHandler: RequestHandler = async (context, request, response) // then pick the dashboards from the package saved object const dashboards = pkgSavedObject[0].attributes?.installed?.filter( - o => o.type === KibanaAssetType.dashboard + (o) => o.type === KibanaAssetType.dashboard ) || []; // and then pick the human-readable titles from the dashboard saved objects const enhancedDashboards = await getEnhancedDashboards( @@ -169,7 +169,7 @@ const getEnhancedDashboards = async ( savedObjectsClient: SavedObjectsClientContract, dashboards: any[] ) => { - const dashboardsPromises = dashboards.map(async db => { + const dashboardsPromises = dashboards.map(async (db) => { const dbSavedObject: any = await getKibanaSavedObject( savedObjectsClient, KibanaAssetType.dashboard, diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts index ad808a10400e2..703ddb521c831 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts @@ -262,7 +262,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { }; export function registerSavedObjects(savedObjects: SavedObjectsServiceSetup) { - Object.values(savedObjectTypes).forEach(type => { + Object.values(savedObjectTypes).forEach((type) => { savedObjects.registerType(type); }); } diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts index 05ef2bb397fd9..0c850f2c25fbf 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts @@ -12,10 +12,9 @@ type Pre790AgentConfig = Exclude & { updated_on: string; }; -export const migrateAgentConfigToV790: SavedObjectMigrationFn< - Pre790AgentConfig, - AgentConfig -> = doc => { +export const migrateAgentConfigToV790: SavedObjectMigrationFn = ( + doc +) => { const updatedAgentConfig = cloneDeep(doc); updatedAgentConfig.attributes.updated_at = doc.attributes.updated_on; diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts index 1f16af6f83065..0d1fb6f21a1ae 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts @@ -13,10 +13,9 @@ type Pre790Datasource = Exclude< 'created_at' | 'created_by' | 'updated_at' | 'updated_by' >; -export const migrateDatasourcesToV790: SavedObjectMigrationFn< - Pre790Datasource, - Datasource -> = doc => { +export const migrateDatasourcesToV790: SavedObjectMigrationFn = ( + doc +) => { const updatedDatasource = cloneDeep(doc); const defDate = new Date().toISOString(); diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.ts b/x-pack/plugins/ingest_manager/server/services/agent_config.ts index 07c69ae132833..62b568b812216 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_config.ts @@ -165,7 +165,7 @@ class AgentConfigService { }); return { - items: agentConfigs.saved_objects.map(agentConfigSO => { + items: agentConfigs.saved_objects.map((agentConfigSO) => { return { id: agentConfigSO.id, ...agentConfigSO.attributes, @@ -238,7 +238,7 @@ class AgentConfigService { ...oldAgentConfig, datasources: uniq( [...((oldAgentConfig.datasources || []) as string[])].filter( - dsId => !datasourceIds.includes(dsId) + (dsId) => !datasourceIds.includes(dsId) ) ), }, @@ -340,8 +340,8 @@ class AgentConfigService { ), }, datasources: (config.datasources as Datasource[]) - .filter(datasource => datasource.enabled) - .map(ds => storedDatasourceToAgentDatasource(ds)), + .filter((datasource) => datasource.enabled) + .map((ds) => storedDatasourceToAgentDatasource(ds)), revision: config.revision, ...(config.monitoring_enabled && config.monitoring_enabled.length > 0 ? { diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts index 24c3b322aad7f..81ba9754e8aa4 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts @@ -40,8 +40,8 @@ export async function acknowledgeAgentActions( } const actionIds = agentEvents - .map(event => event.action_id) - .filter(actionId => actionId !== undefined) as string[]; + .map((event) => event.action_id) + .filter((actionId) => actionId !== undefined) as string[]; let actions; try { @@ -101,7 +101,7 @@ function buildUpdateAgentActionSentAt( actionsIds: string[], sentAt: string = new Date().toISOString() ) { - return actionsIds.map(actionId => ({ + return actionsIds.map((actionId) => ({ type: AGENT_ACTION_SAVED_OBJECT_TYPE, id: actionId, attributes: { @@ -119,7 +119,7 @@ export async function saveAgentEvents( events: AgentEvent[] ): Promise> { const objects: Array> = events.map( - eventData => { + (eventData) => { return { attributes: { ...eventData, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts index 1bb177e54282d..236ad7df466b4 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts @@ -35,7 +35,7 @@ export async function getAgentActionsForCheckin( }); return Promise.all( - res.saved_objects.map(async so => { + res.saved_objects.map(async (so) => { // Get decrypted actions return savedObjectToAgentAction( await appContextService @@ -55,7 +55,7 @@ export async function getAgentActionByIds( ) { const actions = ( await soClient.bulkGet( - actionIds.map(actionId => ({ + actionIds.map((actionId) => ({ id: actionId, type: AGENT_ACTION_SAVED_OBJECT_TYPE, })) @@ -63,7 +63,7 @@ export async function getAgentActionByIds( ).saved_objects.map(savedObjectToAgentAction); return Promise.all( - actions.map(async action => { + actions.map(async (action) => { // Get decrypted actions return savedObjectToAgentAction( await appContextService diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts index 2c8b1d5bb6078..20b62eee9a317 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts @@ -100,7 +100,9 @@ async function processEventsForCheckin( if (isErrorOrState(event)) { // Remove any global or specific to a stream event - const existingEventIndex = updatedErrorEvents.findIndex(e => e.stream_id === event.stream_id); + const existingEventIndex = updatedErrorEvents.findIndex( + (e) => e.stream_id === event.stream_id + ); if (existingEventIndex >= 0) { updatedErrorEvents.splice(existingEventIndex, 1); } @@ -126,7 +128,7 @@ async function createEventsForAgent( events: NewAgentEvent[] ) { const objects: Array> = events.map( - eventData => { + (eventData) => { return { attributes: { ...eventData, @@ -172,7 +174,7 @@ export function shouldCreateConfigAction(agent: Agent, actions: AgentAction[]): return false; } - const isActionAlreadyGenerated = !!actions.find(action => { + const isActionAlreadyGenerated = !!actions.find((action) => { if (!action.data || action.type !== 'CONFIG_CHANGE') { return false; } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/crud.ts b/x-pack/plugins/ingest_manager/server/services/agents/crud.ts index 43fd5a3ce0ac9..c78a9ff8bb7b5 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/crud.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/crud.ts @@ -41,8 +41,9 @@ export async function listAgents( if (showInactive === false) { const agentActiveCondition = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND not ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL}`; - const recentlySeenEphemeralAgent = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL} AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.last_checkin > ${Date.now() - - 3 * AGENT_POLLING_THRESHOLD_MS}`; + const recentlySeenEphemeralAgent = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL} AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.last_checkin > ${ + Date.now() - 3 * AGENT_POLLING_THRESHOLD_MS + }`; filters.push(`(${agentActiveCondition}) OR (${recentlySeenEphemeralAgent})`); } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/events.ts b/x-pack/plugins/ingest_manager/server/services/agents/events.ts index 947f79bbea094..b6d87c9ca5b2f 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/events.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/events.ts @@ -37,7 +37,7 @@ export async function getAgentEvents( searchFields: ['agent_id'], }); - const items: AgentEvent[] = saved_objects.map(so => { + const items: AgentEvent[] = saved_objects.map((so) => { return { id: so.id, ...so.attributes, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/status.ts b/x-pack/plugins/ingest_manager/server/services/agents/status.ts index f570243164aa9..63388db890ea5 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/status.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/status.ts @@ -30,7 +30,7 @@ export async function getAgentStatusForConfig( undefined, AgentStatusKueryHelper.buildKueryForErrorAgents(), AgentStatusKueryHelper.buildKueryForOfflineAgents(), - ].map(kuery => + ].map((kuery) => listAgents(soClient, { showInactive: false, perPage: 0, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/update.ts b/x-pack/plugins/ingest_manager/server/services/agents/update.ts index fd57e83d7421e..ec7a42ff11b7a 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/update.ts @@ -31,7 +31,7 @@ export async function updateAgentsForConfigId( hasMore = false; break; } - const agentUpdate = agents.map(agent => ({ + const agentUpdate = agents.map((agent) => ({ id: agent.id, type: AGENT_SAVED_OBJECT_TYPE, attributes: { config_newest_revision: config.revision }, diff --git a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts index 57362e6b4b0de..7d8d372a89ac4 100644 --- a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts @@ -104,9 +104,7 @@ export function parseApiKeyFromHeaders(headers: KibanaRequest['headers']) { } export function parseApiKey(apiKey: string) { - const apiKeyId = Buffer.from(apiKey, 'base64') - .toString('utf8') - .split(':')[0]; + const apiKeyId = Buffer.from(apiKey, 'base64').toString('utf8').split(':')[0]; return { apiKey, diff --git a/x-pack/plugins/ingest_manager/server/services/datasource.ts b/x-pack/plugins/ingest_manager/server/services/datasource.ts index 8f9b4825ab5d7..c3dba0700bdaf 100644 --- a/x-pack/plugins/ingest_manager/server/services/datasource.ts +++ b/x-pack/plugins/ingest_manager/server/services/datasource.ts @@ -77,7 +77,7 @@ class DatasourceService { ids: string[] ): Promise { const datasourceSO = await soClient.bulkGet( - ids.map(id => ({ + ids.map((id) => ({ id, type: SAVED_OBJECT_TYPE, })) @@ -86,7 +86,7 @@ class DatasourceService { return null; } - return datasourceSO.saved_objects.map(so => ({ + return datasourceSO.saved_objects.map((so) => ({ id: so.id, ...so.attributes, })); @@ -112,7 +112,7 @@ class DatasourceService { }); return { - items: datasources.saved_objects.map(datasourceSO => { + items: datasources.saved_objects.map((datasourceSO) => { return { id: datasourceSO.id, ...datasourceSO.attributes, @@ -215,14 +215,14 @@ class DatasourceService { pkgInfo: PackageInfo, inputs: DatasourceInput[] ): Promise { - const inputsPromises = inputs.map(input => _assignPackageStreamToInput(pkgInfo, input)); + const inputsPromises = inputs.map((input) => _assignPackageStreamToInput(pkgInfo, input)); return Promise.all(inputsPromises); } } async function _assignPackageStreamToInput(pkgInfo: PackageInfo, input: DatasourceInput) { - const streamsPromises = input.streams.map(stream => + const streamsPromises = input.streams.map((stream) => _assignPackageStreamToStream(pkgInfo, input, stream) ); @@ -244,13 +244,13 @@ async function _assignPackageStreamToStream( throw new Error('Stream template not found, no datasource'); } - const inputFromPkg = datasource.inputs.find(pkgInput => pkgInput.type === input.type); + const inputFromPkg = datasource.inputs.find((pkgInput) => pkgInput.type === input.type); if (!inputFromPkg) { throw new Error(`Stream template not found, unable to found input ${input.type}`); } const streamFromPkg = inputFromPkg.streams.find( - pkgStream => pkgStream.dataset === stream.dataset + (pkgStream) => pkgStream.dataset === stream.dataset ); if (!streamFromPkg) { throw new Error(`Stream template not found, unable to found stream ${stream.dataset}`); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts index 60a85e367079f..1d06bf23a8c0f 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts @@ -19,7 +19,7 @@ export async function installILMPolicy( ); if (!ilmPaths.length) return; await Promise.all( - ilmPaths.map(async path => { + ilmPaths.map(async (path) => { const body = Registry.getAsset(path).toString('utf-8'); const { file } = Registry.pathParts(path); const name = file.substr(0, file.lastIndexOf('.')); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts index 2bbb555ef7393..bdf6ecfcdb9aa 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts @@ -39,7 +39,7 @@ export const installPipelines = async ( } return acc; }, []); - return Promise.all(pipelines).then(results => results.flat()); + return Promise.all(pipelines).then((results) => results.flat()); } return []; }; @@ -48,7 +48,7 @@ export function rewriteIngestPipeline( pipeline: string, substitutions: RewriteSubstitution[] ): string { - substitutions.forEach(sub => { + substitutions.forEach((sub) => { const { source, target, templateFunction } = sub; // This fakes the use of the golang text/template expression {{SomeTemplateFunction 'some-param'}} // cf. https://github.com/elastic/beats/blob/master/filebeat/fileset/fileset.go#L294 @@ -84,7 +84,7 @@ export async function installPipelinesForDataset({ let pipelines: any[] = []; const substitutions: RewriteSubstitution[] = []; - pipelinePaths.forEach(path => { + pipelinePaths.forEach((path) => { const { name, extension } = getNameAndExtension(path); const nameForInstallation = getPipelineNameForInstallation({ pipelineName: name, @@ -105,14 +105,14 @@ export async function installPipelinesForDataset({ }); }); - pipelines = pipelines.map(pipeline => { + pipelines = pipelines.map((pipeline) => { return { ...pipeline, contentForInstallation: rewriteIngestPipeline(pipeline.content, substitutions), }; }); - const installationPromises = pipelines.map(async pipeline => { + const installationPromises = pipelines.map(async (pipeline) => { return installPipeline({ callCluster, pipeline }); }); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts index 2c452f16cc104..c600c8ba3efb8 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts @@ -54,7 +54,7 @@ const installPreBuiltTemplates = async ( pkgVersion, (entry: Registry.ArchiveEntry) => isTemplate(entry) ); - const templateInstallPromises = templatePaths.map(async path => { + const templateInstallPromises = templatePaths.map(async (path) => { const { file } = Registry.pathParts(path); const templateName = file.substr(0, file.lastIndexOf('.')); const content = JSON.parse(Registry.getAsset(path).toString('utf8')); @@ -104,7 +104,7 @@ const installPreBuiltComponentTemplates = async ( pkgVersion, (entry: Registry.ArchiveEntry) => isComponentTemplate(entry) ); - const templateInstallPromises = templatePaths.map(async path => { + const templateInstallPromises = templatePaths.map(async (path) => { const { file } = Registry.pathParts(path); const templateName = file.substr(0, file.lastIndexOf('.')); const content = JSON.parse(Registry.getAsset(path).toString('utf8')); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts index 65b5ae636612c..85d4a85e245c2 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts @@ -63,7 +63,7 @@ export function generateMappings(fields: Field[]): IndexTemplateMappings { // TODO: this can happen when the fields property in fields.yml is present but empty // Maybe validation should be moved to fields/field.ts if (fields) { - fields.forEach(field => { + fields.forEach((field) => { // If type is not defined, assume keyword const type = field.type || 'keyword'; @@ -314,11 +314,11 @@ const queryIndicesFromTemplates = async ( callCluster: CallESAsCurrentUser, templates: TemplateRef[] ): Promise => { - const indexPromises = templates.map(template => { + const indexPromises = templates.map((template) => { return getIndices(callCluster, template); }); const indexObjects = await Promise.all(indexPromises); - return indexObjects.filter(item => item !== undefined).flat(); + return indexObjects.filter((item) => item !== undefined).flat(); }; const getIndices = async ( @@ -329,7 +329,7 @@ const getIndices = async ( const res = await callCluster('search', getIndexQuery(templateName)); const indices: any[] = res?.aggregations?.index.buckets; if (indices) { - return indices.map(index => ({ + return indices.map((index) => ({ indexName: index.key, indexTemplate, })); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts index abaf7ab5b0dfc..e7c0eca2a9613 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts @@ -105,8 +105,8 @@ export function expandFields(fields: Fields): Fields { */ function dedupFields(fields: Fields): Fields { const dedupedFields: Fields = []; - fields.forEach(field => { - const found = dedupedFields.find(f => { + fields.forEach((field) => { + const found = dedupedFields.find((f) => { return f.name === field.name; }); if (found) { @@ -185,7 +185,7 @@ function dedupFields(fields: Fields): Fields { function validateFields(fields: Fields, allFields: Fields): Fields { const validatedFields: Fields = []; - fields.forEach(field => { + fields.forEach((field) => { if (field.type === 'alias') { if (field.path && getField(allFields, field.path.split('.'))) { validatedFields.push(field); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts index f1660fbc01591..d083b40e40fd5 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts @@ -64,7 +64,7 @@ describe('creating index patterns from yaml fields', () => { describe('dedupFields', () => { const deduped = dedupeFields(dupeFields); const checkIfDup = (field: Field) => { - return deduped.filter(item => item.name === field.name); + return deduped.filter((item) => item.name === field.name); }; test('there there is one field object with name of "1"', () => { expect(checkIfDup({ name: '1' }).length).toBe(1); @@ -80,7 +80,7 @@ describe('creating index patterns from yaml fields', () => { }); // existing field takes precendence test('the new merged field has correct attributes', () => { - const mergedField = deduped.find(field => field.name === '1'); + const mergedField = deduped.find((field) => field.name === '1'); expect(mergedField?.searchable).toBe(true); expect(mergedField?.aggregatable).toBe(true); expect(mergedField?.analyzed).toBe(true); @@ -153,7 +153,7 @@ describe('creating index patterns from yaml fields', () => { { fields: [{ name: 'testField', type: 'constant_keyword' }], expect: 'string' }, ]; - tests.forEach(test => { + tests.forEach((test) => { const res = test.fields.map(transformField); expect(res[0].type).toBe(test.expect); }); @@ -261,7 +261,7 @@ describe('creating index patterns from yaml fields', () => { { fields: [{ name }], expect: undefined, attr: 'lang' }, { fields: [{ name, script: 'doc[]' }], expect: 'painless', attr: 'lang' }, ]; - tests.forEach(test => { + tests.forEach((test) => { const res = test.fields.map(transformField); expect(res[0][test.attr]).toBe(test.expect); }); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts index d220ecfc62bb8..f321e2d614a04 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts @@ -88,7 +88,7 @@ export async function installIndexPatterns( ); if (pkgName && pkgVersion) { // add this package to the array if it doesn't already exist - const foundPkg = installedPackages.find(pkg => pkg.pkgName === pkgName); + const foundPkg = installedPackages.find((pkg) => pkg.pkgName === pkgName); // this may be removed if we add the packged to saved objects before installing index patterns // otherwise this is a first time install // TODO: handle update case when versions are different @@ -97,7 +97,7 @@ export async function installIndexPatterns( } } // get each package's registry info - const installedPackagesFetchInfoPromise = installedPackages.map(pkg => + const installedPackagesFetchInfoPromise = installedPackages.map((pkg) => Registry.fetchInfo(pkg.pkgName, pkg.pkgVersion) ); const installedPackagesInfo = await Promise.all(installedPackagesFetchInfoPromise); @@ -108,7 +108,7 @@ export async function installIndexPatterns( IndexPatternType.metrics, IndexPatternType.events, ]; - indexPatternTypes.forEach(async indexPatternType => { + indexPatternTypes.forEach(async (indexPatternType) => { // if this is an update because a package is being unisntalled (no pkgkey argument passed) and no other packages are installed, remove the index pattern if (!pkgName && installedPackages.length === 0) { try { @@ -140,8 +140,8 @@ export const getAllDatasetFieldsByType = async ( const datasetsPromises = packages.reduce>>((acc, pkg) => { if (pkg.datasets) { // filter out datasets by datasetType - const matchingDatasets = pkg.datasets.filter(dataset => dataset.type === datasetType); - matchingDatasets.forEach(dataset => acc.push(loadFieldsFromYaml(pkg, dataset.path))); + const matchingDatasets = pkg.datasets.filter((dataset) => dataset.type === datasetType); + matchingDatasets.forEach((dataset) => acc.push(loadFieldsFromYaml(pkg, dataset.path))); } return acc; }, []); @@ -329,7 +329,7 @@ export const flattenFields = (allFields: Fields): Fields => { // helper function to call flatten() and rename the fields const renameAndFlatten = (field: Field, fields: Fields, acc: Fields): Fields => { const flattenedFields = flatten(fields); - flattenedFields.forEach(nestedField => { + flattenedFields.forEach((nestedField) => { acc.push({ ...nestedField, name: `${field.name}.${nestedField.name}`, @@ -372,7 +372,7 @@ export const ensureDefaultIndices = async (callCluster: CallESAsCurrentUser) => // that no matching indices exist https://github.com/elastic/kibana/issues/62343 const logger = appContextService.getLogger(); return Promise.all( - Object.keys(IndexPatternType).map(async indexPattern => { + Object.keys(IndexPatternType).map(async (indexPattern) => { const defaultIndexPatternName = indexPattern + INDEX_PATTERN_PLACEHOLDER_SUFFIX; const indexExists = await callCluster('indices.exists', { index: defaultIndexPatternName }); if (!indexExists) { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts index 50d347c69cc24..c6f7a1f6b97aa 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts @@ -62,7 +62,7 @@ export async function getAssetsData( // Gather all asset data const assets = getAssets(packageInfo, filter, datasetName); - const entries: Registry.ArchiveEntry[] = assets.map(registryPath => { + const entries: Registry.ArchiveEntry[] = assets.map((registryPath) => { const archivePath = registryPathToArchivePath(registryPath); const buffer = Registry.getAsset(archivePath); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts index 6db08e344b3da..7d5e6d6e88387 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts @@ -26,8 +26,8 @@ export async function getPackages( } & Registry.SearchParams ) { const { savedObjectsClient } = options; - const registryItems = await Registry.fetchList({ category: options.category }).then(items => { - return items.map(item => + const registryItems = await Registry.fetchList({ category: options.category }).then((items) => { + return items.map((item) => Object.assign({}, item, { title: item.title || nameAsTitle(item.name) }) ); }); @@ -35,9 +35,11 @@ export async function getPackages( const packageSavedObjects = await getPackageSavedObjects(savedObjectsClient); // filter out any internal packages - const savedObjectsVisible = packageSavedObjects.saved_objects.filter(o => !o.attributes.internal); + const savedObjectsVisible = packageSavedObjects.saved_objects.filter( + (o) => !o.attributes.internal + ); const packageList = registryItems - .map(item => + .map((item) => createInstallableFrom( item, savedObjectsVisible.find(({ id }) => id === item.name) @@ -99,7 +101,7 @@ export async function getInstallationObject(options: { const { savedObjectsClient, pkgName } = options; return savedObjectsClient .get(PACKAGES_SAVED_OBJECT_TYPE, pkgName) - .catch(e => undefined); + .catch((e) => undefined); } export async function getInstallation(options: { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts index 79a5e98b9507d..dddb21bc4e075 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts @@ -140,7 +140,7 @@ export async function installPackage(options: { const toSaveESIndexPatterns = generateESIndexPatterns(registryPackageInfo.datasets); // get template refs to save - const installedTemplateRefs = installedTemplates.map(template => ({ + const installedTemplateRefs = installedTemplates.map((template) => ({ id: template.templateName, type: IngestAssetType.IndexTemplate, })); @@ -191,13 +191,13 @@ export async function installKibanaAssets(options: { // Only install Kibana assets during package installation. const kibanaAssetTypes = Object.values(KibanaAssetType); - const installationPromises = kibanaAssetTypes.map(async assetType => + const installationPromises = kibanaAssetTypes.map(async (assetType) => installKibanaSavedObjects({ savedObjectsClient, pkgName, pkgVersion, assetType }) ); // installKibanaSavedObjects returns AssetReference[], so .map creates AssetReference[][] // call .flat to flatten into one dimensional array - return Promise.all(installationPromises).then(results => results.flat()); + return Promise.all(installationPromises).then((results) => results.flat()); } export async function saveInstallationReferences(options: { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts index 23e63f0a89a5e..9b506a2d055a7 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts @@ -119,7 +119,7 @@ export async function deleteAssetsByType({ installedObjects: AssetReference[]; assetType: ElasticsearchAssetType; }) { - const toDelete = installedObjects.filter(asset => asset.type === assetType); + const toDelete = installedObjects.filter((asset) => asset.type === assetType); try { await deleteAssets(toDelete, savedObjectsClient, callCluster); } catch (err) { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts index feed2236f06eb..1f708c5edbcc7 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts @@ -22,7 +22,7 @@ export async function untarBuffer( const inflateStream = tar.list().on('entry', (entry: tar.FileStat) => { const path = entry.header.path || ''; if (!filter({ path })) return; - streamToBuffer(entry).then(entryBuffer => onEntry({ buffer: entryBuffer, path })); + streamToBuffer(entry).then((entryBuffer) => onEntry({ buffer: entryBuffer, path })); }); return new Promise((resolve, reject) => { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts index e174c5f2e4d72..97d6f7b40a588 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts @@ -23,7 +23,7 @@ export function streamToString(stream: NodeJS.ReadableStream): Promise { export function streamToBuffer(stream: NodeJS.ReadableStream): Promise { return new Promise((resolve, reject) => { const chunks: Buffer[] = []; - stream.on('data', chunk => chunks.push(Buffer.from(chunk))); + stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); stream.on('end', () => resolve(Buffer.concat(chunks))); stream.on('error', reject); }); diff --git a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts index 0bb68c40bc580..50421070e1202 100644 --- a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts +++ b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts @@ -6,7 +6,7 @@ import { InstallTemplateFunction } from './types'; -export const linuxInstallTemplate: InstallTemplateFunction = variables => { +export const linuxInstallTemplate: InstallTemplateFunction = (variables) => { const artifact = `elastic-agent-${variables.kibanaVersion}-linux-x86_64`; return `#!/bin/sh diff --git a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts index 11bb58d184d33..921c31ebe238f 100644 --- a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts +++ b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts @@ -6,7 +6,7 @@ import { InstallTemplateFunction } from './types'; -export const macosInstallTemplate: InstallTemplateFunction = variables => { +export const macosInstallTemplate: InstallTemplateFunction = (variables) => { const artifact = `elastic-agent-${variables.kibanaVersion}-darwin-x86_64`; return `#!/bin/sh diff --git a/x-pack/plugins/ingest_manager/server/services/output.ts b/x-pack/plugins/ingest_manager/server/services/output.ts index ce6f1f2e27130..618fefd80edaf 100644 --- a/x-pack/plugins/ingest_manager/server/services/output.ts +++ b/x-pack/plugins/ingest_manager/server/services/output.ts @@ -122,7 +122,7 @@ class OutputService { }); return { - items: outputs.saved_objects.map(outputSO => { + items: outputs.saved_objects.map((outputSO) => { return { id: outputSO.id, ...outputSO.attributes, diff --git a/x-pack/plugins/ingest_manager/server/services/setup.ts b/x-pack/plugins/ingest_manager/server/services/setup.ts index 6481b0753bab5..b6e1bca7b9d05 100644 --- a/x-pack/plugins/ingest_manager/server/services/setup.ts +++ b/x-pack/plugins/ingest_manager/server/services/setup.ts @@ -81,7 +81,7 @@ export async function setupIngestManager( } for (const installedPackage of installedPackages) { const packageShouldBeInstalled = DEFAULT_AGENT_CONFIGS_PACKAGES.some( - packageName => installedPackage.name === packageName + (packageName) => installedPackage.name === packageName ); if (!packageShouldBeInstalled) { continue; diff --git a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts index 0f9745981c18b..03ffe361bb5a6 100644 --- a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts +++ b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts @@ -67,10 +67,7 @@ const createActions = (testBed: TestBed) => { clickActionMenu(pipelineName); - component - .find('.euiContextMenuItem') - .at(actions.indexOf(action)) - .simulate('click'); + component.find('.euiContextMenuItem').at(actions.indexOf(action)).simulate('click'); }; return { diff --git a/x-pack/plugins/ingest_pipelines/public/application/app.tsx b/x-pack/plugins/ingest_pipelines/public/application/app.tsx index 98b49bafd6ed6..f4ac640722120 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/app.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/app.tsx @@ -50,7 +50,7 @@ export const App: FunctionComponent = () => { return ( `cluster.${privilege}`)} + privileges={APP_CLUSTER_REQUIRED_PRIVILEGES.map((privilege) => `cluster.${privilege}`)} > {({ isLoading, hasPrivileges, privilegesMissing }) => { if (isLoading) { diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx index d9cbee248a788..73bc1cfaa2cf5 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx @@ -127,7 +127,7 @@ export const PipelineForm: React.FunctionComponent = ({ setIsRequestVisible(prevIsRequestVisible => !prevIsRequestVisible)} + onClick={() => setIsRequestVisible((prevIsRequestVisible) => !prevIsRequestVisible)} > {isRequestVisible ? ( = ({ {/* ES request flyout */} {isRequestVisible ? ( setIsRequestVisible(prevIsRequestVisible => !prevIsRequestVisible)} + closeFlyout={() => setIsRequestVisible((prevIsRequestVisible) => !prevIsRequestVisible)} /> ) : null} @@ -155,7 +155,7 @@ export const PipelineForm: React.FunctionComponent = ({ {isTestingPipeline ? ( { - setIsTestingPipeline(prevIsTestingPipeline => !prevIsTestingPipeline); + setIsTestingPipeline((prevIsTestingPipeline) => !prevIsTestingPipeline); }} /> ) : null} diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx index dfdd9ea2f748e..9fb5ab55a34ce 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx @@ -60,7 +60,7 @@ export const PipelineFormFields: React.FunctionComponent = ({ /> } checked={isVersionVisible} - onChange={e => setIsVersionVisible(e.target.checked)} + onChange={(e) => setIsVersionVisible(e.target.checked)} data-test-subj="versionToggle" /> @@ -205,7 +205,7 @@ export const PipelineFormFields: React.FunctionComponent = ({ /> } checked={isOnFailureEditorVisible} - onChange={e => setIsOnFailureEditorVisible(e.target.checked)} + onChange={(e) => setIsOnFailureEditorVisible(e.target.checked)} data-test-subj="onFailureToggle" /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx index 57abea2309aa1..e6482a9fc12c2 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx @@ -9,7 +9,9 @@ import React from 'react'; import { PipelineForm as PipelineFormUI, PipelineFormProps } from './pipeline_form'; import { TestConfigContextProvider } from './test_config_context'; -export const PipelineFormProvider: React.FunctionComponent = passThroughProps => { +export const PipelineFormProvider: React.FunctionComponent = ( + passThroughProps +) => { return ( diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx index ea96ead9a3aab..da5e6cf77364c 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx @@ -154,7 +154,7 @@ export const PipelineTestFlyout: React.FunctionComponent !executeOutput && tabId === 'output'} + getIsDisabled={(tabId) => !executeOutput && tabId === 'output'} /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx index f720b80122702..4d378db169574 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx @@ -44,7 +44,7 @@ export const Tabs: React.FunctionComponent = ({ return ( - {tabs.map(tab => ( + {tabs.map((tab) => ( onTabChange(tab.id)} isSelected={tab.id === selectedTab} diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx index bcaf186e62129..f7c349a379c68 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx @@ -76,7 +76,7 @@ export const OutputTab: React.FunctionComponent = ({ /> } checked={cachedVerbose} - onChange={e => onEnableVerbose(e.target.checked)} + onChange={(e) => onEnableVerbose(e.target.checked)} /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx index e122307ca9485..5435f43a78acf 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx @@ -104,7 +104,7 @@ export const pipelineFormSchema: FormSchema = { }} /> ), - serializer: value => { + serializer: (value) => { const result = parseJson(value); // If an empty array was passed, strip out this value entirely. if (!result.length) { @@ -115,7 +115,7 @@ export const pipelineFormSchema: FormSchema = { deserializer: stringifyJson, validations: [ { - validator: validationArg => { + validator: (validationArg) => { if (!validationArg.value) { return; } diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx index b3b1217caf834..4c857dc9c74f7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx @@ -21,7 +21,7 @@ export interface ParamProps { * This section is a wrapper around the create section where we receive a pipeline name * to load and set as the source pipeline for the {@link PipelinesCreate} form. */ -export const PipelinesClone: FunctionComponent> = props => { +export const PipelinesClone: FunctionComponent> = (props) => { const { sourceName } = props.match.params; const { services } = useKibana(); diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx index c7736a6c19ba1..390863146fac4 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx @@ -114,7 +114,7 @@ export const PipelineDeleteModal = ({

            - {pipelinesToDelete.map(name => ( + {pipelinesToDelete.map((name) => (
          • {name}
          • ))}
          diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx index 39789bb38ed41..3122aa6da7396 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx @@ -89,7 +89,7 @@ export const PipelineDetailsFlyout: FunctionComponent = ({ defaultMessage: 'Manage pipeline', } )} - onClick={() => setShowPopover(previousBool => !previousBool)} + onClick={() => setShowPopover((previousBool) => !previousBool)} iconType="arrowUp" iconSide="right" fill diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx index 948290b169134..ccb50376dddb7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx @@ -61,7 +61,7 @@ export const PipelinesList: React.FunctionComponent = ({ useEffect(() => { if (pipelineNameFromLocation && data?.length) { - const pipeline = data.find(p => p.name === pipelineNameFromLocation); + const pipeline = data.find((p) => p.name === pipelineNameFromLocation); setSelectedPipeline(pipeline); setShowFlyout(true); } @@ -201,7 +201,7 @@ export const PipelinesList: React.FunctionComponent = ({ {renderFlyout()} {pipelinesToDelete?.length > 0 ? ( { + callback={(deleteResponse) => { if (deleteResponse?.hasDeletedPipelines) { // reload pipelines list sendRequest(); diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx index e5c708b5c0e53..541a2b486b5a7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx @@ -57,7 +57,7 @@ export const PipelineTable: FunctionComponent = ({ selection.length > 0 ? ( onDeletePipelineClick(selection.map(pipeline => pipeline.name))} + onClick={() => onDeletePipelineClick(selection.map((pipeline) => pipeline.name))} color="danger" > = ({ values={{ count: selection.length }} /> - ) : ( - undefined - ), + ) : undefined, toolsRight: [ encodeURIComponent(name)).join(',')}`, + path: `${API_BASE_PATH}/${names.map((name) => encodeURIComponent(name)).join(',')}`, method: 'delete', }); diff --git a/x-pack/plugins/ingest_pipelines/public/plugin.ts b/x-pack/plugins/ingest_pipelines/public/plugin.ts index d537f8d68d7e4..2c1ffdd31aafe 100644 --- a/x-pack/plugins/ingest_pipelines/public/plugin.ts +++ b/x-pack/plugins/ingest_pipelines/public/plugin.ts @@ -27,7 +27,7 @@ export class IngestPipelinesPlugin implements Plugin { title: i18n.translate('xpack.ingestPipelines.appTitle', { defaultMessage: 'Ingest Node Pipelines', }), - mount: async params => { + mount: async (params) => { const { mountManagementSection } = await import('./application/mount_management_section'); return await mountManagementSection(coreSetup, params); diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts index 4664b49a08a50..8ef9387010eb6 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts @@ -31,10 +31,10 @@ export const registerDeleteRoute = ({ router, license }: RouteDependencies): voi }; await Promise.all( - pipelineNames.map(pipelineName => { + pipelineNames.map((pipelineName) => { return callAsCurrentUser('ingest.deletePipeline', { id: pipelineName }) .then(() => response.itemsDeleted.push(pipelineName)) - .catch(e => + .catch((e) => response.errors.push({ name: pipelineName, error: e, diff --git a/x-pack/plugins/ingest_pipelines/server/services/license.ts b/x-pack/plugins/ingest_pipelines/server/services/license.ts index 0a4748bd0ace0..9b68acd073c4a 100644 --- a/x-pack/plugins/ingest_pipelines/server/services/license.ts +++ b/x-pack/plugins/ingest_pipelines/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/lens/public/app_plugin/app.test.tsx b/x-pack/plugins/lens/public/app_plugin/app.test.tsx index 0608c978ad0dc..1762965478292 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.test.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.test.tsx @@ -133,8 +133,8 @@ describe('Lens App', () => { }, }, indexPatterns: { - get: jest.fn(id => { - return new Promise(resolve => resolve({ id })); + get: jest.fn((id) => { + return new Promise((resolve) => resolve({ id })); }), }, }, @@ -176,7 +176,7 @@ describe('Lens App', () => { core = coreMock.createStart({ basePath: '/testbasepath' }); core.uiSettings.get.mockImplementation( - jest.fn(type => { + jest.fn((type) => { if (type === 'timepicker:timeDefaults') { return { from: 'now-7d', to: 'now' }; } else if (type === 'search:queryLanguage') { @@ -391,7 +391,7 @@ describe('Lens App', () => { return (inst .find('[data-test-subj="lnsApp_topNav"]') .prop('config') as TopNavMenuData[]).find( - button => button.testId === 'lnsApp_saveButton' + (button) => button.testId === 'lnsApp_saveButton' )!; } diff --git a/x-pack/plugins/lens/public/app_plugin/app.tsx b/x-pack/plugins/lens/public/app_plugin/app.tsx index 718f49413a082..a77fbbb597564 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.tsx @@ -101,7 +101,7 @@ export function App({ const filterSubscription = data.query.filterManager.getUpdates$().subscribe({ next: () => { - setState(s => ({ ...s, filters: data.query.filterManager.getFilters() })); + setState((s) => ({ ...s, filters: data.query.filterManager.getFilters() })); trackUiEvent('app_filters_updated'); }, }); @@ -109,7 +109,7 @@ export function App({ const timeSubscription = data.query.timefilter.timefilter.getTimeUpdate$().subscribe({ next: () => { const currentRange = data.query.timefilter.timefilter.getTime(); - setState(s => ({ + setState((s) => ({ ...s, dateRange: { fromDate: currentRange.from, @@ -130,7 +130,7 @@ export function App({ core.chrome.setBreadcrumbs([ { href: core.http.basePath.prepend(`/app/visualize#/`), - onClick: e => { + onClick: (e) => { core.application.navigateToApp('visualize', { path: '/' }); e.preventDefault(); }, @@ -148,19 +148,19 @@ export function App({ useEffect(() => { if (docId && (!state.persistedDoc || state.persistedDoc.id !== docId)) { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); docStorage .load(docId) - .then(doc => { + .then((doc) => { getAllIndexPatterns( doc.state.datasourceMetaData.filterableIndexPatterns, data.indexPatterns, core.notifications ) - .then(indexPatterns => { + .then((indexPatterns) => { // Don't overwrite any pinned filters data.query.filterManager.setAppFilters(doc.state.filters); - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, persistedDoc: doc, @@ -170,13 +170,13 @@ export function App({ })); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); redirectTo(); }); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); core.notifications.toasts.addDanger( i18n.translate('xpack.lens.app.docLoadingError', { @@ -229,7 +229,7 @@ export function App({ .then(({ id }) => { // Prevents unnecessary network request and disables save button const newDoc = { ...doc, id }; - setState(s => ({ + setState((s) => ({ ...s, isSaveModalVisible: false, persistedDoc: newDoc, @@ -239,7 +239,7 @@ export function App({ redirectTo(id, saveProps.returnToOrigin, state.originatingApp, newlyCreated); } }) - .catch(e => { + .catch((e) => { // eslint-disable-next-line no-console console.dir(e); trackUiEvent('save_failed'); @@ -248,7 +248,7 @@ export function App({ defaultMessage: 'Error saving document', }) ); - setState(s => ({ ...s, isSaveModalVisible: false })); + setState((s) => ({ ...s, isSaveModalVisible: false })); }); }; @@ -311,7 +311,7 @@ export function App({ emphasize: !state.originatingApp || !lastKnownDoc?.id, run: () => { if (isSaveable && lastKnownDoc) { - setState(s => ({ ...s, isSaveModalVisible: true })); + setState((s) => ({ ...s, isSaveModalVisible: true })); } }, testId: 'lnsApp_saveButton', @@ -320,7 +320,7 @@ export function App({ ]} data-test-subj="lnsApp_topNav" screenTitle={'lens'} - onQuerySubmit={payload => { + onQuerySubmit={(payload) => { const { dateRange, query } = payload; if ( @@ -333,7 +333,7 @@ export function App({ trackUiEvent('app_query_change'); } - setState(s => ({ + setState((s) => ({ ...s, dateRange: { fromDate: dateRange.from, @@ -350,14 +350,14 @@ export function App({ showFilterBar={true} showSaveQuery={core.application.capabilities.visualize.saveQuery as boolean} savedQuery={state.savedQuery} - onSaved={savedQuery => { - setState(s => ({ ...s, savedQuery })); + onSaved={(savedQuery) => { + setState((s) => ({ ...s, savedQuery })); }} - onSavedQueryUpdated={savedQuery => { + onSavedQueryUpdated={(savedQuery) => { const savedQueryFilters = savedQuery.attributes.filters || []; const globalFilters = data.query.filterManager.getGlobalFilters(); data.query.filterManager.setFilters([...globalFilters, ...savedQueryFilters]); - setState(s => ({ + setState((s) => ({ ...s, savedQuery: { ...savedQuery }, // Shallow query for reference issues dateRange: savedQuery.attributes.timefilter @@ -370,7 +370,7 @@ export function App({ }} onClearSavedQuery={() => { data.query.filterManager.setFilters(data.query.filterManager.getGlobalFilters()); - setState(s => ({ + setState((s) => ({ ...s, savedQuery: undefined, filters: data.query.filterManager.getGlobalFilters(), @@ -401,7 +401,7 @@ export function App({ onError, onChange: ({ filterableIndexPatterns, doc }) => { if (!_.isEqual(state.persistedDoc, doc)) { - setState(s => ({ ...s, lastKnownDoc: doc })); + setState((s) => ({ ...s, lastKnownDoc: doc })); } // Update the cached index patterns if the user made a change to any of them @@ -409,16 +409,16 @@ export function App({ state.indexPatternsForTopNav.length !== filterableIndexPatterns.length || filterableIndexPatterns.find( ({ id }) => - !state.indexPatternsForTopNav.find(indexPattern => indexPattern.id === id) + !state.indexPatternsForTopNav.find((indexPattern) => indexPattern.id === id) ) ) { getAllIndexPatterns( filterableIndexPatterns, data.indexPatterns, core.notifications - ).then(indexPatterns => { + ).then((indexPatterns) => { if (indexPatterns) { - setState(s => ({ ...s, indexPatternsForTopNav: indexPatterns })); + setState((s) => ({ ...s, indexPatternsForTopNav: indexPatterns })); } }); } @@ -430,8 +430,8 @@ export function App({ {lastKnownDoc && state.isSaveModalVisible && ( runSave(props)} - onClose={() => setState(s => ({ ...s, isSaveModalVisible: false }))} + onSave={(props) => runSave(props)} + onClose={() => setState((s) => ({ ...s, isSaveModalVisible: false }))} documentInfo={{ id: lastKnownDoc.id, title: lastKnownDoc.title || '', diff --git a/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx b/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx index ea8eeaee8b2f0..ac43593213687 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx @@ -66,7 +66,7 @@ describe('datatable_expression', () => { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn()} /> @@ -87,16 +87,13 @@ describe('datatable_expression', () => { }, }} args={args} - formatFactory={x => x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn(() => ({ type: 'buckets' } as IAggType))} /> ); - wrapper - .find('[data-test-subj="lensDatatableFilterOut"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lensDatatableFilterOut"]').first().simulate('click'); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -125,16 +122,13 @@ describe('datatable_expression', () => { }, }} args={args} - formatFactory={x => x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn(() => ({ type: 'buckets' } as IAggType))} /> ); - wrapper - .find('[data-test-subj="lensDatatableFilterFor"]') - .at(3) - .simulate('click'); + wrapper.find('[data-test-subj="lensDatatableFilterFor"]').at(3).simulate('click'); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -166,9 +160,9 @@ describe('datatable_expression', () => { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} - getType={jest.fn(type => + getType={jest.fn((type) => type === 'count' ? ({ type: 'metrics' } as IAggType) : ({ type: 'buckets' } as IAggType) )} /> diff --git a/x-pack/plugins/lens/public/datatable_visualization/expression.tsx b/x-pack/plugins/lens/public/datatable_visualization/expression.tsx index d897290d5a13c..1fd01654d8149 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/expression.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/expression.tsx @@ -156,7 +156,7 @@ export function DatatableComponent(props: DatatableRenderProps) { const [firstTable] = Object.values(props.data.tables); const formatters: Record> = {}; - firstTable.columns.forEach(column => { + firstTable.columns.forEach((column) => { formatters[column.id] = props.formatFactory(column.formatHint); }); @@ -166,7 +166,7 @@ export function DatatableComponent(props: DatatableRenderProps) { const isDateHistogram = col.meta?.type === 'date_histogram'; const timeFieldName = negate && isDateHistogram ? undefined : col?.meta?.aggConfigParams?.field; - const rowIndex = firstTable.rows.findIndex(row => row[field] === value); + const rowIndex = firstTable.rows.findIndex((row) => row[field] === value); const data: LensFilterEvent['data'] = { negate, @@ -186,15 +186,17 @@ export function DatatableComponent(props: DatatableRenderProps) { ); const bucketColumns = firstTable.columns - .filter(col => { + .filter((col) => { return col?.meta?.type && props.getType(col.meta.type)?.type === 'buckets'; }) - .map(col => col.id); + .map((col) => col.id); const isEmpty = firstTable.rows.length === 0 || (bucketColumns.length && - firstTable.rows.every(row => bucketColumns.every(col => typeof row[col] === 'undefined'))); + firstTable.rows.every((row) => + bucketColumns.every((col) => typeof row[col] === 'undefined') + )); if (isEmpty) { return ; @@ -207,10 +209,10 @@ export function DatatableComponent(props: DatatableRenderProps) { data-test-subj="lnsDataTable" tableLayout="auto" columns={props.args.columns.columnIds - .map(field => { - const col = firstTable.columns.find(c => c.id === field); + .map((field) => { + const col = firstTable.columns.find((c) => c.id === field); const filterable = bucketColumns.includes(field); - const colIndex = firstTable.columns.findIndex(c => c.id === field); + const colIndex = firstTable.columns.findIndex((c) => c.id === field); return { field, name: (col && col.name) || '', diff --git a/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx b/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx index ed0512ba220eb..e4b371143594a 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx @@ -46,12 +46,12 @@ export const datatableVisualization: Visualization< }, getLayerIds(state) { - return state.layers.map(l => l.layerId); + return state.layers.map((l) => l.layerId); }, clearLayer(state) { return { - layers: state.layers.map(l => newLayerState(l.layerId)), + layers: state.layers.map((l) => newLayerState(l.layerId)), }; }, @@ -74,7 +74,7 @@ export const datatableVisualization: Visualization< ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getSuggestions({ table, @@ -101,7 +101,7 @@ export const datatableVisualization: Visualization< operations: table.label || table.columns - .map(col => col.operation.label) + .map((col) => col.operation.label) .join( i18n.translate('xpack.lens.datatable.conjunctionSign', { defaultMessage: ' & ', @@ -121,7 +121,7 @@ export const datatableVisualization: Visualization< layers: [ { layerId: table.layerId, - columns: table.columns.map(col => col.columnId), + columns: table.columns.map((col) => col.columnId), }, ], }, @@ -133,7 +133,7 @@ export const datatableVisualization: Visualization< }, getConfiguration({ state, frame, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); + const layer = state.layers.find((l) => l.layerId === layerId); if (!layer) { return { groups: [] }; } @@ -163,7 +163,7 @@ export const datatableVisualization: Visualization< setDimension({ prevState, layerId, columnId }) { return { ...prevState, - layers: prevState.layers.map(l => { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId || l.columns.includes(columnId)) { return l; } @@ -174,11 +174,11 @@ export const datatableVisualization: Visualization< removeDimension({ prevState, layerId, columnId }) { return { ...prevState, - layers: prevState.layers.map(l => + layers: prevState.layers.map((l) => l.layerId === layerId ? { ...l, - columns: l.columns.filter(c => c !== columnId), + columns: l.columns.filter((c) => c !== columnId), } : l ), @@ -189,7 +189,7 @@ export const datatableVisualization: Visualization< const layer = state.layers[0]; const datasource = frame.datasourceLayers[layer.layerId]; const operations = layer.columns - .map(columnId => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) + .map((columnId) => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) .filter((o): o is { columnId: string; operation: Operation } => !!o.operation); return { @@ -207,7 +207,7 @@ export const datatableVisualization: Visualization< type: 'function', function: 'lens_datatable_columns', arguments: { - columnIds: operations.map(o => o.columnId), + columnIds: operations.map((o) => o.columnId), }, }, ], diff --git a/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx b/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx index 447d9118c2930..929dd8e434afe 100644 --- a/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx +++ b/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx @@ -25,7 +25,7 @@ describe('debouncedComponent', () => { component.setProps({ title: 'yall' }); expect(component.text()).toEqual('there'); await act(async () => { - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); }); expect(component.text()).toEqual('yall'); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx index 157a871e202f7..648bb5c03cb39 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx @@ -22,7 +22,7 @@ describe('chart_switch', () => { return { ...createMockVisualization(), id, - getVisualizationTypeId: jest.fn(_state => id), + getVisualizationTypeId: jest.fn((_state) => id), visualizationTypes: [ { icon: 'empty', @@ -33,7 +33,7 @@ describe('chart_switch', () => { initialize: jest.fn((_frame, state?: unknown) => { return state || `${id} initial state`; }), - getSuggestions: jest.fn(options => { + getSuggestions: jest.fn((options) => { return [ { score: 1, @@ -70,8 +70,8 @@ describe('chart_switch', () => { label: 'C3', }, ], - getVisualizationTypeId: jest.fn(state => state.type), - getSuggestions: jest.fn(options => { + getVisualizationTypeId: jest.fn((state) => state.type), + getSuggestions: jest.fn((options) => { if (options.subVisualizationId === 'subvisC2') { return []; } @@ -144,18 +144,12 @@ describe('chart_switch', () => { } function showFlyout(component: ReactWrapper) { - component - .find('[data-test-subj="lnsChartSwitchPopover"]') - .first() - .simulate('click'); + component.find('[data-test-subj="lnsChartSwitchPopover"]').first().simulate('click'); } function switchTo(subType: string, component: ReactWrapper) { showFlyout(component); - component - .find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`) - .first() - .simulate('click'); + component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).first().simulate('click'); } function getMenuItem(subType: string, component: ReactWrapper) { @@ -566,7 +560,7 @@ describe('chart_switch', () => { showFlyout(component); const allDisplayed = ['visA', 'visB', 'subvisC1', 'subvisC2', 'subvisC3'].every( - subType => component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).length > 0 + (subType) => component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).length > 0 ); expect(allDisplayed).toBeTruthy(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx index 81eb82dfdbab4..e212cb70d1855 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx @@ -172,14 +172,14 @@ export function ChartSwitch(props: Props) { () => flyoutOpen && flatten( - Object.values(props.visualizationMap).map(v => - v.visualizationTypes.map(t => ({ + Object.values(props.visualizationMap).map((v) => + v.visualizationTypes.map((t) => ({ visualizationId: v.id, ...t, icon: t.largeIcon || t.icon, })) ) - ).map(visualizationType => ({ + ).map((visualizationType) => ({ ...visualizationType, selection: getSelection(visualizationType.visualizationId, visualizationType.id), })), @@ -223,7 +223,7 @@ export function ChartSwitch(props: Props) { })} - {(visualizationTypes || []).map(v => ( + {(visualizationTypes || []).map((v) => ( {v.label}} @@ -269,7 +269,7 @@ function getTopSuggestion( activeVisualizationId: props.visualizationId, visualizationState: props.visualizationState, subVisualizationId, - }).filter(suggestion => { + }).filter((suggestion) => { // don't use extended versions of current data table on switching between visualizations // to avoid confusing the user. return ( @@ -282,8 +282,8 @@ function getTopSuggestion( // charts since that allows you to switch from A to B and back // to A with the greatest chance of preserving your original state. return ( - suggestions.find(s => s.changeType === 'unchanged') || - suggestions.find(s => s.changeType === 'reduced') || + suggestions.find((s) => s.changeType === 'unchanged') || + suggestions.find((s) => s.changeType === 'reduced') || suggestions[0] ); } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx index e5d3e93258c0a..0d86a051b0faa 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx @@ -79,7 +79,7 @@ function LayerPanels( props.dispatch({ type: 'UPDATE_STATE', subType: 'UPDATE_ALL_STATES', - updater: prevState => { + updater: (prevState) => { return { ...prevState, datasourceStates: { @@ -104,7 +104,7 @@ function LayerPanels( return ( - {layerIds.map(layerId => ( + {layerIds.map((layerId) => ( + updater: (state) => removeLayer({ activeVisualization, layerId, @@ -157,7 +157,7 @@ function LayerPanels( dispatch({ type: 'UPDATE_STATE', subType: 'ADD_LAYER', - updater: state => + updater: (state) => appendLayer({ activeVisualization, generateId, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx index 36db13b74ac4f..f89b6ef32d3f7 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx @@ -26,7 +26,7 @@ export function DimensionPopover({ trigger: React.ReactElement; panel: React.ReactElement; }) { - const noMatch = popoverState.isOpen ? !groups.some(d => d.accessors.includes(accessor)) : false; + const noMatch = popoverState.isOpen ? !groups.some((d) => d.accessors.includes(accessor)) : false; return ( id === opts.layerId); + .every((id) => id === opts.layerId); trackUiEvent(isOnlyLayer ? 'layer_cleared' : 'layer_removed'); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx index 81476e8fa3708..814b7fc644c9c 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx @@ -81,7 +81,7 @@ export function LayerPanel( }; const { groups } = activeVisualization.getConfiguration(layerVisualizationConfigProps); - const isEmptyLayer = !groups.some(d => d.accessors.length > 0); + const isEmptyLayer = !groups.some((d) => d.accessors.length > 0); return ( @@ -120,9 +120,9 @@ export function LayerPanel( const removed = datasourcePublicAPI .getTableSpec() .map(({ columnId }) => columnId) - .filter(columnId => !nextTable.has(columnId)); + .filter((columnId) => !nextTable.has(columnId)); let nextVisState = props.visualizationState; - removed.forEach(columnId => { + removed.forEach((columnId) => { nextVisState = activeVisualization.removeDimension({ layerId, columnId, @@ -158,7 +158,7 @@ export function LayerPanel( } > <> - {group.accessors.map(accessor => ( + {group.accessors.map((accessor) => ( { + onDrop={(droppedItem) => { layerDatasource.onDrop({ ...layerDatasourceDropProps, droppedItem, @@ -268,7 +268,7 @@ export function LayerPanel( filterOperations: group.filterOperations, }) } - onDrop={droppedItem => { + onDrop={(droppedItem) => { const dropSuccess = layerDatasource.onDrop({ ...layerDatasourceDropProps, droppedItem, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx index cd0aee732793e..afb2719f28e89 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx @@ -27,7 +27,7 @@ interface DataPanelWrapperProps { export const DataPanelWrapper = memo((props: DataPanelWrapperProps) => { const setDatasourceState: StateSetter = useMemo( - () => updater => { + () => (updater) => { props.dispatch({ type: 'UPDATE_DATASOURCE_STATE', updater, @@ -78,7 +78,7 @@ export const DataPanelWrapper = memo((props: DataPanelWrapperProps) => { title={i18n.translate('xpack.lens.dataPanelWrapper.switchDatasource', { defaultMessage: 'Switch to datasource', })} - items={Object.keys(props.datasourceMap).map(datasourceId => ( + items={Object.keys(props.datasourceMap).map((datasourceId) => ( { testDatasource: { ...mockDatasource, initialize: () => - new Promise(resolve => { + new Promise((resolve) => { databaseInitialized = resolve; }), }, @@ -474,9 +474,11 @@ describe('editor_frame', () => { it('should render individual expression for each given layer', async () => { mockDatasource.toExpression.mockReturnValue('datasource'); mockDatasource2.toExpression.mockImplementation((_state, layerId) => `datasource_${layerId}`); - mockDatasource.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource.initialize.mockImplementation((initialState) => Promise.resolve(initialState)); mockDatasource.getLayers.mockReturnValue(['first']); - mockDatasource2.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource2.initialize.mockImplementation((initialState) => + Promise.resolve(initialState) + ); mockDatasource2.getLayers.mockReturnValue(['second', 'third']); await act(async () => { @@ -772,9 +774,11 @@ describe('editor_frame', () => { }); it('should create a separate datasource public api for each layer', async () => { - mockDatasource.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource.initialize.mockImplementation((initialState) => Promise.resolve(initialState)); mockDatasource.getLayers.mockReturnValue(['first']); - mockDatasource2.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource2.initialize.mockImplementation((initialState) => + Promise.resolve(initialState) + ); mockDatasource2.getLayers.mockReturnValue(['second', 'third']); const datasource1State = { datasource1: '' }; @@ -872,10 +876,7 @@ describe('editor_frame', () => { function switchTo(subType: string) { act(() => { - instance - .find('[data-test-subj="lnsChartSwitchPopover"]') - .last() - .simulate('click'); + instance.find('[data-test-subj="lnsChartSwitchPopover"]').last().simulate('click'); }); instance.update(); @@ -1149,7 +1150,7 @@ describe('editor_frame', () => { instance .find('[data-test-subj="lnsSuggestion"]') .find(EuiPanel) - .map(el => el.parents(EuiToolTip).prop('content')) + .map((el) => el.parents(EuiToolTip).prop('content')) ).toEqual([ 'Current', 'Suggestion1', @@ -1200,10 +1201,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + instance.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(1); @@ -1266,10 +1264,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find('[data-test-subj="lnsWorkspace"]') - .last() - .simulate('drop'); + instance.find('[data-test-subj="lnsWorkspace"]').last().simulate('drop'); }); expect(mockVisualization.getConfiguration).toHaveBeenCalledWith( @@ -1340,10 +1335,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find(DragDrop) - .filter('[data-test-subj="mockVisA"]') - .prop('onDrop')!({ + instance.find(DragDrop).filter('[data-test-subj="mockVisA"]').prop('onDrop')!({ indexPatternId: '1', field: {}, }); @@ -1439,10 +1431,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find(DragDrop) - .filter('[data-test-subj="lnsWorkspace"]') - .prop('onDrop')!({ + instance.find(DragDrop).filter('[data-test-subj="lnsWorkspace"]').prop('onDrop')!({ indexPatternId: '1', field: {}, }); @@ -1464,7 +1453,7 @@ describe('editor_frame', () => { const onChange = jest.fn(); mockDatasource.initialize.mockReturnValue( - new Promise(resolve => { + new Promise((resolve) => { resolver = resolve; }) ); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx index 06d417ad18d54..90405b98afe65 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx @@ -73,7 +73,7 @@ export function EditorFrame(props: EditorFrameProps) { ) { datasource .initialize(state.datasourceStates[datasourceId].state || undefined) - .then(datasourceState => { + .then((datasourceState) => { if (!isUnmounted) { dispatch({ type: 'UPDATE_DATASOURCE_STATE', @@ -93,13 +93,13 @@ export function EditorFrame(props: EditorFrameProps) { const datasourceLayers: Record = {}; Object.keys(props.datasourceMap) - .filter(id => state.datasourceStates[id] && !state.datasourceStates[id].isLoading) - .forEach(id => { + .filter((id) => state.datasourceStates[id] && !state.datasourceStates[id].isLoading) + .forEach((id) => { const datasourceState = state.datasourceStates[id].state; const datasource = props.datasourceMap[id]; const layers = datasource.getLayers(datasourceState); - layers.forEach(layer => { + layers.forEach((layer) => { datasourceLayers[layer] = props.datasourceMap[id].getPublicAPI({ state: datasourceState, layerId: layer, @@ -140,7 +140,7 @@ export function EditorFrame(props: EditorFrameProps) { }); } - layerIds.forEach(layerId => { + layerIds.forEach((layerId) => { const layerDatasourceId = Object.entries(props.datasourceMap).find( ([datasourceId, datasource]) => state.datasourceStates[datasourceId] && diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts index 9d4f8587577a3..ee28ccfe1bf53 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts @@ -25,7 +25,7 @@ export function prependDatasourceExpression( const state = datasourceStates[datasourceId].state; const layers = datasource.getLayers(datasourceStates[datasourceId].state); - layers.forEach(layerId => { + layers.forEach((layerId) => { const result = datasource.toExpression(state, layerId); if (result) { datasourceExpressions.push([layerId, result]); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts index 9c7ed265f3539..d72e5c57ce56e 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts @@ -10,12 +10,12 @@ import { esFilters, IIndexPattern, IFieldType } from '../../../../../../src/plug describe('save editor frame state', () => { const mockVisualization = createMockVisualization(); - mockVisualization.getPersistableState.mockImplementation(x => x); + mockVisualization.getPersistableState.mockImplementation((x) => x); const mockDatasource = createMockDatasource('a'); const mockIndexPattern = ({ id: 'indexpattern' } as unknown) as IIndexPattern; const mockField = ({ name: '@timestamp' } as unknown) as IFieldType; - mockDatasource.getPersistableState.mockImplementation(x => x); + mockDatasource.getPersistableState.mockImplementation((x) => x); const saveArgs: Props = { activeDatasources: { indexpattern: mockDatasource, @@ -46,12 +46,12 @@ describe('save editor frame state', () => { it('transforms from internal state to persisted doc format', async () => { const datasource = createMockDatasource('a'); - datasource.getPersistableState.mockImplementation(state => ({ + datasource.getPersistableState.mockImplementation((state) => ({ stuff: `${state}_datasource_persisted`, })); const visualization = createMockVisualization(); - visualization.getPersistableState.mockImplementation(state => ({ + visualization.getPersistableState.mockImplementation((state) => ({ things: `${state}_vis_persisted`, })); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts index 949ae1f43448e..263f7cd65f43d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts @@ -73,7 +73,7 @@ export function getSuggestions({ return (field ? datasource.getDatasourceSuggestionsForField(datasourceState, field) : datasource.getDatasourceSuggestionsFromCurrentState(datasourceState) - ).map(suggestion => ({ ...suggestion, datasourceId })); + ).map((suggestion) => ({ ...suggestion, datasourceId })); }) ); @@ -82,7 +82,7 @@ export function getSuggestions({ return _.flatten( Object.entries(visualizationMap).map(([visualizationId, visualization]) => _.flatten( - datasourceTableSuggestions.map(datasourceSuggestion => { + datasourceTableSuggestions.map((datasourceSuggestion) => { const table = datasourceSuggestion.table; const currentVisualizationState = visualizationId === activeVisualizationId ? visualizationState : undefined; diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx index 240bdff40b51c..6b0f0338d4015 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx @@ -95,7 +95,7 @@ describe('suggestion_panel', () => { wrapper .find('[data-test-subj="lnsSuggestion"]') .find(EuiPanel) - .map(el => el.parents(EuiToolTip).prop('content')) + .map((el) => el.parents(EuiToolTip).prop('content')) ).toEqual(['Current', 'Suggestion1', 'Suggestion2']); }); @@ -157,39 +157,27 @@ describe('suggestion_panel', () => { const wrapper = mount(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); wrapper.update(); - expect( - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .prop('className') - ).toContain('lnsSuggestionPanel__button-isSelected'); + expect(wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).prop('className')).toContain( + 'lnsSuggestionPanel__button-isSelected' + ); }); it('should rollback suggestion if current panel is clicked', () => { const wrapper = mount(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); wrapper.update(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(0) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(0).simulate('click'); }); wrapper.update(); @@ -204,10 +192,7 @@ describe('suggestion_panel', () => { const wrapper = mount(); act(() => { - wrapper - .find('button[data-test-subj="lnsSuggestion"]') - .at(1) - .simulate('click'); + wrapper.find('button[data-test-subj="lnsSuggestion"]').at(1).simulate('click'); }); wrapper.update(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx index 867214d15578a..0f0885d696ba4 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx @@ -171,7 +171,7 @@ export function SuggestionPanel({ activeVisualizationId: currentVisualizationId, visualizationState: currentVisualizationState, }) - .map(suggestion => ({ + .map((suggestion) => ({ ...suggestion, previewExpression: preparePreviewExpression( suggestion, @@ -181,7 +181,7 @@ export function SuggestionPanel({ frame ), })) - .filter(suggestion => !suggestion.hide) + .filter((suggestion) => !suggestion.hide) .slice(0, MAX_SUGGESTIONS_DISPLAYED); const newStateExpression = @@ -368,7 +368,7 @@ function getPreviewExpression( visualizableState.keptLayerIds ); const changedLayers = datasource.getLayers(visualizableState.datasourceState); - changedLayers.forEach(layerId => { + changedLayers.forEach((layerId) => { if (updatedLayerApis[layerId]) { updatedLayerApis[layerId] = datasource.getPublicAPI({ layerId, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx index a20626ebaaad7..59b5f358e190f 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx @@ -348,7 +348,7 @@ describe('workspace_panel', () => { .mockReturnValueOnce('datasource') .mockReturnValueOnce('datasource second'); - expressionRendererMock = jest.fn(_arg => ); + expressionRendererMock = jest.fn((_arg) => ); await act(async () => { instance = mount( @@ -404,7 +404,7 @@ describe('workspace_panel', () => { .mockReturnValueOnce('datasource') .mockReturnValueOnce('datasource second'); - expressionRendererMock = jest.fn(_arg => ); + expressionRendererMock = jest.fn((_arg) => ); await act(async () => { instance = mount( { expect(expressionRendererMock).toHaveBeenCalledTimes(1); - expressionRendererMock.mockImplementation(_ => { + expressionRendererMock.mockImplementation((_) => { return ; }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx index b000fc7fa0176..44dd9f8364870 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx @@ -86,7 +86,7 @@ export function InnerWorkspacePanel({ } const hasData = Object.values(framePublicAPI.datasourceLayers).some( - datasource => datasource.getTableSpec().length > 0 + (datasource) => datasource.getTableSpec().length > 0 ); const suggestions = getSuggestions({ @@ -101,7 +101,7 @@ export function InnerWorkspacePanel({ field: dragDropContext.dragging, }); - return suggestions.find(s => s.visualizationId === activeVisualizationId) || suggestions[0]; + return suggestions.find((s) => s.visualizationId === activeVisualizationId) || suggestions[0]; }, [dragDropContext.dragging]); const [localState, setLocalState] = useState({ @@ -123,7 +123,7 @@ export function InnerWorkspacePanel({ }); } catch (e) { // Most likely an error in the expression provided by a datasource or visualization - setLocalState(s => ({ ...s, expressionBuildError: e.toString() })); + setLocalState((s) => ({ ...s, expressionBuildError: e.toString() })); } }, [ activeVisualization, @@ -138,7 +138,7 @@ export function InnerWorkspacePanel({ useEffect(() => { // reset expression error if component attempts to run it again if (expression && localState.expressionBuildError) { - setLocalState(s => ({ + setLocalState((s) => ({ ...s, expressionBuildError: undefined, })); @@ -256,7 +256,7 @@ export function InnerWorkspacePanel({ { - setLocalState(prevState => ({ + setLocalState((prevState) => ({ ...prevState, expandError: !prevState.expandError, })); diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx index 4e5b32ad7f7a3..69447b3b9a9b8 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx @@ -40,7 +40,7 @@ describe('embeddable', () => { beforeEach(() => { mountpoint = document.createElement('div'); - expressionRenderer = jest.fn(_props => null); + expressionRenderer = jest.fn((_props) => null); trigger = { exec: jest.fn() }; getTrigger = jest.fn(() => trigger); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx index 796cf5b32e3ba..bbd2b18907e9b 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx @@ -96,7 +96,7 @@ export class Embeddable extends AbstractEmbeddable this.onContainerStateChanged(input)); + this.subscription = this.getInput$().subscribe((input) => this.onContainerStateChanged(input)); this.onContainerStateChanged(initialInput); this.autoRefreshFetchSubscription = timefilter @@ -119,7 +119,7 @@ export class Embeddable extends AbstractEmbeddable !filter.meta.disabled) + ? containerState.filters.filter((filter) => !filter.meta.disabled) : undefined; if ( !_.isEqual(containerState.timeRange, this.currentContext.timeRange) || diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx index 41706121830cb..296dcef3e70b9 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx @@ -55,7 +55,7 @@ export function ExpressionWrapper({ padding="m" expression={expression} searchContext={{ ...context }} - renderError={error =>
          {error}
          } + renderError={(error) =>
          {error}
          } onEvent={handleEvent} />
          diff --git a/x-pack/plugins/lens/public/editor_frame_service/format_column.ts b/x-pack/plugins/lens/public/editor_frame_service/format_column.ts index dfb725fef49bb..b95139a00ec57 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/format_column.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/format_column.ts @@ -68,7 +68,7 @@ export const formatColumn: ExpressionFunctionDefinition< fn(input, { format, columnId, decimals }: FormatColumn) { return { ...input, - columns: input.columns.map(col => { + columns: input.columns.map((col) => { if (col.id === columnId) { if (supportedFormats[format]) { return { diff --git a/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts b/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts index 243441f2c8ab3..b3da722de5f34 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts @@ -87,24 +87,8 @@ describe('lens_merge_tables', () => { {} as any ); - expect( - moment - .duration( - moment() - .startOf('week') - .diff(dateRange!.fromDate) - ) - .asDays() - ).toEqual(0); + expect(moment.duration(moment().startOf('week').diff(dateRange!.fromDate)).asDays()).toEqual(0); - expect( - moment - .duration( - moment() - .endOf('week') - .diff(dateRange!.toDate) - ) - .asDays() - ).toEqual(0); + expect(moment.duration(moment().endOf('week').diff(dateRange!.toDate)).asDays()).toEqual(0); }); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx b/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx index e684fe8b3b5d6..9c0825b3c2d27 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx @@ -20,7 +20,7 @@ export function createMockVisualization(): jest.Mocked { return { id: 'TEST_VIS', clearLayer: jest.fn((state, _layerId) => state), - getLayerIds: jest.fn(_state => ['layer1']), + getLayerIds: jest.fn((_state) => ['layer1']), visualizationTypes: [ { icon: 'empty', @@ -28,13 +28,13 @@ export function createMockVisualization(): jest.Mocked { label: 'TEST', }, ], - getVisualizationTypeId: jest.fn(_state => 'empty'), - getDescription: jest.fn(_state => ({ label: '' })), + getVisualizationTypeId: jest.fn((_state) => 'empty'), + getDescription: jest.fn((_state) => ({ label: '' })), switchVisualizationType: jest.fn((_, x) => x), - getPersistableState: jest.fn(_state => _state), - getSuggestions: jest.fn(_options => []), + getPersistableState: jest.fn((_state) => _state), + getSuggestions: jest.fn((_options) => []), initialize: jest.fn((_frame, _state?) => ({})), - getConfiguration: jest.fn(props => ({ + getConfiguration: jest.fn((props) => ({ groups: [ { groupId: 'a', @@ -70,7 +70,7 @@ export function createMockDatasource(id: string): DatasourceMock { id: 'mockindexpattern', clearLayer: jest.fn((state, _layerId) => state), getDatasourceSuggestionsForField: jest.fn((_state, _item) => []), - getDatasourceSuggestionsFromCurrentState: jest.fn(_state => []), + getDatasourceSuggestionsFromCurrentState: jest.fn((_state) => []), getPersistableState: jest.fn(), getPublicAPI: jest.fn().mockReturnValue(publicAPIMock), initialize: jest.fn((_state?) => Promise.resolve()), @@ -79,9 +79,9 @@ export function createMockDatasource(id: string): DatasourceMock { toExpression: jest.fn((_frame, _state) => null), insertLayer: jest.fn((_state, _newLayerId) => {}), removeLayer: jest.fn((_state, _layerId) => {}), - removeColumn: jest.fn(props => {}), - getLayers: jest.fn(_state => []), - getMetaData: jest.fn(_state => ({ filterableIndexPatterns: [] })), + removeColumn: jest.fn((props) => {}), + getLayers: jest.fn((_state) => []), + getMetaData: jest.fn((_state) => ({ filterableIndexPatterns: [] })), renderDimensionTrigger: jest.fn(), renderDimensionEditor: jest.fn(), @@ -121,7 +121,7 @@ export function createExpressionRendererMock(): jest.Mock< React.ReactElement, [ReactExpressionRendererProps] > { - return jest.fn(_ => ); + return jest.fn((_) => ); } export function createMockSetupDependencies() { diff --git a/x-pack/plugins/lens/public/editor_frame_service/service.tsx b/x-pack/plugins/lens/public/editor_frame_service/service.tsx index a815e70c58629..f57acf3bef62d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/service.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/service.tsx @@ -46,7 +46,7 @@ async function collectAsyncDefinitions( ) { const resolvedDefinitions = await Promise.all(definitions); const definitionMap: Record = {}; - resolvedDefinitions.forEach(definition => { + resolvedDefinitions.forEach((definition) => { definitionMap[definition.id] = definition; }); @@ -84,10 +84,10 @@ export class EditorFrameService { } return { - registerDatasource: datasource => { + registerDatasource: (datasource) => { this.datasources.push(datasource as Datasource); }, - registerVisualization: visualization => { + registerVisualization: (visualization) => { this.visualizations.push(visualization as Visualization); }, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx index 99cc22cc6e890..851a9f4653fec 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx @@ -38,7 +38,7 @@ export function ChangeIndexPattern({ }) { const [isPopoverOpen, setPopoverIsOpen] = useState(false); - const createTrigger = function() { + const createTrigger = function () { const { label, title, ...rest } = trigger; return ( { + onChange={(choices) => { const choice = (choices.find(({ checked }) => checked) as unknown) as { value: string; }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx index 5e3b32f6961e6..187ccb8c47563 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx @@ -284,13 +284,13 @@ describe('IndexPattern Data Panel', () => { describe('loading existence data', () => { function testProps() { const setState = jest.fn(); - core.http.post.mockImplementation(async path => { + core.http.post.mockImplementation(async (path) => { const parts = ((path as unknown) as string).split('/'); const indexPatternTitle = parts[parts.length - 1]; return { indexPatternTitle: `${indexPatternTitle}_testtitle`, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }; }); @@ -489,7 +489,7 @@ describe('IndexPattern Data Panel', () => { let overlapCount = 0; const props = testProps(); - core.http.post.mockImplementation(path => { + core.http.post.mockImplementation((path) => { if (queryCount) { ++overlapCount; } @@ -500,7 +500,7 @@ describe('IndexPattern Data Panel', () => { const result = Promise.resolve({ indexPatternTitle, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }); @@ -540,7 +540,7 @@ describe('IndexPattern Data Panel', () => { ); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'client', @@ -561,7 +561,7 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -571,17 +571,11 @@ describe('IndexPattern Data Panel', () => { ); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'bytes', 'memory', ]); @@ -592,21 +586,12 @@ describe('IndexPattern Data Panel', () => { ); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); - - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); - - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); + + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); + + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'client', @@ -627,17 +612,11 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -653,7 +632,7 @@ describe('IndexPattern Data Panel', () => { ...defaultProps.indexPatterns, '1': { ...defaultProps.indexPatterns['1'], - fields: defaultProps.indexPatterns['1'].fields.map(field => ({ + fields: defaultProps.indexPatterns['1'].fields.map((field) => ({ ...field, exists: field.type === 'number', })), @@ -675,7 +654,7 @@ describe('IndexPattern Data Panel', () => { }; const wrapper = shallowWithIntl(); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'memory', @@ -693,7 +672,7 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -701,15 +680,11 @@ describe('IndexPattern Data Panel', () => { it('should allow removing the filter for data', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="lnsEmptyFilter"]') - .first() - .prop('onChange')!({} as ChangeEvent); + wrapper.find('[data-test-subj="lnsEmptyFilter"]').first().prop('onChange')!( + {} as ChangeEvent + ); expect(emptyFieldsTestProps.onToggleEmptyFields).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx index b013f2b9d22a6..ae5632ddae84e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx @@ -95,7 +95,7 @@ export function IndexPatternDataPanel({ const onToggleEmptyFields = useCallback( (showEmptyFields?: boolean) => { - setState(prevState => ({ + setState((prevState) => ({ ...prevState, showEmptyFields: showEmptyFields === undefined ? !prevState.showEmptyFields : showEmptyFields, @@ -106,12 +106,12 @@ export function IndexPatternDataPanel({ const indexPatternList = uniq( Object.values(state.layers) - .map(l => l.indexPatternId) + .map((l) => l.indexPatternId) .concat(currentIndexPatternId) ) .sort((a, b) => a.localeCompare(b)) - .filter(id => !!indexPatterns[id]) - .map(id => ({ + .filter((id) => !!indexPatterns[id]) + .map((id) => ({ id, title: indexPatterns[id].title, timeFieldName: indexPatterns[id].timeFieldName, @@ -141,7 +141,7 @@ export function IndexPatternDataPanel({ filters, dateRange.fromDate, dateRange.toDate, - indexPatternList.map(x => `${x.title}:${x.timeFieldName}`).join(','), + indexPatternList.map((x) => `${x.title}:${x.timeFieldName}`).join(','), ]} /> @@ -232,7 +232,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ const currentIndexPattern = indexPatterns[currentIndexPatternId]; const allFields = currentIndexPattern.fields; const fieldByName = indexBy(allFields, 'name'); - const clearLocalState = () => setLocalState(s => ({ ...s, nameFilter: '', typeFilter: [] })); + const clearLocalState = () => setLocalState((s) => ({ ...s, nameFilter: '', typeFilter: [] })); const lazyScroll = () => { if (scrollContainer) { @@ -255,10 +255,10 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ }, [localState.nameFilter, localState.typeFilter, currentIndexPatternId, showEmptyFields]); const availableFieldTypes = uniq(allFields.map(({ type }) => type)).filter( - type => type in fieldTypeNames + (type) => type in fieldTypeNames ); - const displayedFields = allFields.filter(field => { + const displayedFields = allFields.filter((field) => { if (!supportedFieldTypes.has(field.type)) { return false; } @@ -289,9 +289,9 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ return true; }); - const specialFields = displayedFields.filter(f => f.type === 'document'); + const specialFields = displayedFields.filter((f) => f.type === 'document'); const paginatedFields = displayedFields - .filter(f => f.type !== 'document') + .filter((f) => f.type !== 'document') .sort(sortFields) .slice(0, pageSize); const hilight = localState.nameFilter.toLowerCase(); @@ -354,7 +354,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ 'Search the list of fields in the index pattern for the provided text', })} value={localState.nameFilter} - onChange={e => { + onChange={(e) => { setLocalState({ ...localState, nameFilter: e.target.value }); }} aria-label={i18n.translate('xpack.lens.indexPatterns.filterByNameAriaLabel', { @@ -380,7 +380,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ icon={} isSelected={localState.typeFilter.length ? true : false} onClick={() => { - setLocalState(s => ({ + setLocalState((s) => ({ ...s, isTypeFilterOpen: !localState.isTypeFilterOpen, })); @@ -394,7 +394,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ ( + items={(availableFieldTypes as DataType[]).map((type) => ( { trackUiEvent('indexpattern_type_filter_toggled'); - setLocalState(s => ({ + setLocalState((s) => ({ ...s, typeFilter: localState.typeFilter.includes(type) - ? localState.typeFilter.filter(t => t !== type) + ? localState.typeFilter.filter((t) => t !== type) : [...localState.typeFilter, type], })); }} @@ -434,7 +434,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({
{ + ref={(el) => { if (el && !el.dataset.dynamicScroll) { el.dataset.dynamicScroll = 'true'; setScrollContainer(el); @@ -443,7 +443,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ onScroll={lazyScroll} >
- {specialFields.map(field => ( + {specialFields.map((field) => ( )} - {paginatedFields.map(field => { + {paginatedFields.map((field) => { const overallField = fieldByName[field.name]; return ( c !== inner); + const result = columnOrder.filter((c) => c !== inner); const outerPosition = result.indexOf(outer); result.splice(outerPosition + 1, 0, inner); @@ -130,7 +130,7 @@ export function BucketNestingEditor({ ...aggColumns.map(({ value, text }) => ({ value, text })), ]} value={prevColumn} - onChange={e => setColumns(nestColumn(layer.columnOrder, e.target.value, columnId))} + onChange={(e) => setColumns(nestColumn(layer.columnOrder, e.target.value, columnId))} /> diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx index 9df79aa9e0908..a9e9efa8d1039 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx @@ -751,7 +751,7 @@ describe('IndexPatternDimensionEditorPanel', () => { indexPatterns: { 1: { ...state.indexPatterns['1'], - fields: state.indexPatterns['1'].fields.filter(field => field.name !== 'memory'), + fields: state.indexPatterns['1'].fields.filter((field) => field.name !== 'memory'), }, }, }; @@ -865,7 +865,7 @@ describe('IndexPatternDimensionEditorPanel', () => { expect(options![0]['data-test-subj']).not.toContain('Incompatible'); - options![1].options!.map(operation => + options![1].options!.map((operation) => expect(operation['data-test-subj']).toContain('Incompatible') ); }); @@ -950,10 +950,9 @@ describe('IndexPatternDimensionEditorPanel', () => { ); act(() => { - wrapper - .find('[data-test-subj="lns-indexPatternDimension-min"]') - .first() - .prop('onClick')!({} as React.MouseEvent<{}, MouseEvent>); + wrapper.find('[data-test-subj="lns-indexPatternDimension-min"]').first().prop('onClick')!( + {} as React.MouseEvent<{}, MouseEvent> + ); }); expect(changeColumn).toHaveBeenCalledWith({ diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx index 583832aafcbe8..1e8f73b19a3b0 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx @@ -63,13 +63,13 @@ const getOperationFieldSupportMatrix = (props: Props): OperationFieldSupportMatr const filteredOperationsByMetadata = getAvailableOperationsByMetadata( currentIndexPattern - ).filter(operation => props.filterOperations(operation.operationMetaData)); + ).filter((operation) => props.filterOperations(operation.operationMetaData)); const supportedOperationsByField: Partial> = {}; const supportedFieldsByOperation: Partial> = {}; filteredOperationsByMetadata.forEach(({ operations }) => { - operations.forEach(operation => { + operations.forEach((operation) => { if (supportedOperationsByField[operation.field]) { supportedOperationsByField[operation.field]!.push(operation.operationType); } else { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx index 8651751ea365b..6544d70311511 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx @@ -65,12 +65,12 @@ export function FieldSelect({ const [specialFields, normalFields] = _.partition( fields, - field => fieldMap[field].type === 'document' + (field) => fieldMap[field].type === 'document' ); function fieldNamesToOptions(items: string[]) { return items - .map(field => ({ + .map((field) => ({ label: field, value: { type: 'field', @@ -86,7 +86,7 @@ export function FieldSelect({ fieldExists(existingFields, currentIndexPattern.title, field), compatible: isCompatibleWithCurrentOperation(field), })) - .filter(field => showEmptyFields || field.exists) + .filter((field) => showEmptyFields || field.exists) .sort((a, b) => { if (a.compatible && !b.compatible) { return -1; @@ -153,7 +153,7 @@ export function FieldSelect({ : []) as unknown) as EuiComboBoxOptionOption[] } singleSelection={{ asPlainText: true }} - onChange={choices => { + onChange={(choices) => { if (choices.length === 0) { onDeleteColumn(); return; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx index ed68a93c51ca2..b3b0190b9c400 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx @@ -88,7 +88,7 @@ export function FormatSelector(props: FormatSelectorProps) { ] : [defaultOption] } - onChange={choices => { + onChange={(choices) => { if (choices.length === 0) { return; } @@ -117,7 +117,7 @@ export function FormatSelector(props: FormatSelectorProps) { value={state.decimalPlaces} min={0} max={20} - onChange={e => { + onChange={(e) => { setState({ decimalPlaces: Number(e.target.value) }); onChange({ id: (selectedColumn.params as { format: { id: string } }).format.id, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx index e26c338b6e240..6bd4263014b13 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx @@ -48,7 +48,7 @@ function asOperationOptions(operationTypes: OperationType[], compatibleWithCurre operationPanels[opType2].displayName ); }) - .map(operationType => ({ + .map((operationType) => ({ operationType, compatibleWithCurrentField, })); @@ -76,7 +76,7 @@ export function PopoverEditor(props: PopoverEditorProps) { const fieldMap: Record = useMemo(() => { const fields: Record = {}; - currentIndexPattern.fields.forEach(field => { + currentIndexPattern.fields.forEach((field) => { fields[field.name] = field; }); return fields; @@ -205,7 +205,7 @@ export function PopoverEditor(props: PopoverEditorProps) { }) ); }} - onChoose={choice => { + onChoose={(choice) => { let column: IndexPatternColumn; if ( !incompatibleSelectedOperationType && @@ -313,7 +313,7 @@ export function PopoverEditor(props: PopoverEditorProps) { compressed data-test-subj="indexPattern-label-edit" value={selectedColumn.label} - onChange={e => { + onChange={(e) => { setState( changeColumn({ state, @@ -334,7 +334,7 @@ export function PopoverEditor(props: PopoverEditorProps) { { + setColumns={(columnOrder) => { setState({ ...state, layers: { @@ -352,7 +352,7 @@ export function PopoverEditor(props: PopoverEditorProps) { {selectedColumn && selectedColumn.dataType === 'number' ? ( { + onChange={(newFormat) => { setState( updateColumnParam({ state, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx index 6a4a2bd2ba77b..511ba3c0442c7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx @@ -114,7 +114,7 @@ describe('IndexPattern Field Item', () => { let resolveFunction: (arg: unknown) => void; core.http.post.mockImplementation(() => { - return new Promise(resolve => { + return new Promise((resolve) => { resolveFunction = resolve; }); }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx index 5f0fa95ad0022..81eb53cd10002 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx @@ -125,7 +125,7 @@ export function FieldItem(props: FieldItemProps) { return; } - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); core.http .post(`/api/lens/index_stats/${indexPattern.title}/field`, { @@ -143,7 +143,7 @@ export function FieldItem(props: FieldItemProps) { }), }) .then((results: FieldStatsResponse) => { - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, totalDocuments: results.totalDocuments, @@ -154,7 +154,7 @@ export function FieldItem(props: FieldItemProps) { })); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); }); } @@ -193,7 +193,7 @@ export function FieldItem(props: FieldItemProps) { onClick={() => { togglePopover(); }} - onKeyPress={event => { + onKeyPress={(event) => { if (event.key === 'ENTER') { togglePopover(); } @@ -331,7 +331,7 @@ function FieldItemPopoverContents(props: State & FieldItemProps) { id: 'histogram', }, ]} - onChange={optionId => { + onChange={(optionId) => { setShowingHistogram(optionId === 'histogram'); }} idSelected={showingHistogram ? 'histogram' : 'topValues'} @@ -444,7 +444,7 @@ function FieldItemPopoverContents(props: State & FieldItemProps) { id="key" position={Position.Left} showOverlappingTicks={true} - tickFormat={d => formatter.convert(d)} + tickFormat={(d) => formatter.convert(d)} /> - {props.topValues.buckets.map(topValue => { + {props.topValues.buckets.map((topValue) => { const formatted = formatter.convert(topValue.key); return (
diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx index b8f0460f2a9ab..c94dd621b9d19 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx @@ -86,7 +86,7 @@ export function uniqueLabels(layers: Record) { return uniqueLabel; }; - Object.values(layers).forEach(layer => { + Object.values(layers).forEach((layer) => { if (!layer.columns) { return; } @@ -180,8 +180,8 @@ export function getIndexPatternDatasource({ return { filterableIndexPatterns: _.uniq( Object.values(state.layers) - .map(layer => layer.indexPatternId) - .map(indexPatternId => ({ + .map((layer) => layer.indexPatternId) + .map((indexPatternId) => ({ id: indexPatternId, title: state.indexPatterns[indexPatternId].title, })) @@ -282,7 +282,7 @@ export function getIndexPatternDatasource({ render( { + onChangeIndexPattern={(indexPatternId) => { changeLayerIndexPattern({ savedObjectsClient, indexPatternId, @@ -309,7 +309,7 @@ export function getIndexPatternDatasource({ datasourceId: 'indexpattern', getTableSpec: () => { - return state.layers[layerId].columnOrder.map(colId => ({ columnId: colId })); + return state.layers[layerId].columnOrder.map((colId) => ({ columnId: colId })); }, getOperationForColumnId: (columnId: string) => { const layer = state.layers[layerId]; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx index f26fd39a60c0e..5eca55cbfcbda 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx @@ -1308,7 +1308,7 @@ describe('IndexPattern Data Source suggestions', () => { ...state, indexPatterns: { 1: { ...state.indexPatterns['1'], timeFieldName: undefined } }, }); - suggestions.forEach(suggestion => expect(suggestion.table.columns.length).toBe(1)); + suggestions.forEach((suggestion) => expect(suggestion.table.columns.length).toBe(1)); }); it('returns simplified versions of table with more than 2 columns', () => { @@ -1616,9 +1616,9 @@ function isTableWithBucketColumns( columnIds: string[], numBuckets: number ) { - expect(suggestion.table.columns.map(column => column.columnId)).toEqual(columnIds); + expect(suggestion.table.columns.map((column) => column.columnId)).toEqual(columnIds); expect( - suggestion.table.columns.slice(0, numBuckets).every(column => column.operation.isBucketed) + suggestion.table.columns.slice(0, numBuckets).every((column) => column.operation.isBucketed) ).toBeTruthy(); } @@ -1627,6 +1627,6 @@ function isTableWithMetricColumns( columnIds: string[] ) { expect(suggestion.table.isMultiRow).toEqual(false); - expect(suggestion.table.columns.map(column => column.columnId)).toEqual(columnIds); - expect(suggestion.table.columns.every(column => !column.operation.isBucketed)).toBeTruthy(); + expect(suggestion.table.columns.map((column) => column.columnId)).toEqual(columnIds); + expect(suggestion.table.columns.every((column) => !column.operation.isBucketed)).toBeTruthy(); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts index 487c1bf759fc2..89e2c753f4c76 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts @@ -55,7 +55,7 @@ function buildSuggestion({ // It's fairly easy to accidentally introduce a mismatch between // columnOrder and columns, so this is a safeguard to ensure the // two match up. - const layers = _.mapValues(updatedState.layers, layer => ({ + const layers = _.mapValues(updatedState.layers, (layer) => ({ ...layer, columns: _.pick, Record>( layer.columns, @@ -65,7 +65,7 @@ function buildSuggestion({ const columnOrder = layers[layerId].columnOrder; const columnMap = layers[layerId].columns; - const isMultiRow = Object.values(columnMap).some(column => column.isBucketed); + const isMultiRow = Object.values(columnMap).some((column) => column.isBucketed); return { state: { @@ -74,7 +74,7 @@ function buildSuggestion({ }, table: { - columns: columnOrder.map(columnId => ({ + columns: columnOrder.map((columnId) => ({ columnId, operation: columnToOperation(columnMap[columnId]), })), @@ -94,7 +94,7 @@ export function getDatasourceSuggestionsForField( field: IndexPatternField ): IndexPatternSugestion[] { const layers = Object.keys(state.layers); - const layerIds = layers.filter(id => state.layers[id].indexPatternId === indexPatternId); + const layerIds = layers.filter((id) => state.layers[id].indexPatternId === indexPatternId); if (layerIds.length === 0) { // The field we're suggesting on does not match any existing layer. @@ -108,7 +108,7 @@ export function getDatasourceSuggestionsForField( // The field we're suggesting on matches an existing layer. In this case we find the layer with // the fewest configured columns and try to add the field to this table. If this layer does not // contain any layers yet, behave as if there is no layer. - const mostEmptyLayerId = _.min(layerIds, layerId => state.layers[layerId].columnOrder.length); + const mostEmptyLayerId = _.min(layerIds, (layerId) => state.layers[layerId].columnOrder.length); if (state.layers[mostEmptyLayerId].columnOrder.length === 0) { return getEmptyLayerSuggestionsForField(state, mostEmptyLayerId, indexPatternId, field); } else { @@ -121,7 +121,7 @@ function getBucketOperation(field: IndexPatternField) { // We allow numeric bucket types in some cases, but it's generally not the right suggestion, // so we eliminate it here. if (field.type !== 'number') { - return getOperationTypesForField(field).find(op => op === 'date_histogram' || op === 'terms'); + return getOperationTypesForField(field).find((op) => op === 'date_histogram' || op === 'terms'); } } @@ -135,7 +135,7 @@ function getExistingLayerSuggestionsForField( const operations = getOperationTypesForField(field); const usableAsBucketOperation = getBucketOperation(field); const fieldInUse = Object.values(layer.columns).some( - column => hasField(column) && column.sourceField === field.name + (column) => hasField(column) && column.sourceField === field.name ); const suggestions: IndexPatternSugestion[] = []; @@ -238,7 +238,7 @@ function addFieldAsBucketOperation( } const oldDateHistogramIndex = layer.columnOrder.findIndex( - columnId => layer.columns[columnId].operationType === 'date_histogram' + (columnId) => layer.columns[columnId].operationType === 'date_histogram' ); const oldDateHistogramId = oldDateHistogramIndex > -1 ? layer.columnOrder[oldDateHistogramIndex] : null; @@ -256,7 +256,7 @@ function addFieldAsBucketOperation( } else if (operation === 'date_histogram') { // Replace date histogram with new date histogram delete updatedColumns[oldDateHistogramId]; - updatedColumnOrder = layer.columnOrder.map(columnId => + updatedColumnOrder = layer.columnOrder.map((columnId) => columnId !== oldDateHistogramId ? columnId : newColumnId ); } @@ -351,7 +351,7 @@ function createNewLayerWithMetricAggregation( indexPattern: IndexPattern, field: IndexPatternField ): IndexPatternLayer { - const dateField = indexPattern.fields.find(f => f.name === indexPattern.timeFieldName)!; + const dateField = indexPattern.fields.find((f) => f.name === indexPattern.timeFieldName)!; const column = getMetricColumn(indexPattern, layerId, field); @@ -427,7 +427,7 @@ export function getDatasourceSuggestionsFromCurrentState( const indexPattern = state.indexPatterns[layer.indexPatternId]; const [buckets, metrics] = separateBucketColumns(layer); const timeDimension = layer.columnOrder.find( - columnId => + (columnId) => layer.columns[columnId].isBucketed && layer.columns[columnId].dataType === 'date' ); const timeField = indexPattern.fields.find( @@ -493,7 +493,7 @@ function createChangedNestingSuggestion(state: IndexPatternPrivateState, layerId function getMetricColumn(indexPattern: IndexPattern, layerId: string, field: IndexPatternField) { const operationDefinitionsMap = _.indexBy(operationDefinitions, 'type'); const [column] = getOperationTypesForField(field) - .map(type => + .map((type) => operationDefinitionsMap[type].buildColumn({ field, indexPattern, @@ -502,7 +502,7 @@ function getMetricColumn(indexPattern: IndexPattern, layerId: string, field: Ind suggestedPriority: 0, }) ) - .filter(op => (op.dataType === 'number' || op.dataType === 'document') && !op.isBucketed); + .filter((op) => (op.dataType === 'number' || op.dataType === 'document') && !op.isBucketed); return column; } @@ -561,14 +561,14 @@ function createAlternativeMetricSuggestions( ) { const layer = state.layers[layerId]; const suggestions: Array> = []; - layer.columnOrder.forEach(columnId => { + layer.columnOrder.forEach((columnId) => { const column = layer.columns[columnId]; if (!hasField(column)) { return; } const field = indexPattern.fields.find(({ name }) => column.sourceField === name)!; const alternativeMetricOperations = getOperationTypesForField(field) - .map(op => + .map((op) => buildColumn({ op, columns: layer.columns, @@ -579,7 +579,7 @@ function createAlternativeMetricSuggestions( }) ) .filter( - fullOperation => + (fullOperation) => fullOperation.operationType !== column.operationType && !fullOperation.isBucketed ); if (alternativeMetricOperations.length === 0) { @@ -662,12 +662,12 @@ function createSimplifiedTableSuggestions(state: IndexPatternPrivateState, layer }) ) .concat( - availableMetricColumns.map(columnId => { + availableMetricColumns.map((columnId) => { // build suggestions with only metrics return { ...layer, columnOrder: [columnId] }; }) ) - .map(updatedLayer => { + .map((updatedLayer) => { return buildSuggestion({ state, layerId, @@ -695,5 +695,5 @@ function getMetricSuggestionTitle(layer: IndexPatternLayer, onlyMetric: boolean) } function separateBucketColumns(layer: IndexPatternLayer) { - return partition(layer.columnOrder, columnId => layer.columns[columnId].isBucketed); + return partition(layer.columnOrder, (columnId) => layer.columns[columnId].isBucketed); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx index 4dd29d7925916..0d16e2d054a77 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx @@ -183,17 +183,13 @@ describe('Layer Data Panel', () => { }); function getIndexPatternPickerList(instance: ShallowWrapper) { - return instance - .find(ChangeIndexPattern) - .first() - .dive() - .find(EuiSelectable); + return instance.find(ChangeIndexPattern).first().dive().find(EuiSelectable); } function selectIndexPatternPickerOption(instance: ShallowWrapper, selectedLabel: string) { const options: Array<{ label: string; checked?: 'on' | 'off' }> = getIndexPatternPickerOptions( instance - ).map(option => + ).map((option) => option.label === selectedLabel ? { ...option, checked: 'on' } : { ...option, checked: undefined } @@ -202,16 +198,13 @@ describe('Layer Data Panel', () => { } function getIndexPatternPickerOptions(instance: ShallowWrapper) { - return getIndexPatternPickerList(instance) - .dive() - .find(EuiSelectableList) - .prop('options'); + return getIndexPatternPickerList(instance).dive().find(EuiSelectableList).prop('options'); } it('should list all index patterns', () => { const instance = shallow(); - expect(getIndexPatternPickerOptions(instance)!.map(option => option.label)).toEqual([ + expect(getIndexPatternPickerOptions(instance)!.map((option) => option.label)).toEqual([ 'my-fake-index-pattern', 'my-fake-restricted-pattern', 'my-compatible-pattern', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts index cacf729ba0caf..b54ad3651471d 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts @@ -147,7 +147,7 @@ function indexPatternSavedObject({ id }: { id: keyof typeof sampleIndexPatterns attributes: { title: pattern.title, timeFieldName: pattern.timeFieldName, - fields: JSON.stringify(pattern.fields.filter(f => f.type !== 'document')), + fields: JSON.stringify(pattern.fields.filter((f) => f.type !== 'document')), }, }; } @@ -256,12 +256,14 @@ describe('loader', () => { } as unknown) as Pick, }); - expect(cache.foo.fields.find(f => f.name === 'bytes')!.aggregationRestrictions).toEqual({ + expect(cache.foo.fields.find((f) => f.name === 'bytes')!.aggregationRestrictions).toEqual({ sum: { agg: 'sum' }, }); - expect(cache.foo.fields.find(f => f.name === 'timestamp')!.aggregationRestrictions).toEqual({ - date_histogram: { agg: 'date_histogram', fixed_interval: 'm' }, - }); + expect(cache.foo.fields.find((f) => f.name === 'timestamp')!.aggregationRestrictions).toEqual( + { + date_histogram: { agg: 'date_histogram', fixed_interval: 'm' }, + } + ); }); }); @@ -549,7 +551,7 @@ describe('loader', () => { return { indexPatternTitle, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }; }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts b/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts index 23faab768eba6..c34f4c1d23148 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts @@ -46,14 +46,14 @@ export async function loadIndexPatterns({ savedObjectsClient: SavedObjectsClient; cache: Record; }) { - const missingIds = patterns.filter(id => !cache[id]); + const missingIds = patterns.filter((id) => !cache[id]); if (missingIds.length === 0) { return cache; } const resp = await savedObjectsClient.bulkGet( - missingIds.map(id => ({ id, type: 'index-pattern' })) + missingIds.map((id) => ({ id, type: 'index-pattern' })) ); return resp.savedObjects.reduce( @@ -81,7 +81,7 @@ export async function loadInitialState({ const requiredPatterns = _.unique( state ? Object.values(state.layers) - .map(l => l.indexPatternId) + .map((l) => l.indexPatternId) .concat(state.currentIndexPatternId) : [defaultIndexPatternId || indexPatternRefs[0].id] ); @@ -134,10 +134,10 @@ export async function changeIndexPattern({ patterns: [id], }); - setState(s => ({ + setState((s) => ({ ...s, layers: isSingleEmptyLayer(state.layers) - ? _.mapValues(state.layers, layer => updateLayerIndexPattern(layer, indexPatterns[id])) + ? _.mapValues(state.layers, (layer) => updateLayerIndexPattern(layer, indexPatterns[id])) : state.layers, indexPatterns: { ...s.indexPatterns, @@ -174,7 +174,7 @@ export async function changeLayerIndexPattern({ patterns: [indexPatternId], }); - setState(s => ({ + setState((s) => ({ ...s, layers: { ...s.layers, @@ -201,7 +201,7 @@ async function loadIndexPatternRefs( }); return result.savedObjects - .map(o => ({ + .map((o) => ({ id: String(o.id), title: (o.attributes as { title: string }).title, })) @@ -224,7 +224,7 @@ export async function syncExistingFields({ dslQuery: object; }) { const emptinessInfo = await Promise.all( - indexPatterns.map(pattern => { + indexPatterns.map((pattern) => { const body: Record = { dslQuery, fromDate: dateRange.fromDate, @@ -241,7 +241,7 @@ export async function syncExistingFields({ }) ); - setState(state => ({ + setState((state) => ({ ...state, existingFields: emptinessInfo.reduce((acc, info) => { acc[info.indexPatternTitle] = booleanMap(info.existingFieldNames); @@ -273,7 +273,7 @@ function fromSavedObject( title: attributes.title, fields: (JSON.parse(attributes.fields) as IFieldType[]) .filter( - field => + (field) => !indexPatternsUtils.isNestedField(field) && (!!field.aggregatable || !!field.scripted) ) .concat(documentField) as IndexPatternField[], @@ -294,7 +294,7 @@ function fromSavedObject( const aggs = Object.keys(typeMeta.aggs); newFields.forEach((field, index) => { const restrictionsObj: IndexPatternField['aggregationRestrictions'] = {}; - aggs.forEach(agg => { + aggs.forEach((agg) => { const restriction = typeMeta.aggs && typeMeta.aggs[agg] && typeMeta.aggs[agg][field.name]; if (restriction) { restrictionsObj[agg] = restriction; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx index 9491ca9ea3787..09faa4bb70447 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx @@ -40,7 +40,7 @@ export const cardinalityOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx index e3b6061248f3b..e665e8b8dd326 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx @@ -251,7 +251,7 @@ describe('date_histogram', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'start_date')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'start_date')!; const column = dateHistogramOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'start_date'); @@ -271,7 +271,7 @@ describe('date_histogram', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'start_date')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'start_date')!; const column = dateHistogramOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'start_date'); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx index 6161df1167afe..6e007c12acf42 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx @@ -78,7 +78,7 @@ export const dateHistogramOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && @@ -88,7 +88,7 @@ export const dateHistogramOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); if ( newField && newField.aggregationRestrictions && @@ -138,7 +138,7 @@ export const dateHistogramOperation: OperationDefinition currentField.name === currentColumn.sourceField + (currentField) => currentField.name === currentColumn.sourceField ); const intervalIsRestricted = field!.aggregationRestrictions && field!.aggregationRestrictions.date_histogram; @@ -216,7 +216,7 @@ export const dateHistogramOperation: OperationDefinition { + onChange={(e) => { setInterval({ ...interval, value: e.target.value, @@ -228,7 +228,7 @@ export const dateHistogramOperation: OperationDefinition { + onChange={(e) => { setInterval({ ...interval, unit: e.target.value, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx index 3da635dc13d10..3ede847a5e257 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx @@ -41,7 +41,7 @@ function buildMetricOperation>({ } }, isTransferable: (column, newIndexPattern) => { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && @@ -91,7 +91,7 @@ export const minOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.min', { defaultMessage: 'Minimum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.minOf', { defaultMessage: 'Minimum of {name}', values: { name }, @@ -103,7 +103,7 @@ export const maxOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.max', { defaultMessage: 'Maximum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.maxOf', { defaultMessage: 'Maximum of {name}', values: { name }, @@ -116,7 +116,7 @@ export const averageOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.avg', { defaultMessage: 'Average', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.avgOf', { defaultMessage: 'Average of {name}', values: { name }, @@ -129,7 +129,7 @@ export const sumOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.sum', { defaultMessage: 'Sum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.sumOf', { defaultMessage: 'Sum of {name}', values: { name }, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx index 8f6130e74b5b8..89d02708a900c 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx @@ -100,7 +100,7 @@ describe('terms', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'dest')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'dest')!; const column = termsOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'dest'); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx index 7eb10456b2a6e..1ab58cb11c598 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx @@ -64,7 +64,7 @@ export const termsOperation: OperationDefinition = { } }, isTransferable: (column, newIndexPattern) => { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts index dbcd4eac7fd59..a04f71a9095c5 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts @@ -63,7 +63,7 @@ function getSortScoreByPriority(a: GenericOperationDefinition, b: GenericOperati export function getOperationTypesForField(field: IndexPatternField): OperationType[] { return operationDefinitions .filter( - operationDefinition => + (operationDefinition) => 'getPossibleOperationForField' in operationDefinition && operationDefinition.getPossibleOperationForField(field) ) @@ -133,8 +133,8 @@ export function getAvailableOperationsByMetadata(indexPattern: IndexPattern) { } }; - operationDefinitions.sort(getSortScoreByPriority).forEach(operationDefinition => { - indexPattern.fields.forEach(field => { + operationDefinitions.sort(getSortScoreByPriority).forEach((operationDefinition) => { + indexPattern.fields.forEach((field) => { addToMap( { type: 'field', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts b/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts index 248eb12ec8026..bf938a3e05ef6 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts @@ -44,7 +44,7 @@ export const renameColumns: ExpressionFunctionDefinition< return { type: 'kibana_datatable', - rows: data.rows.map(row => { + rows: data.rows.map((row) => { const mappedRow: Record = {}; Object.entries(idMap).forEach(([fromId, toId]) => { mappedRow[toId.id] = row[fromId]; @@ -60,7 +60,7 @@ export const renameColumns: ExpressionFunctionDefinition< return mappedRow; }), - columns: data.columns.map(column => { + columns: data.columns.map((column) => { const mappedItem = idMap[column.id]; if (!mappedItem) { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts index a2d64e8f2eb8f..a34d0c4187485 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts @@ -52,7 +52,7 @@ function adjustColumnReferencesForChangedColumn( columnId: string ) { const newColumns = { ...columns }; - Object.keys(newColumns).forEach(currentColumnId => { + Object.keys(newColumns).forEach((currentColumnId) => { if (currentColumnId !== columnId) { const currentColumn = newColumns[currentColumnId]; const operationDefinition = operationDefinitionMap[currentColumn.operationType]; @@ -156,16 +156,16 @@ export function updateLayerIndexPattern( layer: IndexPatternLayer, newIndexPattern: IndexPattern ): IndexPatternLayer { - const keptColumns: IndexPatternLayer['columns'] = _.pick(layer.columns, column => + const keptColumns: IndexPatternLayer['columns'] = _.pick(layer.columns, (column) => isColumnTransferable(column, newIndexPattern) ); - const newColumns: IndexPatternLayer['columns'] = _.mapValues(keptColumns, column => { + const newColumns: IndexPatternLayer['columns'] = _.mapValues(keptColumns, (column) => { const operationDefinition = operationDefinitionMap[column.operationType]; return operationDefinition.transfer ? operationDefinition.transfer(column, newIndexPattern) : column; }); - const newColumnOrder = layer.columnOrder.filter(columnId => newColumns[columnId]); + const newColumnOrder = layer.columnOrder.filter((columnId) => newColumns[columnId]); return { ...layer, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts index 1dde03ca8ee9b..e507bee2a898d 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts @@ -25,7 +25,7 @@ function getExpressionForLayer( return operationDefinitionMap[column.operationType].toEsAggsConfig(column, columnId); } - const columnEntries = columnOrder.map(colId => [colId, columns[colId]] as const); + const columnEntries = columnOrder.map((colId) => [colId, columns[colId]] as const); const bucketsCount = columnEntries.filter(([, entry]) => entry.isBucketed).length; const metricsCount = columnEntries.length - bucketsCount; @@ -88,7 +88,7 @@ function getExpressionForLayer( }); const allDateHistogramFields = Object.values(columns) - .map(column => + .map((column) => column.operationType === dateHistogramOperation.type ? column.sourceField : null ) .filter((field): field is string => Boolean(field)); diff --git a/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts b/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts index 10b052c66efed..cb517acff4f7a 100644 --- a/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts +++ b/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts @@ -102,9 +102,7 @@ export class LensReportManager { } private trackTo(target: Record>, name: string) { - const date = moment() - .utc() - .format('YYYY-MM-DD'); + const date = moment().utc().format('YYYY-MM-DD'); if (!target[date]) { target[date] = { [name]: 1, diff --git a/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx b/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx index 18c6ec6536e96..c75da2f34d98d 100644 --- a/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx @@ -61,10 +61,10 @@ export class AutoScale extends React.Component { return ( - {resizeRef => ( + {(resizeRef) => (
{ + ref={(el) => { this.setParent(el); resizeRef(el); }} diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx b/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx index 2406e7cd42ebc..27f971c2ba11a 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx @@ -57,7 +57,7 @@ describe('metric_expression', () => { const { data, args } = sampleArgs(); expect( - shallow( x as IFieldFormat} />) + shallow( x as IFieldFormat} />) ).toMatchInlineSnapshot(` { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} /> ) ).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts b/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts index 173119714189d..ecb1f07214ac6 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts +++ b/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts @@ -80,7 +80,7 @@ describe('metric_suggestions', () => { layerId: 'l1', changeType: 'unchanged', }, - ] as TableSuggestion[]).map(table => + ] as TableSuggestion[]).map((table) => expect(getSuggestions({ table, keptLayerIds: ['l1'] })).toEqual([]) ) ); diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx b/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx index 04a1c3865f22d..e565d2fa8b293 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx @@ -88,7 +88,7 @@ export const metricVisualization: Visualization = { ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getConfiguration(props) { return { diff --git a/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx b/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx index 08464dd65f67e..8146caaf95ced 100644 --- a/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx +++ b/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx @@ -23,6 +23,6 @@ export interface NativeRendererProps extends HTMLAttributes { export function NativeRenderer({ render, nativeProps, tag, ...rest }: NativeRendererProps) { return React.createElement(tag || 'div', { ...rest, - ref: el => el && render(el, nativeProps), + ref: (el) => el && render(el, nativeProps), }); } diff --git a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx index 78e13bc51588c..4f0c081d8be00 100644 --- a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx @@ -57,13 +57,13 @@ export const pieVisualization: Visualization l.layerId); + return state.layers.map((l) => l.layerId); }, clearLayer(state) { return { shape: state.shape, - layers: state.layers.map(l => newLayerState(l.layerId)), + layers: state.layers.map((l) => newLayerState(l.layerId)), }; }, @@ -91,12 +91,12 @@ export const pieVisualization: Visualization state, + getPersistableState: (state) => state, getSuggestions: suggestions, getConfiguration({ state, frame, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); + const layer = state.layers.find((l) => l.layerId === layerId); if (!layer) { return { groups: [] }; } @@ -105,7 +105,7 @@ export const pieVisualization: Visualization columnId) - .filter(columnId => columnId !== layer.metric); + .filter((columnId) => columnId !== layer.metric); // When we add a column it could be empty, and therefore have no order const sortedColumns = Array.from(new Set(originalOrder.concat(layer.groups))); @@ -171,10 +171,10 @@ export const pieVisualization: Visualization l.groups.length === 1) + prevState.shape === 'donut' && prevState.layers.every((l) => l.groups.length === 1) ? 'pie' : prevState.shape, - layers: prevState.layers.map(l => { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId) { return l; } @@ -188,7 +188,7 @@ export const pieVisualization: Visualization { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId) { return l; } @@ -196,7 +196,7 @@ export const pieVisualization: Visualization c !== columnId) }; + return { ...l, groups: l.groups.filter((c) => c !== columnId) }; }), }; }, diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx index a914efcead005..2e29513ba548b 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx @@ -17,7 +17,7 @@ describe('PieVisualization component', () => { let convertSpy: jest.Mock; beforeEach(() => { - convertSpy = jest.fn(x => x); + convertSpy = jest.fn((x) => x); getFormatSpy = jest.fn(); getFormatSpy.mockReturnValue({ convert: convertSpy }); }); @@ -114,10 +114,9 @@ describe('PieVisualization component', () => { test('it calls filter callback with the given context', () => { const defaultArgs = getDefaultArgs(); const component = shallow(); - component - .find(Settings) - .first() - .prop('onElementClick')!([[[{ groupByRollup: 6, value: 6 }], {} as SeriesIdentifier]]); + component.find(Settings).first().prop('onElementClick')!([ + [[{ groupByRollup: 6, value: 6 }], {} as SeriesIdentifier], + ]); expect(defaultArgs.onClickValue.mock.calls[0][0]).toMatchInlineSnapshot(` Object { diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx index d812803272f3e..be74ec352287f 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx @@ -61,7 +61,7 @@ export function PieComponent( } = props.args; if (!hideLabels) { - firstTable.columns.forEach(column => { + firstTable.columns.forEach((column) => { formatters[column.id] = props.formatFactory(column.formatHint); }); } @@ -70,7 +70,7 @@ export function PieComponent( // [bucket, subtotal, bucket, count] // But the user only configured [bucket, bucket, count] const columnGroups: ColumnGroups = []; - firstTable.columns.forEach(col => { + firstTable.columns.forEach((col) => { if (groups.includes(col.id)) { columnGroups.push({ col, @@ -115,7 +115,7 @@ export function PieComponent( ? { ...fillLabel, textColor: euiDarkVars.euiTextColor } : fillLabel, shape: { - fillColor: d => { + fillColor: (d) => { // Color is determined by round-robin on the index of the innermost slice // This has to be done recursively until we get to the slice index let parentIndex = 0; @@ -134,9 +134,7 @@ export function PieComponent( } const lighten = (d.depth - 1) / (columnGroups.length * 2); - return color(outputColor, 'hsl') - .lighten(lighten) - .hex(); + return color(outputColor, 'hsl').lighten(lighten).hex(); }, }, }; @@ -179,7 +177,7 @@ export function PieComponent( config.linkLabel = { maxCount: 0 }; } } - const metricColumn = firstTable.columns.find(c => c.id === metric)!; + const metricColumn = firstTable.columns.find((c) => c.id === metric)!; const percentFormatter = props.formatFactory({ id: 'percent', params: { @@ -196,14 +194,14 @@ export function PieComponent( const reverseGroups = [...columnGroups].reverse(); - const hasNegative = firstTable.rows.some(row => { + const hasNegative = firstTable.rows.some((row) => { const value = row[metricColumn.id]; return typeof value === 'number' && value < 0; }); const isEmpty = firstTable.rows.length === 0 || - firstTable.rows.every(row => - groups.every(colId => !row[colId] || typeof row[colId] === 'undefined') + firstTable.rows.every((row) => + groups.every((colId) => !row[colId] || typeof row[colId] === 'undefined') ); if (isEmpty) { @@ -237,7 +235,7 @@ export function PieComponent( (legendDisplay === 'default' && columnGroups.length > 1 && shape !== 'treemap')) } legendMaxDepth={nestedLegend ? undefined : 1 /* Color is based only on first layer */} - onElementClick={args => { + onElementClick={(args) => { const context = getFilterContext( args[0][0] as LayerValue[], columnGroups.map(({ col }) => col.id), diff --git a/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts b/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts index 3f7494661c049..aafbb477bab22 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts +++ b/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts @@ -20,7 +20,7 @@ export function getSliceValueWithFallback( // Sometimes there is missing data for outer groups // When there is missing data, we fall back to the next groups // This creates a sunburst effect - const hasMetric = reverseGroups.find(group => group.metrics.length && d[group.metrics[0].id]); + const hasMetric = reverseGroups.find((group) => group.metrics.length && d[group.metrics[0].id]); return hasMetric ? d[hasMetric.metrics[0].id] || Number.EPSILON : Number.EPSILON; } @@ -29,7 +29,7 @@ export function getFilterContext( layerColumnIds: string[], table: KibanaDatatable ): LensFilterEvent['data'] { - const matchingIndex = table.rows.findIndex(row => + const matchingIndex = table.rows.findIndex((row) => clickedLayers.every((layer, index) => { const columnId = layerColumnIds[index]; return row[columnId] === layer.groupByRollup; @@ -38,7 +38,7 @@ export function getFilterContext( return { data: clickedLayers.map((clickedLayer, index) => ({ - column: table.columns.findIndex(col => col.id === layerColumnIds[index]), + column: table.columns.findIndex((col) => col.id === layerColumnIds[index]), row: matchingIndex, value: clickedLayer.groupByRollup, table, diff --git a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx b/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx index bb63ceceb2b1b..e5fde12f74b42 100644 --- a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx @@ -132,7 +132,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(option) => { setState({ ...state, layers: [{ ...layer, categoryDisplay: option }], @@ -152,7 +152,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(option) => { setState({ ...state, layers: [{ ...layer, numberDisplay: option }], @@ -175,7 +175,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(e) => { setState({ ...state, layers: [{ ...layer, percentDecimals: Number(e.currentTarget.value) }], @@ -197,7 +197,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps value === layer.legendDisplay)!.id} - onChange={optionId => { + onChange={(optionId) => { setState({ ...state, layers: [ diff --git a/x-pack/plugins/lens/public/pie_visualization/suggestions.ts b/x-pack/plugins/lens/public/pie_visualization/suggestions.ts index 16c8fda3807db..5d85ac3bbd56a 100644 --- a/x-pack/plugins/lens/public/pie_visualization/suggestions.ts +++ b/x-pack/plugins/lens/public/pie_visualization/suggestions.ts @@ -15,7 +15,7 @@ function shouldReject({ table, keptLayerIds }: SuggestionRequest 1 || (keptLayerIds.length && table.layerId !== keptLayerIds[0]) || table.changeType === 'reorder' || - table.columns.some(col => col.operation.dataType === 'date') + table.columns.some((col) => col.operation.dataType === 'date') ); } @@ -30,7 +30,7 @@ export function suggestions({ return []; } - const [groups, metrics] = partition(table.columns, col => col.operation.isBucketed); + const [groups, metrics] = partition(table.columns, (col) => col.operation.isBucketed); if ( groups.length === 0 || @@ -62,12 +62,12 @@ export function suggestions({ ? { ...state.layers[0], layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, } : { layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, numberDisplay: 'percent', categoryDisplay: 'default', @@ -113,7 +113,7 @@ export function suggestions({ ? { ...state.layers[0], layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, categoryDisplay: state.layers[0].categoryDisplay === 'inside' @@ -122,7 +122,7 @@ export function suggestions({ } : { layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, numberDisplay: 'percent', categoryDisplay: 'default', diff --git a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts index 4a7272b26a63f..cf9d311dfd504 100644 --- a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts @@ -21,7 +21,7 @@ function expressionHelper( const layer = state.layers[0]; const datasource = frame.datasourceLayers[layer.layerId]; const operations = layer.groups - .map(columnId => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) + .map((columnId) => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) .filter((o): o is { columnId: string; operation: Operation } => !!o.operation); if (!layer.metric || !operations.length) { return null; @@ -36,7 +36,7 @@ function expressionHelper( arguments: { shape: [state.shape], hideLabels: [isPreview], - groups: operations.map(o => o.columnId), + groups: operations.map((o) => o.columnId), metric: [layer.metric], numberDisplay: [layer.numberDisplay], categoryDisplay: [layer.categoryDisplay], diff --git a/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts b/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts index eb7fd688bab5a..6efcfcab1ff7f 100644 --- a/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts +++ b/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts @@ -12,11 +12,11 @@ export function isHorizontalSeries(seriesType: SeriesType) { } export function isHorizontalChart(layers: Array<{ seriesType: SeriesType }>) { - return layers.every(l => isHorizontalSeries(l.seriesType)); + return layers.every((l) => isHorizontalSeries(l.seriesType)); } export function getIconForSeries(type: SeriesType): EuiIconType { - const definition = visualizationTypes.find(t => t.id === type); + const definition = visualizationTypes.find((t) => t.id === type); if (!definition) { throw new Error(`Unknown series type ${type}`); diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts index 6bc379ea33bca..e9e0cfed909fb 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts @@ -25,7 +25,7 @@ describe('#toExpression', () => { { columnId: 'c' }, ]); - mockDatasource.publicAPIMock.getOperationForColumnId.mockImplementation(col => { + mockDatasource.publicAPIMock.getOperationForColumnId.mockImplementation((col) => { return { label: `col_${col}`, dataType: 'number' } as Operation; }); diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts index d28a803790822..e02d135d9a455 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts @@ -41,10 +41,10 @@ export const toExpression = (state: State, frame: FramePublicAPI): Ast | null => } const metadata: Record> = {}; - state.layers.forEach(layer => { + state.layers.forEach((layer) => { metadata[layer.layerId] = {}; const datasource = frame.datasourceLayers[layer.layerId]; - datasource.getTableSpec().forEach(column => { + datasource.getTableSpec().forEach((column) => { const operation = frame.datasourceLayers[layer.layerId].getOperationForColumnId( column.columnId ); @@ -59,7 +59,7 @@ export function toPreviewExpression(state: State, frame: FramePublicAPI) { return toExpression( { ...state, - layers: state.layers.map(layer => ({ ...layer, hide: true })), + layers: state.layers.map((layer) => ({ ...layer, hide: true })), // hide legend for preview legend: { ...state.legend, @@ -133,14 +133,14 @@ export const buildExpression = ( ], }, ], - layers: validLayers.map(layer => { + layers: validLayers.map((layer) => { const columnToLabel: Record = {}; if (frame) { const datasource = frame.datasourceLayers[layer.layerId]; layer.accessors .concat(layer.splitAccessor ? [layer.splitAccessor] : []) - .forEach(accessor => { + .forEach((accessor) => { const operation = datasource.getOperationForColumnId(accessor); if (operation?.label) { columnToLabel[accessor] = operation.label; diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx index 5e85680cc2b2c..0ea44e469f8dd 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx @@ -28,7 +28,7 @@ function updateLayer(state: State, layer: UnwrapArray, index: n export function LayerContextMenu(props: VisualizationLayerWidgetProps) { const { state, layerId } = props; const horizontalOnly = isHorizontalChart(state.layers); - const index = state.layers.findIndex(l => l.layerId === layerId); + const index = state.layers.findIndex((l) => l.layerId === layerId); const layer = state.layers[index]; if (!layer) { @@ -49,14 +49,14 @@ export function LayerContextMenu(props: VisualizationLayerWidgetProps) { className="eui-displayInlineBlock" data-test-subj="lnsXY_seriesType" options={visualizationTypes - .filter(t => isHorizontalSeries(t.id as SeriesType) === horizontalOnly) - .map(t => ({ + .filter((t) => isHorizontalSeries(t.id as SeriesType) === horizontalOnly) + .map((t) => ({ id: t.id, label: t.label, iconType: t.icon || 'empty', }))} idSelected={layer.seriesType} - onChange={seriesType => { + onChange={(seriesType) => { trackUiEvent('xy_change_layer_display'); props.setState( updateLayer(state, { ...layer, seriesType: seriesType as SeriesType }, index) diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx index 346351f2e7ee2..b2d9f6acfc9f5 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx @@ -281,7 +281,7 @@ describe('xy_expression', () => { let convertSpy: jest.Mock; beforeEach(() => { - convertSpy = jest.fn(x => x); + convertSpy = jest.fn((x) => x); getFormatSpy = jest.fn(); getFormatSpy.mockReturnValue({ convert: convertSpy }); }); @@ -618,10 +618,7 @@ describe('xy_expression', () => { /> ); - wrapper - .find(Settings) - .first() - .prop('onBrushEnd')!({ x: [1585757732783, 1585758880838] }); + wrapper.find(Settings).first().prop('onBrushEnd')!({ x: [1585757732783, 1585758880838] }); expect(onSelectRange).toHaveBeenCalledWith({ column: 0, @@ -671,10 +668,9 @@ describe('xy_expression', () => { /> ); - wrapper - .find(Settings) - .first() - .prop('onElementClick')!([[geometry, series as XYChartSeriesIdentifier]]); + wrapper.find(Settings).first().prop('onElementClick')!([ + [geometry, series as XYChartSeriesIdentifier], + ]); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -1188,10 +1184,7 @@ describe('xy_expression', () => { /> ); - const tickFormatter = instance - .find(Axis) - .first() - .prop('tickFormat'); + const tickFormatter = instance.find(Axis).first().prop('tickFormat'); if (!tickFormatter) { throw new Error('tickFormatter prop not found'); diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx index 8b7229cd808aa..4ad2b2f22c98a 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx @@ -156,7 +156,7 @@ export const getXyChartRenderer = (dependencies: { }); function getIconForSeriesType(seriesType: SeriesType): IconType { - return visualizationTypes.find(c => c.id === seriesType)!.icon || 'empty'; + return visualizationTypes.find((c) => c.id === seriesType)!.icon || 'empty'; } const MemoizedChart = React.memo(XYChart); @@ -197,7 +197,7 @@ export function XYChart({ !accessors.length || !data.tables[layerId] || data.tables[layerId].rows.length === 0 || - data.tables[layerId].rows.every(row => typeof row[xAccessor] === 'undefined') + data.tables[layerId].rows.every((row) => typeof row[xAccessor] === 'undefined') ); }); @@ -225,8 +225,8 @@ export function XYChart({ const chartHasMoreThanOneSeries = filteredLayers.length > 1 || - filteredLayers.some(layer => layer.accessors.length > 1) || - filteredLayers.some(layer => layer.splitAccessor); + filteredLayers.some((layer) => layer.accessors.length > 1) || + filteredLayers.some((layer) => layer.splitAccessor); const shouldRotate = isHorizontalChart(filteredLayers); const xTitle = (xAxisColumn && xAxisColumn.name) || args.xTitle; @@ -240,7 +240,7 @@ export function XYChart({ for (const layer of filteredLayers) { if ( layer.xAccessor && - data.tables[layer.layerId].rows.some(row => row[layer.xAccessor!] !== firstRowValue) + data.tables[layer.layerId].rows.some((row) => row[layer.xAccessor!] !== firstRowValue) ) { return false; } @@ -261,7 +261,7 @@ export function XYChart({ return undefined; } - const isTimeViz = data.dateRange && filteredLayers.every(l => l.xScaleType === 'time'); + const isTimeViz = data.dateRange && filteredLayers.every((l) => l.xScaleType === 'time'); const xDomain = isTimeViz ? { @@ -293,7 +293,7 @@ export function XYChart({ const table = data.tables[filteredLayers[0].layerId]; const xAxisColumnIndex = table.columns.findIndex( - el => el.id === filteredLayers[0].xAccessor + (el) => el.id === filteredLayers[0].xAccessor ); const timeFieldName = table.columns[xAxisColumnIndex]?.meta?.aggConfigParams?.field; @@ -310,7 +310,7 @@ export function XYChart({ const xySeries = series as XYChartSeriesIdentifier; const xyGeometry = geometry as GeometryValue; - const layer = filteredLayers.find(l => + const layer = filteredLayers.find((l) => xySeries.seriesKeys.some((key: string | number) => l.accessors.includes(key.toString())) ); if (!layer) { @@ -322,9 +322,9 @@ export function XYChart({ const points = [ { row: table.rows.findIndex( - row => layer.xAccessor && row[layer.xAccessor] === xyGeometry.x + (row) => layer.xAccessor && row[layer.xAccessor] === xyGeometry.x ), - column: table.columns.findIndex(col => col.id === layer.xAccessor), + column: table.columns.findIndex((col) => col.id === layer.xAccessor), value: xyGeometry.x, }, ]; @@ -334,19 +334,19 @@ export function XYChart({ points.push({ row: table.rows.findIndex( - row => layer.splitAccessor && row[layer.splitAccessor] === pointValue + (row) => layer.splitAccessor && row[layer.splitAccessor] === pointValue ), - column: table.columns.findIndex(col => col.id === layer.splitAccessor), + column: table.columns.findIndex((col) => col.id === layer.splitAccessor), value: pointValue, }); } - const xAxisFieldName = table.columns.find(el => el.id === layer.xAccessor)?.meta + const xAxisFieldName = table.columns.find((el) => el.id === layer.xAccessor)?.meta ?.aggConfigParams?.field; const timeFieldName = xDomain && xAxisFieldName; const context: LensFilterEvent['data'] = { - data: points.map(point => ({ + data: points.map((point) => ({ row: point.row, column: point.column, value: point.value, @@ -364,7 +364,7 @@ export function XYChart({ title={xTitle} showGridLines={false} hide={filteredLayers[0].hide} - tickFormat={d => xAxisFormatter.convert(d)} + tickFormat={(d) => xAxisFormatter.convert(d)} /> yAxisFormatter.convert(d)} + tickFormat={(d) => yAxisFormatter.convert(d)} /> {filteredLayers.map( @@ -400,13 +400,13 @@ export function XYChart({ // For date histogram chart type, we're getting the rows that represent intervals without data. // To not display them in the legend, they need to be filtered out. const rows = table.rows.filter( - row => + (row) => xAccessor && typeof row[xAccessor] !== 'undefined' && !( splitAccessor && typeof row[splitAccessor] === 'undefined' && - accessors.every(accessor => typeof row[accessor] === 'undefined') + accessors.every((accessor) => typeof row[accessor] === 'undefined') ) ); @@ -422,7 +422,7 @@ export function XYChart({ enableHistogramMode: isHistogram && (seriesType.includes('stacked') || !splitAccessor), timeZone, name(d) { - const splitHint = table.columns.find(col => col.id === splitAccessor)?.formatHint; + const splitHint = table.columns.find((col) => col.id === splitAccessor)?.formatHint; // For multiple y series, the name of the operation is used on each, either: // * Key - Y name diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts index 722a07f581db5..c107d8d368248 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts @@ -100,7 +100,7 @@ describe('xy_suggestions', () => { layerId: 'first', changeType: 'unchanged', }, - ] as TableSuggestion[]).map(table => + ] as TableSuggestion[]).map((table) => expect(getSuggestions({ table, keptLayerIds: [] })).toEqual([]) ) ); @@ -432,7 +432,7 @@ describe('xy_suggestions', () => { expect(rest).toHaveLength(visualizationTypes.length - 1); expect(suggestion.state.preferredSeriesType).toEqual('bar_horizontal'); - expect(suggestion.state.layers.every(l => l.seriesType === 'bar_horizontal')).toBeTruthy(); + expect(suggestion.state.layers.every((l) => l.seriesType === 'bar_horizontal')).toBeTruthy(); expect(suggestion.title).toEqual('Flip'); }); @@ -461,7 +461,7 @@ describe('xy_suggestions', () => { keptLayerIds: [], }); - const visibleSuggestions = suggestions.filter(suggestion => !suggestion.hide); + const visibleSuggestions = suggestions.filter((suggestion) => !suggestion.hide); expect(visibleSuggestions).toContainEqual( expect.objectContaining({ title: 'Stacked', diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts index 71cb8e0cbdc99..ffbd3b7e2c1f2 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts @@ -42,8 +42,8 @@ export function getSuggestions({ // We reject any datasource suggestions which have a column of an unknown type. !table.isMultiRow || table.columns.length <= 1 || - table.columns.every(col => col.operation.dataType !== 'number') || - table.columns.some(col => !columnSortOrder.hasOwnProperty(col.operation.dataType)) + table.columns.every((col) => col.operation.dataType !== 'number') || + table.columns.some((col) => !columnSortOrder.hasOwnProperty(col.operation.dataType)) ) { return []; } @@ -62,7 +62,7 @@ function getSuggestionForColumns( keptLayerIds: string[], currentState?: State ): VisualizationSuggestion | Array> | undefined { - const [buckets, values] = partition(table.columns, col => col.operation.isBucketed); + const [buckets, values] = partition(table.columns, (col) => col.operation.isBucketed); if (buckets.length === 1 || buckets.length === 2) { const [x, splitBy] = getBucketMappings(table, currentState); @@ -95,7 +95,7 @@ function getBucketMappings(table: TableSuggestion, currentState?: State) { const currentLayer = currentState && currentState.layers.find(({ layerId }) => layerId === table.layerId); - const buckets = table.columns.filter(col => col.operation.isBucketed); + const buckets = table.columns.filter((col) => col.operation.isBucketed); // reverse the buckets before prioritization to always use the most inner // bucket of the highest-prioritized group as x value (don't use nested // buckets as split series) @@ -182,7 +182,7 @@ function getSuggestionsForLayer({ if (!currentState && changeType === 'unchanged') { // Chart switcher needs to include every chart type return visualizationTypes - .map(visType => ({ + .map((visType) => ({ ...buildSuggestion({ ...options, seriesType: visType.id as SeriesType }), title: visType.label, hide: visType.id !== 'bar_stacked', @@ -251,12 +251,12 @@ function getSuggestionsForLayer({ // Combine all pre-built suggestions with hidden suggestions for remaining chart types return sameStateSuggestions.concat( visualizationTypes - .filter(visType => { + .filter((visType) => { return !sameStateSuggestions.find( - suggestion => suggestion.state.preferredSeriesType === visType.id + (suggestion) => suggestion.state.preferredSeriesType === visType.id ); }) - .map(visType => { + .map((visType) => { return { ...buildSuggestion({ ...options, seriesType: visType.id as SeriesType }), hide: true, @@ -331,7 +331,7 @@ function getSuggestionTitle( tableLabel: string | undefined ) { const yTitle = yValues - .map(col => col.operation.label) + .map((col) => col.operation.label) .join( i18n.translate('xpack.lens.xySuggestions.yAxixConjunctionSign', { defaultMessage: ' & ', @@ -385,12 +385,12 @@ function buildSuggestion({ seriesType, xAccessor: xValue.columnId, splitAccessor: splitBy?.columnId, - accessors: yValues.map(col => col.columnId), + accessors: yValues.map((col) => col.columnId), }; const keptLayers = currentState ? currentState.layers.filter( - layer => layer.layerId !== layerId && keptLayerIds.includes(layer.layerId) + (layer) => layer.layerId !== layerId && keptLayerIds.includes(layer.layerId) ) : []; @@ -425,5 +425,5 @@ function getScore( } function getExistingLayer(currentState: XYState | undefined, layerId: string) { - return currentState && currentState.layers.find(layer => layer.layerId === layerId); + return currentState && currentState.layers.find((layer) => layer.layerId === layerId); } diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts index d176905c65120..0a8e8bbe0c46f 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts @@ -316,7 +316,7 @@ describe('xy_visualization', () => { layerId: 'first', }).groups; expect(options).toHaveLength(3); - expect(options.map(o => o.groupId)).toEqual(['x', 'y', 'breakdown']); + expect(options.map((o) => o.groupId)).toEqual(['x', 'y', 'breakdown']); }); it('should only accept bucketed operations for x', () => { @@ -325,7 +325,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - const filterOperations = options.find(o => o.groupId === 'x')!.filterOperations; + const filterOperations = options.find((o) => o.groupId === 'x')!.filterOperations; const exampleOperation: Operation = { dataType: 'number', @@ -354,7 +354,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - expect(options.find(o => o.groupId === 'x')?.supportsMoreColumns).toBe(false); + expect(options.find((o) => o.groupId === 'x')?.supportsMoreColumns).toBe(false); }); it('should allow number operations on y', () => { @@ -363,7 +363,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - const filterOperations = options.find(o => o.groupId === 'y')!.filterOperations; + const filterOperations = options.find((o) => o.groupId === 'y')!.filterOperations; const exampleOperation: Operation = { dataType: 'number', isBucketed: false, @@ -375,7 +375,7 @@ describe('xy_visualization', () => { { ...exampleOperation, dataType: 'boolean' }, { ...exampleOperation, dataType: 'date' }, ]; - expect(ops.filter(filterOperations).map(x => x.dataType)).toEqual(['number']); + expect(ops.filter(filterOperations).map((x) => x.dataType)).toEqual(['number']); }); }); }); diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx index e91edf9cc0183..ffacfbf8555eb 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx @@ -27,11 +27,11 @@ const isBucketed = (op: OperationMetadata) => op.isBucketed; function getVisualizationType(state: State): VisualizationType | 'mixed' { if (!state.layers.length) { return ( - visualizationTypes.find(t => t.id === state.preferredSeriesType) ?? visualizationTypes[0] + visualizationTypes.find((t) => t.id === state.preferredSeriesType) ?? visualizationTypes[0] ); } - const visualizationType = visualizationTypes.find(t => t.id === state.layers[0].seriesType); - const seriesTypes = _.unique(state.layers.map(l => l.seriesType)); + const visualizationType = visualizationTypes.find((t) => t.id === state.layers[0].seriesType); + const seriesTypes = _.unique(state.layers.map((l) => l.seriesType)); return visualizationType && seriesTypes.length === 1 ? visualizationType : 'mixed'; } @@ -84,18 +84,18 @@ export const xyVisualization: Visualization = { }, getLayerIds(state) { - return state.layers.map(l => l.layerId); + return state.layers.map((l) => l.layerId); }, removeLayer(state, layerId) { return { ...state, - layers: state.layers.filter(l => l.layerId !== layerId), + layers: state.layers.filter((l) => l.layerId !== layerId), }; }, appendLayer(state, layerId) { - const usedSeriesTypes = _.uniq(state.layers.map(layer => layer.seriesType)); + const usedSeriesTypes = _.uniq(state.layers.map((layer) => layer.seriesType)); return { ...state, layers: [ @@ -111,7 +111,7 @@ export const xyVisualization: Visualization = { clearLayer(state, layerId) { return { ...state, - layers: state.layers.map(l => + layers: state.layers.map((l) => l.layerId !== layerId ? l : newLayerState(state.preferredSeriesType, layerId) ), }; @@ -134,7 +134,7 @@ export const xyVisualization: Visualization = { return { ...state, preferredSeriesType: seriesType as SeriesType, - layers: state.layers.map(layer => ({ ...layer, seriesType: seriesType as SeriesType })), + layers: state.layers.map((layer) => ({ ...layer, seriesType: seriesType as SeriesType })), }; }, @@ -159,10 +159,10 @@ export const xyVisualization: Visualization = { ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getConfiguration(props) { - const layer = props.state.layers.find(l => l.layerId === props.layerId)!; + const layer = props.state.layers.find((l) => l.layerId === props.layerId)!; return { groups: [ { @@ -204,7 +204,7 @@ export const xyVisualization: Visualization = { }, setDimension({ prevState, layerId, columnId, groupId }) { - const newLayer = prevState.layers.find(l => l.layerId === layerId); + const newLayer = prevState.layers.find((l) => l.layerId === layerId); if (!newLayer) { return prevState; } @@ -213,7 +213,7 @@ export const xyVisualization: Visualization = { newLayer.xAccessor = columnId; } if (groupId === 'y') { - newLayer.accessors = [...newLayer.accessors.filter(a => a !== columnId), columnId]; + newLayer.accessors = [...newLayer.accessors.filter((a) => a !== columnId), columnId]; } if (groupId === 'breakdown') { newLayer.splitAccessor = columnId; @@ -221,12 +221,12 @@ export const xyVisualization: Visualization = { return { ...prevState, - layers: prevState.layers.map(l => (l.layerId === layerId ? newLayer : l)), + layers: prevState.layers.map((l) => (l.layerId === layerId ? newLayer : l)), }; }, removeDimension({ prevState, layerId, columnId }) { - const newLayer = prevState.layers.find(l => l.layerId === layerId); + const newLayer = prevState.layers.find((l) => l.layerId === layerId); if (!newLayer) { return prevState; } @@ -236,18 +236,18 @@ export const xyVisualization: Visualization = { } else if (newLayer.splitAccessor === columnId) { delete newLayer.splitAccessor; } else if (newLayer.accessors.includes(columnId)) { - newLayer.accessors = newLayer.accessors.filter(a => a !== columnId); + newLayer.accessors = newLayer.accessors.filter((a) => a !== columnId); } return { ...prevState, - layers: prevState.layers.map(l => (l.layerId === layerId ? newLayer : l)), + layers: prevState.layers.map((l) => (l.layerId === layerId ? newLayer : l)), }; }, getLayerContextMenuIcon({ state, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); - return visualizationTypes.find(t => t.id === layer?.seriesType)?.icon; + const layer = state.layers.find((l) => l.layerId === layerId); + return visualizationTypes.find((t) => t.id === layer?.seriesType)?.icon; }, renderLayerContextMenu(domElement, props) { diff --git a/x-pack/plugins/lens/server/migrations.ts b/x-pack/plugins/lens/server/migrations.ts index eba7865028645..d24a3e92cbd9c 100644 --- a/x-pack/plugins/lens/server/migrations.ts +++ b/x-pack/plugins/lens/server/migrations.ts @@ -62,7 +62,7 @@ const removeLensAutoDate: SavedObjectMigrationFn = ( } try { const ast = fromExpression(expression); - const newChain: ExpressionFunctionAST[] = ast.chain.map(topNode => { + const newChain: ExpressionFunctionAST[] = ast.chain.map((topNode) => { if (topNode.function !== 'lens_merge_tables') { return topNode; } @@ -70,10 +70,10 @@ const removeLensAutoDate: SavedObjectMigrationFn = ( ...topNode, arguments: { ...topNode.arguments, - tables: (topNode.arguments.tables as Ast[]).map(middleNode => { + tables: (topNode.arguments.tables as Ast[]).map((middleNode) => { return { type: 'expression', - chain: middleNode.chain.map(node => { + chain: middleNode.chain.map((node) => { // Check for sub-expression in aggConfigs if ( node.function === 'esaggs' && @@ -120,7 +120,7 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = try { const ast = fromExpression(expression); - const newChain: ExpressionFunctionAST[] = ast.chain.map(topNode => { + const newChain: ExpressionFunctionAST[] = ast.chain.map((topNode) => { if (topNode.function !== 'lens_merge_tables') { return topNode; } @@ -128,10 +128,10 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = ...topNode, arguments: { ...topNode.arguments, - tables: (topNode.arguments.tables as Ast[]).map(middleNode => { + tables: (topNode.arguments.tables as Ast[]).map((middleNode) => { return { type: 'expression', - chain: middleNode.chain.map(node => { + chain: middleNode.chain.map((node) => { // Skip if there are any timeField arguments already, because that indicates // the fix is already applied if (node.function !== 'esaggs' || node.arguments.timeFields) { @@ -176,7 +176,7 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = const removeInvalidAccessors: SavedObjectMigrationFn< LensDocShape, LensDocShape -> = doc => { +> = (doc) => { const newDoc = cloneDeep(doc); if (newDoc.attributes.visualizationType === 'lnsXY') { const datasourceLayers = newDoc.attributes.state.datasourceStates.indexpattern.layers || {}; @@ -190,7 +190,7 @@ const removeInvalidAccessors: SavedObjectMigrationFn< ...layer, xAccessor: datasource?.columns[layer.xAccessor] ? layer.xAccessor : undefined, splitAccessor: datasource?.columns[layer.splitAccessor] ? layer.splitAccessor : undefined, - accessors: layer.accessors.filter(accessor => !!datasource?.columns[accessor]), + accessors: layer.accessors.filter((accessor) => !!datasource?.columns[accessor]), }; }); } diff --git a/x-pack/plugins/lens/server/routes/existing_fields.test.ts b/x-pack/plugins/lens/server/routes/existing_fields.test.ts index ed1f85ab902f8..33541c7206c53 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.test.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.test.ts @@ -143,7 +143,7 @@ describe('buildFieldList', () => { it('uses field descriptors to determine the path', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.name === 'baz')).toMatchObject({ + expect(fields.find((f) => f.name === 'baz')).toMatchObject({ isAlias: false, isScript: false, name: 'baz', @@ -153,7 +153,7 @@ describe('buildFieldList', () => { it('uses aliases to determine the path', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.isAlias)).toMatchObject({ + expect(fields.find((f) => f.isAlias)).toMatchObject({ isAlias: true, isScript: false, name: '@bar', @@ -163,7 +163,7 @@ describe('buildFieldList', () => { it('supports scripted fields', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.isScript)).toMatchObject({ + expect(fields.find((f) => f.isScript)).toMatchObject({ isAlias: false, isScript: true, name: 'foo', diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts index 3e91d17950061..4edd0d1fa68e8 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -171,7 +171,7 @@ export function buildFieldList( ): Field[] { const aliasMap = Object.entries(Object.values(mappings)[0].mappings.properties) .map(([name, v]) => ({ ...v, name })) - .filter(f => f.type === 'alias') + .filter((f) => f.type === 'alias') .reduce((acc, f) => { acc[f.name] = f.path; return acc; @@ -236,7 +236,7 @@ async function fetchIndexPatternStats({ }, }; - const scriptedFields = fields.filter(f => f.isScript); + const scriptedFields = fields.filter((f) => f.isScript); const result = await client.callAsCurrentUser('search', { index, body: { @@ -270,18 +270,18 @@ function exists(obj: unknown, path: string[], i = 0): boolean { } if (Array.isArray(obj)) { - return obj.some(child => exists(child, path, i)); + return obj.some((child) => exists(child, path, i)); } if (typeof obj === 'object') { // Because Elasticsearch flattens paths, dots in the field name are allowed // as JSON keys. For example, { 'a.b': 10 } const partialKeyMatches = Object.getOwnPropertyNames(obj) - .map(key => key.split('.')) - .filter(keyPaths => keyPaths.every((key, keyIndex) => key === path[keyIndex + i])); + .map((key) => key.split('.')) + .filter((keyPaths) => keyPaths.every((key, keyIndex) => key === path[keyIndex + i])); if (partialKeyMatches.length) { - return partialKeyMatches.every(keyPaths => { + return partialKeyMatches.every((keyPaths) => { return exists( (obj as Record)[keyPaths.join('.')], path, @@ -310,12 +310,12 @@ export function existingFields( break; } - missingFields.forEach(field => { + missingFields.forEach((field) => { if (exists(field.isScript ? doc.fields : doc._source, field.path)) { missingFields.delete(field); } }); } - return fields.filter(field => !missingFields.has(field)).map(f => f.name); + return fields.filter((field) => !missingFields.has(field)).map((f) => f.name); } diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts index 5c91be9dfbd78..d7fcffa034a2a 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -149,7 +149,7 @@ export async function getNumberHistogram( const maxValue = minMaxResult.aggregations!.sample.max_value.value; const terms = minMaxResult.aggregations!.sample.top_values; const topValuesBuckets = { - buckets: terms.buckets.map(bucket => ({ + buckets: terms.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -195,7 +195,7 @@ export async function getNumberHistogram( sampledDocuments: minMaxResult.aggregations!.sample.doc_count, sampledValues: minMaxResult.aggregations!.sample.sample_count.value!, histogram: { - buckets: histogramResult.aggregations!.sample.histo.buckets.map(bucket => ({ + buckets: histogramResult.aggregations!.sample.histo.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -230,7 +230,7 @@ export async function getStringSamples( sampledDocuments: topValuesResult.aggregations!.sample.doc_count, sampledValues: topValuesResult.aggregations!.sample.sample_count.value!, topValues: { - buckets: topValuesResult.aggregations!.sample.top_values.buckets.map(bucket => ({ + buckets: topValuesResult.aggregations!.sample.top_values.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -276,7 +276,7 @@ export async function getDateHistogram( return { totalDocuments: results.hits.total, histogram: { - buckets: results.aggregations!.histo.buckets.map(bucket => ({ + buckets: results.aggregations!.histo.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), diff --git a/x-pack/plugins/lens/server/usage/collectors.ts b/x-pack/plugins/lens/server/usage/collectors.ts index 52de0df6fed13..3f033bd3b03d0 100644 --- a/x-pack/plugins/lens/server/usage/collectors.ts +++ b/x-pack/plugins/lens/server/usage/collectors.ts @@ -61,7 +61,7 @@ export function registerLensUsageCollector( } function addEvents(prevEvents: Record, newEvents: Record) { - Object.keys(newEvents).forEach(key => { + Object.keys(newEvents).forEach((key) => { prevEvents[key] = (prevEvents[key] || 0) + newEvents[key]; }); } @@ -88,19 +88,15 @@ async function getLatestTaskState(taskManager: TaskManagerStartContract) { } function getDataByDate(dates: Record>) { - const byDate = Object.keys(dates || {}).map(dateStr => parseInt(dateStr, 10)); + const byDate = Object.keys(dates || {}).map((dateStr) => parseInt(dateStr, 10)); const last30: Record = {}; const last90: Record = {}; - const last30Timestamp = moment() - .subtract(30, 'days') - .unix(); - const last90Timestamp = moment() - .subtract(90, 'days') - .unix(); + const last30Timestamp = moment().subtract(30, 'days').unix(); + const last90Timestamp = moment().subtract(90, 'days').unix(); - byDate.forEach(dateKey => { + byDate.forEach((dateKey) => { if (dateKey >= last30Timestamp) { addEvents(last30, dates[dateKey]); addEvents(last90, dates[dateKey]); diff --git a/x-pack/plugins/lens/server/usage/task.ts b/x-pack/plugins/lens/server/usage/task.ts index e1a0bf20f7b48..5a5d26fa2afde 100644 --- a/x-pack/plugins/lens/server/usage/task.ts +++ b/x-pack/plugins/lens/server/usage/task.ts @@ -140,15 +140,15 @@ export async function getDailyEvents( const byDateByType: Record> = {}; const suggestionsByDate: Record> = {}; - metrics.aggregations!.daily.buckets.forEach(daily => { + metrics.aggregations!.daily.buckets.forEach((daily) => { const byType: Record = byDateByType[daily.key] || {}; - daily.groups.buckets.regularEvents.names.buckets.forEach(bucket => { + daily.groups.buckets.regularEvents.names.buckets.forEach((bucket) => { byType[bucket.key] = (bucket.sums.value || 0) + (byType[daily.key] || 0); }); byDateByType[daily.key] = byType; const suggestionsByType: Record = suggestionsByDate[daily.key] || {}; - daily.groups.buckets.suggestionEvents.names.buckets.forEach(bucket => { + daily.groups.buckets.suggestionEvents.names.buckets.forEach((bucket) => { suggestionsByType[bucket.key] = (bucket.sums.value || 0) + (suggestionsByType[daily.key] || 0); }); @@ -208,7 +208,7 @@ export function telemetryTaskRunner( runAt: getNextMidnight(), }; }) - .catch(errMsg => logger.warn(`Error executing lens telemetry task: ${errMsg}`)); + .catch((errMsg) => logger.warn(`Error executing lens telemetry task: ${errMsg}`)); }, async cancel() {}, }; @@ -216,8 +216,5 @@ export function telemetryTaskRunner( } function getNextMidnight() { - return moment() - .add(1, 'day') - .startOf('day') - .toDate(); + return moment().add(1, 'day').startOf('day').toDate(); } diff --git a/x-pack/plugins/license_management/__mocks__/focus-trap-react.js b/x-pack/plugins/license_management/__mocks__/focus-trap-react.js index 6cc385e871b47..2e243aceccb15 100644 --- a/x-pack/plugins/license_management/__mocks__/focus-trap-react.js +++ b/x-pack/plugins/license_management/__mocks__/focus-trap-react.js @@ -6,4 +6,4 @@ import React from 'react'; -export default props =>
{props.children}
; +export default (props) =>
{props.children}
; diff --git a/x-pack/plugins/license_management/public/application/app.container.js b/x-pack/plugins/license_management/public/application/app.container.js index 248f4f63027c9..0c67cc636edd7 100644 --- a/x-pack/plugins/license_management/public/application/app.container.js +++ b/x-pack/plugins/license_management/public/application/app.container.js @@ -15,7 +15,7 @@ import { } from './store/reducers/license_management'; import { loadPermissions } from './store/actions/permissions'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { hasPermission: getPermission(state), permissionsLoading: isPermissionsLoading(state), diff --git a/x-pack/plugins/license_management/public/application/app.js b/x-pack/plugins/license_management/public/application/app.js index 1bc8e9cd563e2..46d0da5252ceb 100644 --- a/x-pack/plugins/license_management/public/application/app.js +++ b/x-pack/plugins/license_management/public/application/app.js @@ -85,7 +85,7 @@ export class App extends Component { ); } - const withTelemetry = Component => props => ; + const withTelemetry = (Component) => (props) => ; return ( diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js index 696c53fc9ca6b..3425fe0339dc4 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js @@ -13,7 +13,7 @@ import { } from '../../../store/reducers/license_management'; import { i18n } from '@kbn/i18n'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { isActive, type } = getLicense(state); return { status: isActive diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js index 580e8de0b304b..517cf9bb36a46 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js @@ -9,7 +9,7 @@ import { connect } from 'react-redux'; import { RequestTrialExtension as PresentationComponent } from './request_trial_extension'; import { shouldShowRequestTrialExtension } from '../../../store/reducers/license_management'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowRequestTrialExtension: shouldShowRequestTrialExtension(state), }; diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js index f171ce8ecf353..4e0c40bf9eb6b 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js @@ -15,7 +15,7 @@ import { } from '../../../store/reducers/license_management'; import { startBasicLicense, cancelStartBasicLicense } from '../../../store/actions/start_basic'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowRevertToBasicLicense: shouldShowRevertToBasicLicense(state), licenseType: getLicenseType(state), diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js index 2424e336fe6e6..a1a46d8616554 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js @@ -62,7 +62,7 @@ export class RevertToBasic extends React.PureComponent { {firstLine}
    - {messages.map(message => ( + {messages.map((message) => (
  • {message}
  • ))}
diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js index 7f95ba55db150..61fae1e49afe6 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js @@ -10,7 +10,7 @@ import { StartTrial as PresentationComponent } from './start_trial'; import { loadTrialStatus, startLicenseTrial } from '../../../store/actions/start_trial'; import { shouldShowStartTrial } from '../../../store/reducers/license_management'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowStartTrial: shouldShowStartTrial(state), }; diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx index 25cbfb7242239..627eb0425c6d7 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx @@ -266,7 +266,7 @@ export class StartTrial extends Component { ); return ( - {dependencies => ( + {(dependencies) => ( {this.acknowledgeModal(dependencies!.docLinks)} { +const mapStateToProps = (state) => { return { isInvalid: isInvalid(state), needsAcknowledgement: uploadNeedsAcknowledgement(state), diff --git a/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js b/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js index 49f2474f83911..95ada7ed2b1df 100644 --- a/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js +++ b/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js @@ -34,10 +34,10 @@ export class UploadLicense extends React.PureComponent { this.props.setBreadcrumb('upload'); this.props.addUploadErrorMessage(''); } - onOptInChange = isOptingInToTelemetry => { + onOptInChange = (isOptingInToTelemetry) => { this.setState({ isOptingInToTelemetry }); }; - send = acknowledge => { + send = (acknowledge) => { const file = this.file; const fr = new FileReader(); @@ -87,7 +87,7 @@ export class UploadLicense extends React.PureComponent { {firstLine}
    - {messages.map(message => ( + {messages.map((message) => (
  • {message}
  • ))}
@@ -110,7 +110,7 @@ export class UploadLicense extends React.PureComponent { } this.file = file; }; - submit = event => { + submit = (event) => { event.preventDefault(); if (this.file) { this.send(); diff --git a/x-pack/plugins/license_management/public/application/store/actions/start_basic.js b/x-pack/plugins/license_management/public/application/store/actions/start_basic.js index 93c722c1f8968..5ae93bf84c2f8 100644 --- a/x-pack/plugins/license_management/public/application/store/actions/start_basic.js +++ b/x-pack/plugins/license_management/public/application/store/actions/start_basic.js @@ -38,7 +38,7 @@ export const startBasicLicense = (currentLicenseType, ack) => async ( //messages coming back in arrays const messages = Object.values(acknowledge) .slice(1) - .map(item => { + .map((item) => { return item[0]; }); const first = i18n.translate( diff --git a/x-pack/plugins/license_management/public/application/store/reducers/license_management.js b/x-pack/plugins/license_management/public/application/store/reducers/license_management.js index c821b7bb294f9..ca7e51b106951 100644 --- a/x-pack/plugins/license_management/public/application/store/reducers/license_management.js +++ b/x-pack/plugins/license_management/public/application/store/reducers/license_management.js @@ -24,31 +24,31 @@ export const licenseManagement = combineReducers({ permissions, }); -export const getPermission = state => { +export const getPermission = (state) => { return state.permissions.hasPermission; }; -export const isPermissionsLoading = state => { +export const isPermissionsLoading = (state) => { return state.permissions.loading; }; -export const getPermissionsError = state => { +export const getPermissionsError = (state) => { return state.permissions.error; }; -export const getLicense = state => { +export const getLicense = (state) => { return state.license; }; -export const getLicenseType = state => { +export const getLicenseType = (state) => { return getLicense(state).type; }; -export const getExpirationMillis = state => { +export const getExpirationMillis = (state) => { return getLicense(state).expiryDateInMillis; }; -export const getExpirationDate = state => { +export const getExpirationDate = (state) => { //basic licenses do not expire if (getLicenseType(state) === 'basic') { return null; @@ -61,16 +61,16 @@ export const getExpirationDate = state => { } }; -export const getExpirationDateFormatted = state => { +export const getExpirationDateFormatted = (state) => { const expirationDate = getExpirationDate(state); return expirationDate ? expirationDate.format('LLL z') : null; }; -export const isExpired = state => { +export const isExpired = (state) => { return new Date().getTime() > getExpirationMillis(state); }; -export const isImminentExpiration = state => { +export const isImminentExpiration = (state) => { const now = new Date(); const expirationDate = getExpirationDate(state); return ( @@ -80,32 +80,32 @@ export const isImminentExpiration = state => { ); }; -export const shouldShowRevertToBasicLicense = state => { +export const shouldShowRevertToBasicLicense = (state) => { const { type } = getLicense(state); return type === 'trial' || isImminentExpiration(state) || isExpired(state); }; -export const uploadNeedsAcknowledgement = state => { +export const uploadNeedsAcknowledgement = (state) => { return !!state.uploadStatus.acknowledge; }; -export const isApplying = state => { +export const isApplying = (state) => { return !!state.uploadStatus.applying; }; -export const uploadMessages = state => { +export const uploadMessages = (state) => { return state.uploadStatus.messages; }; -export const isInvalid = state => { +export const isInvalid = (state) => { return !!state.uploadStatus.invalid; }; -export const getUploadErrorMessage = state => { +export const getUploadErrorMessage = (state) => { return state.uploadErrorMessage; }; -export const shouldShowStartTrial = state => { +export const shouldShowStartTrial = (state) => { const licenseType = getLicenseType(state); return ( state.trialStatus.canStartTrial && @@ -115,7 +115,7 @@ export const shouldShowStartTrial = state => { ); }; -export const shouldShowRequestTrialExtension = state => { +export const shouldShowRequestTrialExtension = (state) => { if (state.trialStatus.canStartTrial) { return false; } @@ -123,14 +123,14 @@ export const shouldShowRequestTrialExtension = state => { return (type !== 'platinum' && type !== 'enterprise') || isExpired(state); }; -export const startTrialError = state => { +export const startTrialError = (state) => { return state.trialStatus.startTrialError; }; -export const startBasicLicenseNeedsAcknowledgement = state => { +export const startBasicLicenseNeedsAcknowledgement = (state) => { return !!state.startBasicStatus.acknowledge; }; -export const getStartBasicMessages = state => { +export const getStartBasicMessages = (state) => { return state.startBasicStatus.messages; }; diff --git a/x-pack/plugins/licensing/common/license_update.test.ts b/x-pack/plugins/licensing/common/license_update.test.ts index 7e2410913f698..b0209e0717da2 100644 --- a/x-pack/plugins/licensing/common/license_update.test.ts +++ b/x-pack/plugins/licensing/common/license_update.test.ts @@ -11,7 +11,7 @@ import { ILicense } from './types'; import { createLicenseUpdate } from './license_update'; import { licenseMock } from './licensing.mock'; -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const stop$ = new Subject(); describe('licensing update', () => { it('loads updates when triggered', async () => { @@ -94,7 +94,7 @@ describe('licensing update', () => { let firstCall = true; const fetcher = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { if (firstCall) { firstCall = false; setTimeout(() => resolve(licenseMock.createLicense()), delayMs); @@ -106,7 +106,7 @@ describe('licensing update', () => { const trigger$ = new Subject(); const { license$ } = createLicenseUpdate(trigger$, stop$, fetcher); const values: ILicense[] = []; - license$.subscribe(license => values.push(license)); + license$.subscribe((license) => values.push(license)); trigger$.next(); trigger$.next(); @@ -136,7 +136,7 @@ describe('licensing update', () => { const { license$ } = createLicenseUpdate(trigger$, stop$, fetcher); const values: ILicense[] = []; - license$.subscribe(license => values.push(license)); + license$.subscribe((license) => values.push(license)); stop$.next(); trigger$.next(); @@ -162,7 +162,7 @@ describe('licensing update', () => { const { license$, refreshManually } = createLicenseUpdate(trigger$, stop$, fetcher); let fromObservable; - license$.subscribe(license => (fromObservable = license)); + license$.subscribe((license) => (fromObservable = license)); const licenseResult = await refreshManually(); expect(licenseResult.uid).toBe('first'); diff --git a/x-pack/plugins/licensing/public/expired_banner.tsx b/x-pack/plugins/licensing/public/expired_banner.tsx index 9c42d3ff6997d..b261bfa9f345f 100644 --- a/x-pack/plugins/licensing/public/expired_banner.tsx +++ b/x-pack/plugins/licensing/public/expired_banner.tsx @@ -14,7 +14,7 @@ interface Props { uploadUrl: string; } -const ExpiredBanner: React.FunctionComponent = props => ( +const ExpiredBanner: React.FunctionComponent = (props) => ( { const { license$, refresh } = await plugin.setup(coreSetup); let fromObservable; - license$.subscribe(license => (fromObservable = license)); + license$.subscribe((license) => (fromObservable = license)); const licenseResult = await refresh(); expect(licenseResult.uid).toBe('first'); @@ -88,7 +88,7 @@ describe('licensing plugin', () => { expect(sessionStorage.getItem).toHaveBeenCalledWith(licensingSessionStorageKey); }); - it('observable receives updated licenses', async done => { + it('observable receives updated licenses', async (done) => { const types: LicenseType[] = ['gold', 'platinum']; const sessionStorage = coreMock.createStorage(); @@ -102,7 +102,7 @@ describe('licensing plugin', () => { const { license$, refresh } = await plugin.setup(coreSetup); let i = 0; - license$.subscribe(value => { + license$.subscribe((value) => { i++; if (i === 1) { expect(value.type).toBe('basic'); diff --git a/x-pack/plugins/licensing/public/plugin.ts b/x-pack/plugins/licensing/public/plugin.ts index 31910d81b3434..6435f3b17313c 100644 --- a/x-pack/plugins/licensing/public/plugin.ts +++ b/x-pack/plugins/licensing/public/plugin.ts @@ -75,7 +75,7 @@ export class LicensingPlugin implements Plugin { this.getSaved() ); - this.internalSubscription = license$.subscribe(license => { + this.internalSubscription = license$.subscribe((license) => { if (license.isAvailable) { this.prevSignature = license.signature; this.save(license); @@ -92,7 +92,7 @@ export class LicensingPlugin implements Plugin { }); this.removeInterceptor = core.http.intercept({ - response: async httpResponse => { + response: async (httpResponse) => { // we don't track license as anon users do not have one. if (core.http.anonymousPaths.isAnonymous(window.location.pathname)) return httpResponse; if (httpResponse.response) { diff --git a/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts b/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts index 9a588a9ac8460..5c768a00783a8 100644 --- a/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts +++ b/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts @@ -30,7 +30,7 @@ describe('createOnPreResponseHandler', () => { const license$ = new BehaviorSubject(licenseMock.createLicense({ signature: 'foo' })); const refresh = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(() => { license$.next(updatedLicense); resolve(); diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts index c9fbb61e6cc19..1dacc9406004a 100644 --- a/x-pack/plugins/licensing/server/plugin.test.ts +++ b/x-pack/plugins/licensing/server/plugin.test.ts @@ -26,7 +26,7 @@ function buildRawLicense(options: Partial = {}): RawLicense { return Object.assign(defaultRawLicense, options); } -const flushPromises = (ms = 50) => new Promise(res => setTimeout(res, ms)); +const flushPromises = (ms = 50) => new Promise((res) => setTimeout(res, ms)); describe('licensing plugin', () => { describe('#setup', () => { diff --git a/x-pack/plugins/licensing/server/plugin.ts b/x-pack/plugins/licensing/server/plugin.ts index ee43ac0ce233c..51e778ba0aa46 100644 --- a/x-pack/plugins/licensing/server/plugin.ts +++ b/x-pack/plugins/licensing/server/plugin.ts @@ -123,7 +123,7 @@ export class LicensingPlugin implements Plugin + this.loggingSubscription = license$.subscribe((license) => this.logger.debug( 'Imported license information from Elasticsearch:' + [ diff --git a/x-pack/plugins/licensing/server/services/feature_usage_service.ts b/x-pack/plugins/licensing/server/services/feature_usage_service.ts index 47ffe3a3d9f54..0c6613d37f63a 100644 --- a/x-pack/plugins/licensing/server/services/feature_usage_service.ts +++ b/x-pack/plugins/licensing/server/services/feature_usage_service.ts @@ -36,7 +36,7 @@ export class FeatureUsageService { public setup(): FeatureUsageServiceSetup { return { - register: featureName => { + register: (featureName) => { if (this.features.includes(featureName)) { throw new Error(`Feature '${featureName}' has already been registered.`); } diff --git a/x-pack/plugins/lists/server/create_config.ts b/x-pack/plugins/lists/server/create_config.ts index 3158fabda935f..7e2e639ce7a35 100644 --- a/x-pack/plugins/lists/server/create_config.ts +++ b/x-pack/plugins/lists/server/create_config.ts @@ -12,10 +12,12 @@ import { ConfigType } from './config'; export const createConfig$ = ( context: PluginInitializerContext -): Observable> => { - return context.config.create().pipe(map(config => config)); +): Observable< + Readonly<{ + enabled: boolean; + listIndex: string; + listItemIndex: string; + }> +> => { + return context.config.create().pipe(map((config) => config)); }; diff --git a/x-pack/plugins/lists/server/plugin.ts b/x-pack/plugins/lists/server/plugin.ts index ed515757875be..dbda144239927 100644 --- a/x-pack/plugins/lists/server/plugin.ts +++ b/x-pack/plugins/lists/server/plugin.ts @@ -39,9 +39,7 @@ export class ListPlugin } public async setup(core: CoreSetup, plugins: PluginsSetup): Promise { - const config = await createConfig$(this.initializerContext) - .pipe(first()) - .toPromise(); + const config = await createConfig$(this.initializerContext).pipe(first()).toPromise(); this.logger.error( 'You have activated the lists values feature flag which is NOT currently supported for Elastic Security! You should turn this feature flag off immediately by un-setting "xpack.lists.enabled: true" in kibana.yml and restarting Kibana' diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts index 8031f085c1635..31bf1ffacbbb2 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts @@ -46,7 +46,10 @@ export const getExceptionListItemIds = async ({ sortOrder: 'desc', }); while (foundExceptionListItems != null && foundExceptionListItems.data.length > 0) { - ids = [...ids, ...foundExceptionListItems.data.map(exceptionListItem => exceptionListItem.id)]; + ids = [ + ...ids, + ...foundExceptionListItems.data.map((exceptionListItem) => exceptionListItem.id), + ]; page += 1; foundExceptionListItems = await findExceptionListItem({ filter: undefined, @@ -76,7 +79,7 @@ export const deleteFoundExceptionListItems = async ({ namespaceType: NamespaceType; }): Promise => { const savedObjectType = getSavedObjectType({ namespaceType }); - ids.forEach(async id => { + ids.forEach(async (id) => { try { await savedObjectsClient.delete(savedObjectType, id); } catch (err) { diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.ts index 505ebc43afc5a..28dfb9c1cddaf 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.ts @@ -210,7 +210,7 @@ export const transformSavedObjectsToFounExceptionListItem = ({ savedObjectsFindResponse: SavedObjectsFindResponse; }): FoundExceptionListItemSchema => { return { - data: savedObjectsFindResponse.saved_objects.map(savedObject => + data: savedObjectsFindResponse.saved_objects.map((savedObject) => transformSavedObjectToExceptionListItem({ savedObject }) ), page: savedObjectsFindResponse.page, @@ -225,7 +225,7 @@ export const transformSavedObjectsToFounExceptionList = ({ savedObjectsFindResponse: SavedObjectsFindResponse; }): FoundExceptionListSchema => { return { - data: savedObjectsFindResponse.saved_objects.map(savedObject => + data: savedObjectsFindResponse.saved_objects.map((savedObject) => transformSavedObjectToExceptionList({ savedObject }) ), page: savedObjectsFindResponse.page, diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts b/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts index 50e690a3185a8..9413bf9a3d84e 100644 --- a/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts +++ b/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts @@ -9,7 +9,7 @@ import { TestReadable } from '../../../common/test_readable.mock'; import { BufferLines } from './buffer_lines'; describe('buffer_lines', () => { - test('it can read a single line', done => { + test('it can read a single line', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push(null); @@ -24,7 +24,7 @@ describe('buffer_lines', () => { }); }); - test('it can read two lines', done => { + test('it can read two lines', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push('line two\n'); @@ -40,7 +40,7 @@ describe('buffer_lines', () => { }); }); - test('two identical lines are collapsed into just one line without duplicates', done => { + test('two identical lines are collapsed into just one line without duplicates', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push('line one\n'); @@ -56,7 +56,7 @@ describe('buffer_lines', () => { }); }); - test('it can close out without writing any lines', done => { + test('it can close out without writing any lines', (done) => { const input = new TestReadable(); input.push(null); const bufferedLine = new BufferLines({ input }); @@ -70,12 +70,12 @@ describe('buffer_lines', () => { }); }); - test('it can read 200 lines', done => { + test('it can read 200 lines', (done) => { const input = new TestReadable(); const bufferedLine = new BufferLines({ input }); let linesToTest: string[] = []; const size200: string[] = new Array(200).fill(null).map((_, index) => `${index}\n`); - size200.forEach(element => input.push(element)); + size200.forEach((element) => input.push(element)); input.push(null); bufferedLine.on('lines', (lines: string[]) => { linesToTest = [...linesToTest, ...lines]; diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.ts b/x-pack/plugins/lists/server/services/items/buffer_lines.ts index fd8fe7077fd58..4ff84268f5e0c 100644 --- a/x-pack/plugins/lists/server/services/items/buffer_lines.ts +++ b/x-pack/plugins/lists/server/services/items/buffer_lines.ts @@ -17,7 +17,7 @@ export class BufferLines extends Readable { input, }); - readline.on('line', line => { + readline.on('line', (line) => { this.push(line); }); diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts b/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts index ec29f14a0ff64..57aced5f3701c 100644 --- a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts +++ b/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts @@ -33,7 +33,7 @@ export const deleteListItemByValue = async ({ type, value: [value], }); - const values = listItems.map(listItem => listItem.value); + const values = listItems.map((listItem) => listItem.value); const filter = getQueryFilterFromTypeValue({ listId, type, diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts index 542c2bb12d8e5..b309779962889 100644 --- a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts +++ b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts @@ -33,7 +33,7 @@ export const importListItemsToStream = ({ user, meta, }: ImportListItemsToStreamOptions): Promise => { - return new Promise(resolve => { + return new Promise((resolve) => { const readBuffer = new BufferLines({ input: stream }); readBuffer.on('lines', async (lines: string[]) => { await writeBufferToItems({ @@ -85,7 +85,7 @@ export const writeBufferToItems = async ({ value: buffer, }); const duplicatesRemoved = buffer.filter( - bufferedValue => !items.some(item => item.value === bufferedValue) + (bufferedValue) => !items.some((item) => item.value === bufferedValue) ); const linesProcessed = duplicatesRemoved.length; const duplicatesFound = buffer.length - duplicatesRemoved.length; diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts index 2f04353e0989b..b1ab0dc2ad613 100644 --- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts +++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts @@ -33,7 +33,7 @@ describe('write_list_items_to_stream', () => { }); describe('exportListItemsToStream', () => { - test('It exports empty list items to the stream as an empty array', done => { + test('It exports empty list items to the stream as an empty array', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); firstResponse.hits.hits = []; @@ -51,7 +51,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports single list item to the stream', done => { + test('It exports single list item to the stream', (done) => { const options = getExportListItemsToStreamOptionsMock(); exportListItemsToStream(options); @@ -66,7 +66,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports two list items to the stream', done => { + test('It exports two list items to the stream', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); const secondResponse = getSearchListItemMock(); @@ -85,7 +85,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports two list items to the stream with two separate calls', done => { + test('It exports two list items to the stream with two separate calls', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); @@ -209,7 +209,7 @@ describe('write_list_items_to_stream', () => { }); describe('writeResponseHitsToStream', () => { - test('it will push into the stream the mock response', done => { + test('it will push into the stream the mock response', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); writeResponseHitsToStream(options); @@ -224,7 +224,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('it will push into the stream an empty mock response', done => { + test('it will push into the stream an empty mock response', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); options.response.hits.hits = []; writeResponseHitsToStream(options); @@ -241,7 +241,7 @@ describe('write_list_items_to_stream', () => { options.stream.end(); }); - test('it will push into the stream 2 mock responses', done => { + test('it will push into the stream 2 mock responses', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); const secondResponse = getSearchListItemMock(); options.response.hits.hits = [...options.response.hits.hits, ...secondResponse.hits.hits]; @@ -258,7 +258,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('it will push an additional string given to it such as a new line character', done => { + test('it will push an additional string given to it such as a new line character', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); const secondResponse = getSearchListItemMock(); options.response.hits.hits = [...options.response.hits.hits, ...secondResponse.hits.hits]; diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts index b81e4a4fc73c2..10d8581ccdbc0 100644 --- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts +++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts @@ -143,7 +143,7 @@ export const writeResponseHitsToStream = ({ }: WriteResponseHitsToStreamOptions): void => { const stringToAppendOrEmpty = stringToAppend ?? ''; - response.hits.hits.forEach(hit => { + response.hits.hits.forEach((hit) => { if (hit._source.ip != null) { stream.push(`${hit._source.ip}${stringToAppendOrEmpty}`); } else if (hit._source.keyword != null) { diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 2dc0f4fe7a821..f150a29c524a5 100644 --- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts +++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts @@ -18,7 +18,7 @@ export const transformElasticToListItem = ({ response, type, }: TransformElasticToListItemOptions): ListItemArraySchema => { - return response.hits.hits.map(hit => { + return response.hits.hits.map((hit) => { const { _id, _source: { diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js index e45820d56cc03..694e50cfe3e36 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js @@ -157,7 +157,7 @@ class PipelineEditorUi extends React.Component { }); }; - onPipelineChange = e => { + onPipelineChange = (e) => { this.setState({ pipeline: { ...this.state.pipeline, @@ -171,12 +171,12 @@ class PipelineEditorUi extends React.Component { this.handleSettingChange(settingName, isNaN(numberValue) ? value : numberValue); }; - handleMaxByteNumberChange = value => { + handleMaxByteNumberChange = (value) => { this.setState({ maxBytesNumber: parseInt(value, 10) }); this.handleSettingChange('queue.max_bytes', value + this.state.maxBytesUnit); }; - handleMaxByteUnitChange = value => { + handleMaxByteUnitChange = (value) => { this.setState({ maxBytesUnit: value }); this.handleSettingChange('queue.max_bytes', this.state.maxBytesNumber + value); }; @@ -192,7 +192,7 @@ class PipelineEditorUi extends React.Component { }); }; - notifyOnError = err => { + notifyOnError = (err) => { const { licenseService, toastNotifications } = this.props; return licenseService.checkValidity().then(() => { @@ -356,7 +356,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.workers', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.workers', e.target.value)} value={this.state.pipeline.settings['pipeline.workers']} /> @@ -371,7 +371,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.batch.size', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.batch.size', e.target.value)} value={this.state.pipeline.settings['pipeline.batch.size']} /> @@ -384,7 +384,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.batch.delay', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.batch.delay', e.target.value)} value={this.state.pipeline.settings['pipeline.batch.delay']} /> @@ -399,7 +399,7 @@ class PipelineEditorUi extends React.Component { > this.handleSettingChange('queue.type', e.target.value)} + onChange={(e) => this.handleSettingChange('queue.type', e.target.value)} options={PIPELINE_EDITOR.QUEUE_TYPES} value={this.state.pipeline.settings['queue.type']} /> @@ -413,14 +413,14 @@ class PipelineEditorUi extends React.Component { > this.handleMaxByteNumberChange(e.target.value)} + onChange={(e) => this.handleMaxByteNumberChange(e.target.value)} value={this.state.maxBytesNumber} /> this.handleMaxByteUnitChange(e.target.value)} + onChange={(e) => this.handleMaxByteUnitChange(e.target.value)} options={PIPELINE_EDITOR.UNITS} value={this.state.maxBytesUnit} /> @@ -434,7 +434,9 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('queue.checkpoint.writes', e.target.value)} + onChange={(e) => + this.handleNumberChange('queue.checkpoint.writes', e.target.value) + } value={this.state.pipeline.settings['queue.checkpoint.writes']} /> diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js index a5052edf03403..bbf91f2c0b957 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js @@ -36,19 +36,13 @@ describe('ConfirmDeleteModal component', () => { it('calls cancel delete', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="confirmModalCancelButton"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="confirmModalCancelButton"]').first().simulate('click'); expect(props.cancelDeletePipelines).toHaveBeenCalled(); }); it('calls deleteSelectedPipelines', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="confirmModalConfirmButton"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="confirmModalConfirmButton"]').first().simulate('click'); expect(props.deleteSelectedPipelines).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js index bf67c70547bf2..d5ef224e2b81d 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js @@ -108,7 +108,7 @@ class PipelineListUi extends React.Component { return pipelinesService .getPipelineList() - .then(pipelines => { + .then((pipelines) => { this.setState({ isLoading: false, isForbidden: false, @@ -124,7 +124,7 @@ class PipelineListUi extends React.Component { }); } }) - .catch(err => { + .catch((err) => { this.setState({ isLoading: false, message: this.getErrorPrompt(), @@ -159,7 +159,7 @@ class PipelineListUi extends React.Component { checkMonitoringAccess = () => { const { clusterService, monitoringService } = this.props; - clusterService.isClusterInfoAvailable().then(isAvailable => { + clusterService.isClusterInfoAvailable().then((isAvailable) => { this.setState({ showAddRoleAlert: !isAvailable, showEnableMonitoringAlert: !monitoringService.isMonitoringEnabled(), @@ -215,7 +215,7 @@ class PipelineListUi extends React.Component { const pipelineIds = selection.map(({ id }) => id); return pipelinesService .deletePipelines(pipelineIds) - .then(results => { + .then((results) => { const { numSuccesses, numErrors } = results; if (numSuccesses === 1 && numErrors === 0) { @@ -276,7 +276,7 @@ class PipelineListUi extends React.Component { this.loadPipelines(); }) - .catch(err => { + .catch((err) => { return licenseService.checkValidity().then(() => toastNotifications.addDanger(err)); }); }; @@ -285,7 +285,7 @@ class PipelineListUi extends React.Component { this.showDeletePipelinesModal(); }; - onSelectionChange = selection => this.setState({ selection }); + onSelectionChange = (selection) => this.setState({ selection }); render() { const { clonePipeline, createPipeline, isReadOnly, openPipeline } = this.props; diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js index db0b1375c604d..019cd29f7a017 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js @@ -19,9 +19,9 @@ describe('PipelineList component', () => { const getGetPipelineList = (isSuccess, result) => isSuccess ? () => Promise.resolve(result) : () => Promise.reject(result); - const getIsClusterInfoAvailable = isAvailable => () => Promise.resolve(isAvailable); + const getIsClusterInfoAvailable = (isAvailable) => () => Promise.resolve(isAvailable); - const getDeleteSelectedPipelines = isSuccess => + const getDeleteSelectedPipelines = (isSuccess) => isSuccess ? () => Promise.resolve({}) : () => Promise.reject({}); beforeEach(() => { diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js index 9f59a6b7c8abc..b40cc3541eed0 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js @@ -38,7 +38,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.descriptionColumnLabel', { defaultMessage: 'Description', }), - render: description => {description}, + render: (description) => {description}, sortable: true, truncateText: true, }, @@ -47,7 +47,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.lastModifiedColumnLabel', { defaultMessage: 'Last modified', }), - render: lastModified => {lastModified}, + render: (lastModified) => {lastModified}, sortable: ({ lastModified }) => lastModified.valueOf(), }, { @@ -55,7 +55,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.modifiedByColumnLabel', { defaultMessage: 'Modified by', }), - render: username => {username}, + render: (username) => {username}, sortable: true, }, { diff --git a/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx b/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx index c1b465febcd9b..9b291e5261033 100644 --- a/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx +++ b/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx @@ -64,7 +64,7 @@ const useIsUpgraded = (upgradeService: any) => { const mounted = usePromise(); useLayoutEffect(() => { - mounted(upgradeService.executeUpgrade() as Promise).then(result => + mounted(upgradeService.executeUpgrade() as Promise).then((result) => setIsUpgraded(result) ); }, [mounted, upgradeService]); diff --git a/x-pack/plugins/logstash/public/models/pipeline/pipeline.js b/x-pack/plugins/logstash/public/models/pipeline/pipeline.js index 0f098bd599b1d..2b603f7aded02 100755 --- a/x-pack/plugins/logstash/public/models/pipeline/pipeline.js +++ b/x-pack/plugins/logstash/public/models/pipeline/pipeline.js @@ -89,7 +89,7 @@ export class Pipeline { }); } - isEqualTo = otherPipeline => { + isEqualTo = (otherPipeline) => { // We need to create a POJO copies because isEqual would return false // because of property getters const cleanPipeline = { diff --git a/x-pack/plugins/logstash/public/plugin.ts b/x-pack/plugins/logstash/public/plugin.ts index 7d4afc0a4ea13..70fdb420ca2d2 100644 --- a/x-pack/plugins/logstash/public/plugin.ts +++ b/x-pack/plugins/logstash/public/plugin.ts @@ -32,7 +32,7 @@ export class LogstashPlugin implements Plugin { public setup(core: CoreSetup, plugins: SetupDeps) { const logstashLicense$ = plugins.licensing.license$.pipe( - map(license => new LogstashLicenseService(license)) + map((license) => new LogstashLicenseService(license)) ); const managementApp = plugins.management.sections @@ -43,7 +43,7 @@ export class LogstashPlugin implements Plugin { defaultMessage: 'Logstash Pipelines', }), order: 1, - mount: async params => { + mount: async (params) => { const [coreStart] = await core.getStartServices(); const { renderApp } = await import('./application'); const isMonitoringEnabled = 'monitoring' in plugins; diff --git a/x-pack/plugins/logstash/public/services/cluster/cluster_service.js b/x-pack/plugins/logstash/public/services/cluster/cluster_service.js index 20f3b0d349c80..d1d04544031f2 100755 --- a/x-pack/plugins/logstash/public/services/cluster/cluster_service.js +++ b/x-pack/plugins/logstash/public/services/cluster/cluster_service.js @@ -13,7 +13,7 @@ export class ClusterService { } loadCluster() { - return this.http.get(`${ROUTES.API_ROOT}/cluster`).then(response => { + return this.http.get(`${ROUTES.API_ROOT}/cluster`).then((response) => { if (!response) { return; } @@ -23,7 +23,7 @@ export class ClusterService { isClusterInfoAvailable() { return this.loadCluster() - .then(cluster => Boolean(cluster)) + .then((cluster) => Boolean(cluster)) .catch(() => false); } } diff --git a/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js b/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js index 4db2838cb5354..9f57b09ee34b6 100755 --- a/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js +++ b/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js @@ -26,7 +26,7 @@ export class MonitoringService { return this.clusterService .loadCluster() - .then(cluster => { + .then((cluster) => { // This API call should live within the Monitoring plugin // https://github.com/elastic/kibana/issues/63931 const url = `${ROUTES.MONITORING_API_ROOT}/v1/clusters/${cluster.uuid}/logstash/pipeline_ids`; @@ -39,8 +39,8 @@ export class MonitoringService { }); return this.http.post(url, { body }); }) - .then(response => - response.map(pipeline => PipelineListItem.fromUpstreamMonitoringJSON(pipeline)) + .then((response) => + response.map((pipeline) => PipelineListItem.fromUpstreamMonitoringJSON(pipeline)) ) .catch(() => []); } diff --git a/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js b/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js index 7c3e18e745d82..85fa6ea8a93f0 100755 --- a/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js +++ b/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js @@ -14,7 +14,7 @@ export class PipelineService { } loadPipeline(id) { - return this.http.get(`${ROUTES.API_ROOT}/pipeline/${id}`).then(response => { + return this.http.get(`${ROUTES.API_ROOT}/pipeline/${id}`).then((response) => { return Pipeline.fromUpstreamJSON(response); }); } @@ -24,7 +24,7 @@ export class PipelineService { .put(`${ROUTES.API_ROOT}/pipeline/${pipelineModel.id}`, { body: JSON.stringify(pipelineModel.upstreamJSON), }) - .catch(e => { + .catch((e) => { throw e.message; }); } @@ -33,7 +33,7 @@ export class PipelineService { return this.http .delete(`${ROUTES.API_ROOT}/pipeline/${id}`) .then(() => this.pipelinesService.addToRecentlyDeleted(id)) - .catch(e => { + .catch((e) => { throw e.message; }); } diff --git a/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js b/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js index 00610a23f2717..c9bcb54691b64 100755 --- a/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js +++ b/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js @@ -23,8 +23,8 @@ export class PipelinesService { // Monitoring will report centrally-managed pipelines as well, including recently-deleted centrally-managed ones. // If there's a recently-deleted pipeline we're keeping track of BUT monitoring doesn't report it, that means // it's not running in Logstash any more. So we can stop tracking it as a recently-deleted pipeline. - const monitoringPipelineIds = monitoringPipelines.map(pipeline => pipeline.id); - this.getRecentlyDeleted().forEach(recentlyDeletedPipeline => { + const monitoringPipelineIds = monitoringPipelines.map((pipeline) => pipeline.id); + this.getRecentlyDeleted().forEach((recentlyDeletedPipeline) => { // We don't want to stop tracking the recently-deleted pipeline until Monitoring has had some // time to report on it. Otherwise, if we stop tracking first, *then* Monitoring reports it, we'll // still end up showing it in the list until Monitoring stops reporting it. @@ -43,10 +43,10 @@ export class PipelinesService { // Merge centrally-managed pipelines with pipelines reported by monitoring. Take care to dedupe // while merging because monitoring will (rightly) report centrally-managed pipelines as well, // including recently-deleted ones! - const managementPipelineIds = managementPipelines.map(pipeline => pipeline.id); + const managementPipelineIds = managementPipelines.map((pipeline) => pipeline.id); return managementPipelines.concat( monitoringPipelines.filter( - monitoringPipeline => + (monitoringPipeline) => !managementPipelineIds.includes(monitoringPipeline.id) && !this.isRecentlyDeleted(monitoringPipeline.id) ) @@ -56,8 +56,8 @@ export class PipelinesService { } getManagementPipelineList() { - return this.http.get(`${ROUTES.API_ROOT}/pipelines`).then(response => { - return response.pipelines.map(pipeline => PipelineListItem.fromUpstreamJSON(pipeline)); + return this.http.get(`${ROUTES.API_ROOT}/pipelines`).then((response) => { + return response.pipelines.map((pipeline) => PipelineListItem.fromUpstreamJSON(pipeline)); }); } @@ -75,7 +75,7 @@ export class PipelinesService { const body = JSON.stringify({ pipelineIds, }); - return this.http.post(`${ROUTES.API_ROOT}/pipelines/delete`, { body }).then(response => { + return this.http.post(`${ROUTES.API_ROOT}/pipelines/delete`, { body }).then((response) => { this.addToRecentlyDeleted(...pipelineIds); return response.results; }); @@ -83,8 +83,8 @@ export class PipelinesService { addToRecentlyDeleted(...pipelineIds) { const recentlyDeletedPipelines = this.getRecentlyDeleted(); - const recentlyDeletedPipelineIds = recentlyDeletedPipelines.map(pipeline => pipeline.id); - pipelineIds.forEach(pipelineId => { + const recentlyDeletedPipelineIds = recentlyDeletedPipelines.map((pipeline) => pipeline.id); + pipelineIds.forEach((pipelineId) => { if (!recentlyDeletedPipelineIds.includes(pipelineId)) { recentlyDeletedPipelines.push({ id: pipelineId, @@ -97,14 +97,14 @@ export class PipelinesService { removeFromRecentlyDeleted(...pipelineIds) { const recentlyDeletedPipelinesToKeep = this.getRecentlyDeleted().filter( - recentlyDeletedPipeline => !pipelineIds.includes(recentlyDeletedPipeline.id) + (recentlyDeletedPipeline) => !pipelineIds.includes(recentlyDeletedPipeline.id) ); this.setRecentlyDeleted(recentlyDeletedPipelinesToKeep); } isRecentlyDeleted(pipelineId) { return this.getRecentlyDeleted() - .map(pipeline => pipeline.id) + .map((pipeline) => pipeline.id) .includes(pipelineId); } diff --git a/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js b/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js index 7bd101ebee6b0..29e9ef6c1f6f4 100755 --- a/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js +++ b/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js @@ -14,8 +14,8 @@ export class UpgradeService { executeUpgrade() { return this.http .post(`${ROUTES.API_ROOT}/upgrade`) - .then(response => response.is_upgraded) - .catch(e => { + .then((response) => response.is_upgraded) + .catch((e) => { throw e.message; }); } diff --git a/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts b/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts index 324e0a22ff378..649764a034d63 100755 --- a/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts +++ b/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts @@ -6,7 +6,7 @@ import { licensingMock } from '../../../../licensing/server/mocks'; import { checkLicense } from './check_license'; -describe('check_license', function() { +describe('check_license', function () { describe('returns "valid": false & message when', () => { it('license information is not available', () => { const license = licensingMock.createLicenseMock(); diff --git a/x-pack/plugins/logstash/server/lib/check_license/check_license.ts b/x-pack/plugins/logstash/server/lib/check_license/check_license.ts index 4eef2eb9b0681..19606a508149d 100644 --- a/x-pack/plugins/logstash/server/lib/check_license/check_license.ts +++ b/x-pack/plugins/logstash/server/lib/check_license/check_license.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { CheckLicense } from '../../../../licensing/server'; -export const checkLicense: CheckLicense = license => { +export const checkLicense: CheckLicense = (license) => { if (!license.isAvailable) { return { valid: false, diff --git a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts index ac3097ac0424b..e29d0128353b5 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts @@ -11,19 +11,19 @@ import { INDEX_NAMES } from '../../../common/constants'; import { checkLicense } from '../../lib/check_license'; async function deletePipelines(callWithRequest: APICaller, pipelineIds: string[]) { - const deletePromises = pipelineIds.map(pipelineId => { + const deletePromises = pipelineIds.map((pipelineId) => { return callWithRequest('delete', { index: INDEX_NAMES.PIPELINES, id: pipelineId, refresh: 'wait_for', }) - .then(success => ({ success })) - .catch(error => ({ error })); + .then((success) => ({ success })) + .catch((error) => ({ error })); }); const results = await Promise.all(deletePromises); - const successes = results.filter(result => Reflect.has(result, 'success')); - const errors = results.filter(result => Reflect.has(result, 'error')); + const successes = results.filter((result) => Reflect.has(result, 'success')); + const errors = results.filter((result) => Reflect.has(result, 'error')); return { numSuccesses: successes.length, diff --git a/x-pack/plugins/logstash/server/routes/pipelines/list.ts b/x-pack/plugins/logstash/server/routes/pipelines/list.ts index bc477a25a7988..594e2b8ed8b3c 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/list.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/list.ts @@ -40,7 +40,7 @@ export function registerPipelinesListRoute(router: IRouter) { const client = context.logstash!.esClient; const pipelinesHits = await fetchPipelines(client.callAsCurrentUser); - const pipelines = pipelinesHits.map(pipeline => { + const pipelines = pipelinesHits.map((pipeline) => { return PipelineListItem.fromUpstreamJSON(pipeline).downstreamJSON; }); diff --git a/x-pack/plugins/maps/common/migrations/add_field_meta_options.js b/x-pack/plugins/maps/common/migrations/add_field_meta_options.js index e425e2a6d5e48..ae926cfa8f475 100644 --- a/x-pack/plugins/maps/common/migrations/add_field_meta_options.js +++ b/x-pack/plugins/maps/common/migrations/add_field_meta_options.js @@ -18,9 +18,9 @@ export function addFieldMetaOptions({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (isVectorLayer(layerDescriptor) && _.has(layerDescriptor, 'style.properties')) { - Object.values(layerDescriptor.style.properties).forEach(stylePropertyDescriptor => { + Object.values(layerDescriptor.style.properties).forEach((stylePropertyDescriptor) => { if (stylePropertyDescriptor.type === STYLE_TYPE.DYNAMIC) { stylePropertyDescriptor.options.fieldMetaOptions = { isEnabled: false, // turn off field metadata to avoid changing behavior of existing saved objects diff --git a/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js b/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js index 091cfd8605cb6..4dcf4b99aeb8f 100644 --- a/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js +++ b/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js @@ -23,7 +23,7 @@ export function emsRasterTileToEmsVectorTile({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layer => { + layerList.forEach((layer) => { if (isTileLayer(layer) && isEmsTileSource(layer)) { // Just need to switch layer type to migrate TILE layer to VECTOR_TILE layer layer.type = LAYER_TYPE.VECTOR_TILE; diff --git a/x-pack/plugins/maps/common/migrations/join_agg_key.ts b/x-pack/plugins/maps/common/migrations/join_agg_key.ts index 92e3172f218b9..4dc70d3c0fa22 100644 --- a/x-pack/plugins/maps/common/migrations/join_agg_key.ts +++ b/x-pack/plugins/maps/common/migrations/join_agg_key.ts @@ -96,7 +96,7 @@ export function migrateJoinAggKey({ }); }); - Object.keys(vectorLayerDescriptor.style.properties).forEach(key => { + Object.keys(vectorLayerDescriptor.style.properties).forEach((key) => { const style: any = vectorLayerDescriptor.style!.properties[key as VECTOR_STYLES]; if (_.get(style, 'options.field.origin') === FIELD_ORIGIN.JOIN) { const joinDescriptor = legacyJoinFields.get(style.options.field.name); diff --git a/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js b/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js index 0ae20ffd142c5..098e8dad68c00 100644 --- a/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js +++ b/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js @@ -18,7 +18,7 @@ export function migrateSymbolStyleDescriptor({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (!isVectorLayer(layerDescriptor) || !_.has(layerDescriptor, 'style.properties')) { return; } diff --git a/x-pack/plugins/maps/common/migrations/move_apply_global_query.js b/x-pack/plugins/maps/common/migrations/move_apply_global_query.js index 0d6b0052d2b0d..ceb19b059e0f8 100644 --- a/x-pack/plugins/maps/common/migrations/move_apply_global_query.js +++ b/x-pack/plugins/maps/common/migrations/move_apply_global_query.js @@ -22,7 +22,7 @@ export function moveApplyGlobalQueryToSources({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { const applyGlobalQuery = _.get(layerDescriptor, 'applyGlobalQuery', true); delete layerDescriptor.applyGlobalQuery; @@ -31,7 +31,7 @@ export function moveApplyGlobalQueryToSources({ attributes }) { } if (_.has(layerDescriptor, 'joins')) { - layerDescriptor.joins.forEach(joinDescriptor => { + layerDescriptor.joins.forEach((joinDescriptor) => { if (_.has(joinDescriptor, 'right')) { // joinDescriptor.right is ES_TERM_SOURCE source descriptor joinDescriptor.right.applyGlobalQuery = applyGlobalQuery; diff --git a/x-pack/plugins/maps/common/migrations/references.js b/x-pack/plugins/maps/common/migrations/references.js index 3980705fd7cfa..e0073c5f09a3d 100644 --- a/x-pack/plugins/maps/common/migrations/references.js +++ b/x-pack/plugins/maps/common/migrations/references.js @@ -65,7 +65,7 @@ export function extractReferences({ attributes, references = [] }) { } function findReference(targetName, references) { - const reference = references.find(reference => reference.name === targetName); + const reference = references.find((reference) => reference.name === targetName); if (!reference) { throw new Error(`Could not find reference "${targetName}"`); } @@ -78,7 +78,7 @@ export function injectReferences({ attributes, references }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layer => { + layerList.forEach((layer) => { // Inject index-pattern references into source descriptor if (doesSourceUseIndexPattern(layer) && _.has(layer, 'sourceDescriptor.indexPatternRefName')) { const reference = findReference(layer.sourceDescriptor.indexPatternRefName, references); @@ -88,7 +88,7 @@ export function injectReferences({ attributes, references }) { // Inject index-pattern references into join const joins = _.get(layer, 'joins', []); - joins.forEach(join => { + joins.forEach((join) => { if (_.has(join, 'right.indexPatternRefName')) { const reference = findReference(join.right.indexPatternRefName, references); join.right.indexPatternId = reference.id; diff --git a/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js b/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js index 055c867486f6c..6b7a5931255c5 100644 --- a/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js +++ b/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js @@ -18,7 +18,7 @@ export function topHitsTimeToSort({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (isEsDocumentSource(layerDescriptor)) { if (_.has(layerDescriptor, 'sourceDescriptor.topHitsTimeField')) { layerDescriptor.sourceDescriptor.sortField = diff --git a/x-pack/plugins/maps/public/actions/data_request_actions.ts b/x-pack/plugins/maps/public/actions/data_request_actions.ts index e615b31744f8d..e521fa5d0402b 100644 --- a/x-pack/plugins/maps/public/actions/data_request_actions.ts +++ b/x-pack/plugins/maps/public/actions/data_request_actions.ts @@ -66,7 +66,7 @@ export function clearDataRequests(layer: ILayer) { export function cancelAllInFlightRequests() { return (dispatch: Dispatch, getState: () => MapStoreState) => { - getLayerList(getState()).forEach(layer => { + getLayerList(getState()).forEach((layer) => { dispatch(clearDataRequests(layer)); }); }; @@ -126,7 +126,7 @@ function getDataRequestContext( export function syncDataForAllLayers() { return async (dispatch: Dispatch, getState: () => MapStoreState) => { - const syncPromises = getLayerList(getState()).map(async layer => { + const syncPromises = getLayerList(getState()).map(async (layer) => { return dispatch(syncDataForLayer(layer)); }); await Promise.all(syncPromises); diff --git a/x-pack/plugins/maps/public/actions/map_actions.js b/x-pack/plugins/maps/public/actions/map_actions.js index fa270954e6bae..4515c896e78a2 100644 --- a/x-pack/plugins/maps/public/actions/map_actions.js +++ b/x-pack/plugins/maps/public/actions/map_actions.js @@ -146,7 +146,7 @@ export function replaceLayerList(newLayerList) { }); } - newLayerList.forEach(layerDescriptor => { + newLayerList.forEach((layerDescriptor) => { dispatch(addLayer(layerDescriptor)); }); }; @@ -264,7 +264,7 @@ export function setTransientLayer(layerId) { } export function clearTransientLayerStateAndCloseFlyout() { - return async dispatch => { + return async (dispatch) => { await dispatch(updateFlyout(FLYOUT_STATE.NONE)); await dispatch(setSelectedLayer(null)); await dispatch(removeTransientLayer()); @@ -284,7 +284,7 @@ export function mapReady() { type: MAP_READY, }); - getWaitingForMapReadyLayerListRaw(getState()).forEach(layerDescriptor => { + getWaitingForMapReadyLayerListRaw(getState()).forEach((layerDescriptor) => { dispatch(addLayer(layerDescriptor)); }); @@ -376,7 +376,7 @@ export function disableScrollZoom() { } export function fitToLayerExtent(layerId) { - return async function(dispatch, getState) { + return async function (dispatch, getState) { const targetLayer = getLayerById(layerId, getState()); if (targetLayer) { @@ -390,7 +390,7 @@ export function fitToLayerExtent(layerId) { } export function fitToDataBounds() { - return async function(dispatch, getState) { + return async function (dispatch, getState) { const layerList = getFittableLayers(getState()); if (!layerList.length) { @@ -398,7 +398,7 @@ export function fitToDataBounds() { } const dataFilters = getDataFilters(getState()); - const boundsPromises = layerList.map(async layer => { + const boundsPromises = layerList.map(async (layer) => { return layer.getBounds(dataFilters); }); @@ -457,7 +457,7 @@ export function clearGoto() { } export function updateSourceProp(layerId, propName, value, newLayerType) { - return async dispatch => { + return async (dispatch) => { dispatch({ type: UPDATE_SOURCE_PROP, layerId, @@ -525,7 +525,7 @@ export function updateLayerAlpha(id, alpha) { } export function setLayerQuery(id, query) { - return dispatch => { + return (dispatch) => { dispatch({ type: UPDATE_LAYER_PROP, id, @@ -564,7 +564,7 @@ function removeLayerFromLayerList(layerId) { return; } - layerGettingRemoved.getInFlightRequestTokens().forEach(requestToken => { + layerGettingRemoved.getInFlightRequestTokens().forEach((requestToken) => { dispatch(cancelRequest(requestToken)); }); dispatch(cleanTooltipStateForLayer(layerId)); @@ -611,7 +611,7 @@ export function setRefreshConfig({ isPaused, interval }) { } export function triggerRefreshTimer() { - return async dispatch => { + return async (dispatch) => { dispatch({ type: TRIGGER_REFRESH_TIMER, }); @@ -643,7 +643,7 @@ export function clearMissingStyleProperties(layerId) { } export function updateLayerStyle(layerId, styleDescriptor) { - return dispatch => { + return (dispatch) => { dispatch({ type: UPDATE_LAYER_STYLE, layerId, @@ -672,7 +672,7 @@ export function updateLayerStyleForSelectedLayer(styleDescriptor) { } export function setJoinsForLayer(layer, joins) { - return async dispatch => { + return async (dispatch) => { await dispatch({ type: SET_JOINS, layer, @@ -685,7 +685,7 @@ export function setJoinsForLayer(layer, joins) { } export function updateDrawState(drawState) { - return dispatch => { + return (dispatch) => { if (drawState !== null) { dispatch({ type: SET_OPEN_TOOLTIPS, openTooltips: [] }); // tooltips just get in the way } @@ -722,7 +722,7 @@ export function setHiddenLayers(hiddenLayerIds) { if (!isMapReady) { dispatch({ type: SET_WAITING_FOR_READY_HIDDEN_LAYERS, hiddenLayerIds }); } else { - getLayerListRaw(getState()).forEach(layer => + getLayerListRaw(getState()).forEach((layer) => dispatch(setLayerVisibility(layer.id, !hiddenLayerIds.includes(layer.id))) ); } diff --git a/x-pack/plugins/maps/public/actions/tooltip_actions.ts b/x-pack/plugins/maps/public/actions/tooltip_actions.ts index ce74a63ac862d..98a121e6be7a3 100644 --- a/x-pack/plugins/maps/public/actions/tooltip_actions.ts +++ b/x-pack/plugins/maps/public/actions/tooltip_actions.ts @@ -76,15 +76,15 @@ export function cleanTooltipStateForLayer(layerId: string, layerFeatures: Featur return (dispatch: Dispatch, getState: () => MapStoreState) => { let featuresRemoved = false; const openTooltips = getOpenTooltips(getState()) - .map(tooltipState => { - const nextFeatures = tooltipState.features.filter(tooltipFeature => { + .map((tooltipState) => { + const nextFeatures = tooltipState.features.filter((tooltipFeature) => { if (tooltipFeature.layerId !== layerId) { // feature from another layer, keep it return true; } // Keep feature if it is still in layer - return layerFeatures.some(layerFeature => { + return layerFeatures.some((layerFeature) => { return layerFeature.properties![FEATURE_ID_PROPERTY_NAME] === tooltipFeature.id; }); }); @@ -95,7 +95,7 @@ export function cleanTooltipStateForLayer(layerId: string, layerFeatures: Featur return { ...tooltipState, features: nextFeatures }; }) - .filter(tooltipState => { + .filter((tooltipState) => { return tooltipState.features.length > 0; }); diff --git a/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js b/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js index 2dcec35960b08..ea48eecf4e421 100644 --- a/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js +++ b/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js @@ -15,7 +15,7 @@ import { getData, } from '../../kibana_services'; -export const getMapsSavedObjectLoader = _.once(function() { +export const getMapsSavedObjectLoader = _.once(function () { const services = { savedObjectsClient: getSavedObjectsClient(), indexPatterns: getIndexPatternService(), diff --git a/x-pack/plugins/maps/public/angular/services/saved_gis_map.js b/x-pack/plugins/maps/public/angular/services/saved_gis_map.js index 2de4432871347..ddb58b610f5f1 100644 --- a/x-pack/plugins/maps/public/angular/services/saved_gis_map.js +++ b/x-pack/plugins/maps/public/angular/services/saved_gis_map.js @@ -60,10 +60,10 @@ export function createSavedGisMapClass(services) { savedObject.layerListJSON = attributes.layerListJSON; const indexPatternIds = references - .filter(reference => { + .filter((reference) => { return reference.type === 'index-pattern'; }) - .map(reference => { + .map((reference) => { return reference.id; }); savedObject.indexPatternIds = _.uniq(indexPatternIds); diff --git a/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts b/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts index 7ed508199e64a..73d6c1ef9f790 100644 --- a/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts +++ b/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts @@ -35,7 +35,7 @@ export class EMSFileField extends AbstractField implements IField { // @ts-ignore const emsFields: any[] = emsFileLayer.getFieldsInLanguage(); // Map EMS field name to language specific label - const emsField = emsFields.find(field => field.name === this.getName()); + const emsField = emsFields.find((field) => field.name === this.getName()); return emsField ? emsField.description : this.getName(); } } diff --git a/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts b/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts index 9b619cf60a020..ce72f01adb5f8 100644 --- a/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts +++ b/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts @@ -33,7 +33,7 @@ export class KibanaRegionField extends AbstractField implements IField { const meta = await this._source.getVectorFileMeta(); // TODO remove any and @ts-ignore when vectorFileMeta type defined // @ts-ignore - const field: any = meta.fields.find(f => f.name === this.getName()); + const field: any = meta.fields.find((f) => f.name === this.getName()); return field ? field.description : this.getName(); } } diff --git a/x-pack/plugins/maps/public/classes/joins/inner_join.js b/x-pack/plugins/maps/public/classes/joins/inner_join.js index 13a2e05ab8eeb..5f8bc7385d04c 100644 --- a/x-pack/plugins/maps/public/classes/joins/inner_join.js +++ b/x-pack/plugins/maps/public/classes/joins/inner_join.js @@ -62,7 +62,7 @@ export class InnerJoin { // delete all dynamic properties for metric field const stylePropertyPrefix = getComputedFieldNamePrefix(metricPropertyKey); - Object.keys(feature.properties).forEach(featurePropertyKey => { + Object.keys(feature.properties).forEach((featurePropertyKey) => { if ( featurePropertyKey.length >= stylePropertyPrefix.length && featurePropertyKey.substring(0, stylePropertyPrefix.length) === stylePropertyPrefix diff --git a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts index f4d60ffa65d31..a949853d431b2 100644 --- a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts +++ b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts @@ -56,7 +56,7 @@ function getClusterSource(documentSource: IESSource, documentStyle: IVectorStyle type: AGG_TYPE.COUNT, label: COUNT_PROP_LABEL, }, - ...documentStyle.getDynamicPropertiesArray().map(dynamicProperty => { + ...documentStyle.getDynamicPropertiesArray().map((dynamicProperty) => { return { type: getAggType(dynamicProperty), field: dynamicProperty.getFieldName(), diff --git a/x-pack/plugins/maps/public/classes/layers/layer.tsx b/x-pack/plugins/maps/public/classes/layers/layer.tsx index 8e1b6162683db..b9a35fc361aad 100644 --- a/x-pack/plugins/maps/public/classes/layers/layer.tsx +++ b/x-pack/plugins/maps/public/classes/layers/layer.tsx @@ -134,7 +134,7 @@ export class AbstractLayer implements ILayer { this._style = style; if (this._descriptor.__dataRequests) { this._dataRequests = this._descriptor.__dataRequests.map( - dataRequest => new DataRequest(dataRequest) + (dataRequest) => new DataRequest(dataRequest) ); } else { this._dataRequests = []; @@ -161,7 +161,7 @@ export class AbstractLayer implements ILayer { // @ts-ignore if (clonedDescriptor.joins) { // @ts-ignore - clonedDescriptor.joins.forEach(joinDescriptor => { + clonedDescriptor.joins.forEach((joinDescriptor) => { // right.id is uuid used to track requests in inspector // @ts-ignore joinDescriptor.right.id = uuid(); @@ -333,7 +333,7 @@ export class AbstractLayer implements ILayer { // @ts-ignore const mbStyle = mbMap.getStyle(); // @ts-ignore - mbStyle.layers.forEach(mbLayer => { + mbStyle.layers.forEach((mbLayer) => { // @ts-ignore if (this.ownsMbLayerId(mbLayer.id)) { // @ts-ignore @@ -341,7 +341,7 @@ export class AbstractLayer implements ILayer { } }); // @ts-ignore - Object.keys(mbStyle.sources).some(mbSourceId => { + Object.keys(mbStyle.sources).some((mbSourceId) => { // @ts-ignore if (this.ownsMbSourceId(mbSourceId)) { // @ts-ignore @@ -387,7 +387,7 @@ export class AbstractLayer implements ILayer { return []; } - const requestTokens = this._dataRequests.map(dataRequest => dataRequest.getRequestToken()); + const requestTokens = this._dataRequests.map((dataRequest) => dataRequest.getRequestToken()); // Compact removes all the undefineds // @ts-ignore @@ -399,11 +399,11 @@ export class AbstractLayer implements ILayer { } getDataRequest(id: string): DataRequest | undefined { - return this._dataRequests.find(dataRequest => dataRequest.getDataId() === id); + return this._dataRequests.find((dataRequest) => dataRequest.getDataId() === id); } isLayerLoading(): boolean { - return this._dataRequests.some(dataRequest => dataRequest.isLoading()); + return this._dataRequests.some((dataRequest) => dataRequest.isLoading()); } hasErrors(): boolean { diff --git a/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts b/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts index dc5849203ff37..7698fb7c0947e 100644 --- a/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts +++ b/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts @@ -40,7 +40,7 @@ export function registerLayerWizard(layerWizard: LayerWizard) { } export async function getLayerWizards(): Promise { - const promises = registry.map(async layerWizard => { + const promises = registry.map(async (layerWizard) => { return { ...layerWizard, // @ts-ignore diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts index ce079d67c15e4..075d19dccdb68 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts @@ -18,7 +18,7 @@ jest.mock('../../../../kibana_services', () => { }); jest.mock('uuid/v4', () => { - return function() { + return function () { return '12345'; }; }); diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx index 7326f8459b5c7..bfd78d5490059 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx @@ -29,7 +29,7 @@ export class ObservabilityLayerTemplate extends Component { + const selectedMetricOption = metricOptions.find((option) => { return option.value === this.state.metric; }); if (!selectedMetricOption) { diff --git a/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js b/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js index d32593f73c46c..a2a0e58e48fd2 100644 --- a/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js +++ b/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js @@ -69,7 +69,7 @@ export class VectorLayer extends AbstractLayer { if (this.getSource()) { this.getSource().destroy(); } - this.getJoins().forEach(joinSource => { + this.getJoins().forEach((joinSource) => { joinSource.destroy(); }); } @@ -79,7 +79,7 @@ export class VectorLayer extends AbstractLayer { } getValidJoins() { - return this.getJoins().filter(join => { + return this.getJoins().filter((join) => { return join.hasCompleteConfig(); }); } @@ -120,7 +120,9 @@ export class VectorLayer extends AbstractLayer { if ( this.getJoins().length && - !featureCollection.features.some(feature => feature.properties[FEATURE_VISIBLE_PROPERTY_NAME]) + !featureCollection.features.some( + (feature) => feature.properties[FEATURE_VISIBLE_PROPERTY_NAME] + ) ) { return { icon: noResultsIcon, @@ -173,7 +175,7 @@ export class VectorLayer extends AbstractLayer { _getJoinFields() { const joinFields = []; - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { const fields = join.getJoinFields(); joinFields.push(...fields); }); @@ -192,7 +194,7 @@ export class VectorLayer extends AbstractLayer { getIndexPatternIds() { const indexPatternIds = this.getSource().getIndexPatternIds(); - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { indexPatternIds.push(...join.getIndexPatternIds()); }); return indexPatternIds; @@ -200,7 +202,7 @@ export class VectorLayer extends AbstractLayer { getQueryableIndexPatternIds() { const indexPatternIds = this.getSource().getQueryableIndexPatternIds(); - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { indexPatternIds.push(...join.getQueryableIndexPatternIds()); }); return indexPatternIds; @@ -266,7 +268,7 @@ export class VectorLayer extends AbstractLayer { } async _syncJoins(syncContext, style) { - const joinSyncs = this.getValidJoins().map(async join => { + const joinSyncs = this.getValidJoins().map(async (join) => { await this._syncJoinStyleMeta(syncContext, join, style); await this._syncJoinFormatters(syncContext, join, style); return this._syncJoin({ join, ...syncContext }); @@ -279,7 +281,7 @@ export class VectorLayer extends AbstractLayer { const fieldNames = [ ...source.getFieldNames(), ...style.getSourceFieldNames(), - ...this.getValidJoins().map(join => join.getLeftField().getName()), + ...this.getValidJoins().map((join) => join.getLeftField().getName()), ]; return { @@ -299,7 +301,7 @@ export class VectorLayer extends AbstractLayer { //-- visibility of any of the features has changed let shouldUpdateStore = - sourceResult.refreshed || joinStates.some(joinState => joinState.dataHasChanged); + sourceResult.refreshed || joinStates.some((joinState) => joinState.dataHasChanged); if (!shouldUpdateStore) { return; @@ -393,7 +395,7 @@ export class VectorLayer extends AbstractLayer { style, sourceQuery: this.getQuery(), dataRequestId: SOURCE_META_ID_ORIGIN, - dynamicStyleProps: style.getDynamicPropertiesArray().filter(dynamicStyleProp => { + dynamicStyleProps: style.getDynamicPropertiesArray().filter((dynamicStyleProp) => { return ( dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE && dynamicStyleProp.isFieldMetaEnabled() @@ -412,7 +414,7 @@ export class VectorLayer extends AbstractLayer { dataRequestId: join.getSourceMetaDataRequestId(), dynamicStyleProps: this.getCurrentStyle() .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { const matchingField = joinSource.getMetricFieldForName( dynamicStyleProp.getField().getName() ); @@ -442,7 +444,7 @@ export class VectorLayer extends AbstractLayer { return; } - const dynamicStyleFields = dynamicStyleProps.map(dynamicStyleProp => { + const dynamicStyleFields = dynamicStyleProps.map((dynamicStyleProp) => { return `${dynamicStyleProp.getField().getName()}${dynamicStyleProp.getNumberOfCategories()}`; }); @@ -489,10 +491,10 @@ export class VectorLayer extends AbstractLayer { dataRequestId: SOURCE_FORMATTERS_ID_ORIGIN, fields: style .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { return dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE; }) - .map(dynamicStyleProp => { + .map((dynamicStyleProp) => { return dynamicStyleProp.getField(); }), ...syncContext, @@ -506,13 +508,13 @@ export class VectorLayer extends AbstractLayer { dataRequestId: join.getSourceFormattersDataRequestId(), fields: style .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { const matchingField = joinSource.getMetricFieldForName( dynamicStyleProp.getField().getName() ); return dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.JOIN && !!matchingField; }) - .map(dynamicStyleProp => { + .map((dynamicStyleProp) => { return dynamicStyleProp.getField(); }), ...syncContext, @@ -524,7 +526,7 @@ export class VectorLayer extends AbstractLayer { return; } - const fieldNames = fields.map(field => { + const fieldNames = fields.map((field) => { return field.getName(); }); const nextMeta = { @@ -542,10 +544,10 @@ export class VectorLayer extends AbstractLayer { const formatters = {}; const promises = fields - .filter(field => { + .filter((field) => { return field.canValueBeFormatted(); }) - .map(async field => { + .map(async (field) => { formatters[field.getName()] = await source.createFieldFormatter(field); }); await Promise.all(promises); @@ -854,11 +856,7 @@ export class VectorLayer extends AbstractLayer { const tooltipProperty = tooltipsFromSource[i]; const matchingJoins = []; for (let j = 0; j < this.getJoins().length; j++) { - if ( - this.getJoins() - [j].getLeftField() - .getName() === tooltipProperty.getPropertyKey() - ) { + if (this.getJoins()[j].getLeftField().getName() === tooltipProperty.getPropertyKey()) { matchingJoins.push(this.getJoins()[j]); } } @@ -893,7 +891,7 @@ export class VectorLayer extends AbstractLayer { return; } - return featureCollection.features.find(feature => { + return featureCollection.features.find((feature) => { return feature.properties[FEATURE_ID_PROPERTY_NAME] === id; }); } diff --git a/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js b/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js index 4ffd0d93fd22a..6f616afb64041 100644 --- a/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js +++ b/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js @@ -117,7 +117,7 @@ export class VectorTileLayer extends TileLayer { if (!vectorStyle) { return []; } - return vectorStyle.layers.map(layer => this._generateMbId(layer.id)); + return vectorStyle.layers.map((layer) => this._generateMbId(layer.id)); } getMbSourceIds() { @@ -126,7 +126,7 @@ export class VectorTileLayer extends TileLayer { return []; } const sourceIds = Object.keys(vectorStyle.sources); - return sourceIds.map(sourceId => this._generateMbSourceId(sourceId)); + return sourceIds.map((sourceId) => this._generateMbSourceId(sourceId)); } ownsMbLayerId(mbLayerId) { @@ -145,7 +145,7 @@ export class VectorTileLayer extends TileLayer { _requiresPrevSourceCleanup(mbMap) { const sourceIdPrefix = this._generateMbSourceIdPrefix(); const mbStyle = mbMap.getStyle(); - return Object.keys(mbStyle.sources).some(mbSourceId => { + return Object.keys(mbStyle.sources).some((mbSourceId) => { const doesMbSourceBelongToLayer = this.ownsMbSourceId(mbSourceId); const doesMbSourceBelongToSource = mbSourceId.startsWith(sourceIdPrefix); return doesMbSourceBelongToLayer && !doesMbSourceBelongToSource; @@ -162,7 +162,7 @@ export class VectorTileLayer extends TileLayer { let initialBootstrapCompleted = false; const sourceIds = Object.keys(vectorStyle.sources); - sourceIds.forEach(sourceId => { + sourceIds.forEach((sourceId) => { if (initialBootstrapCompleted) { return; } @@ -197,7 +197,7 @@ export class VectorTileLayer extends TileLayer { addSpriteSheetToMapFromImageData(newJson, imageData, mbMap); //sync layers - vectorStyle.layers.forEach(layer => { + vectorStyle.layers.forEach((layer) => { const mbLayerId = this._generateMbId(layer.id); const mbLayer = mbMap.getLayer(mbLayerId); if (mbLayer) { @@ -242,7 +242,7 @@ export class VectorTileLayer extends TileLayer { return; } - opacityProps.forEach(opacityProp => { + opacityProps.forEach((opacityProp) => { if (mbLayer.paint && typeof mbLayer.paint[opacityProp] === 'number') { const newOpacity = mbLayer.paint[opacityProp] * this.getAlpha(); mbMap.setPaintProperty(mbLayerId, opacityProp, newOpacity); @@ -270,7 +270,7 @@ export class VectorTileLayer extends TileLayer { return; } - vectorStyle.layers.forEach(mbLayer => { + vectorStyle.layers.forEach((mbLayer) => { const mbLayerId = this._generateMbId(mbLayer.id); this.syncVisibilityWithMb(mbMap, mbLayerId); this._setLayerZoomRange(mbMap, mbLayer, mbLayerId); diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx index b66918f93f521..e398af4acea3b 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx @@ -37,7 +37,7 @@ export class EMSFileCreateSourceEditor extends Component { const emsClient = getEMSClient(); // @ts-ignore const fileLayers: unknown[] = await emsClient.getFileLayers(); - const options = fileLayers.map(fileLayer => { + const options = fileLayers.map((fileLayer) => { return { // @ts-ignore value: fileLayer.getId(), diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx index 5115da510cc5b..0e5aa602e4525 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx @@ -48,7 +48,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc constructor(descriptor: Partial, inspectorAdapters?: Adapters) { super(EMSFileSource.createDescriptor(descriptor), inspectorAdapters); this._descriptor = EMSFileSource.createDescriptor(descriptor); - this._tooltipFields = this._descriptor.tooltipProperties.map(propertyKey => + this._tooltipFields = this._descriptor.tooltipProperties.map((propertyKey) => this.createField({ fieldName: propertyKey }) ); } @@ -78,7 +78,9 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc // @ts-ignore const emsFileLayers = await emsClient.getFileLayers(); // @ts-ignore - const emsFileLayer = emsFileLayers.find(fileLayer => fileLayer.getId() === this._descriptor.id); + const emsFileLayer = emsFileLayers.find( + (fileLayer) => fileLayer.getId() === this._descriptor.id + ); if (!emsFileLayer) { throw new Error( i18n.translate('xpack.maps.source.emsFile.unableToFindIdErrorMessage', { @@ -104,7 +106,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc }); // @ts-ignore - const emsIdField = emsFileLayer._config.fields.find(field => { + const emsIdField = emsFileLayer._config.fields.find((field) => { return field.type === 'id'; }); featureCollection.features.forEach((feature: Feature, index: number) => { @@ -163,7 +165,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc // @ts-ignore const fields = emsFileLayer.getFieldsInLanguage(); // @ts-ignore - return fields.map(f => this.createField({ fieldName: f.name })); + return fields.map((f) => this.createField({ fieldName: f.name })); } canFormatFeatureProperties() { @@ -171,7 +173,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc } async filterAndFormatPropertiesToHtml(properties: unknown): Promise { - const promises = this._tooltipFields.map(field => { + const promises = this._tooltipFields.map((field) => { // @ts-ignore const value = properties[field.getName()]; return field.createTooltipProperty(value); diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx index 806213b667ba4..daeb1f8bc6b2b 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx @@ -49,11 +49,11 @@ export class UpdateSourceEditor extends Component { // @ts-ignore const emsFiles = await emsClient.getFileLayers(); // @ts-ignore - const taregetEmsFile = emsFiles.find(emsFile => emsFile.getId() === this.props.layerId); + const taregetEmsFile = emsFiles.find((emsFile) => emsFile.getId() === this.props.layerId); // @ts-ignore const emsFields = taregetEmsFile.getFieldsInLanguage(); // @ts-ignore - fields = emsFields.map(field => this.props.source.createField({ fieldName: field.name })); + fields = emsFields.map((field) => this.props.source.createField({ fieldName: field.name })); } catch (e) { // When a matching EMS-config cannot be found, the source already will have thrown errors during the data request. // This will propagate to the vector-layer and be displayed in the UX diff --git a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js index b20a3c80e0510..36c9e424a8b22 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js +++ b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js @@ -69,7 +69,7 @@ export class EMSTMSSource extends AbstractTMSSource { const emsClient = getEMSClient(); const emsTMSServices = await emsClient.getTMSServices(); const emsTileLayerId = this.getTileLayerId(); - const tmsService = emsTMSServices.find(tmsService => tmsService.getId() === emsTileLayerId); + const tmsService = emsTMSServices.find((tmsService) => tmsService.getId() === emsTileLayerId); if (!tmsService) { throw new Error( i18n.translate('xpack.maps.source.emsTile.errorMessage', { diff --git a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js index 337fc7aa46693..4d5d6655609c1 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js +++ b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js @@ -36,7 +36,7 @@ export class TileServiceSelect extends React.Component { return; } - const emsTmsOptions = emsTMSServices.map(tmsService => { + const emsTmsOptions = emsTMSServices.map((tmsService) => { return { value: tmsService.getId(), text: tmsService.getDisplayName() ? tmsService.getDisplayName() : tmsService.getId(), @@ -51,7 +51,7 @@ export class TileServiceSelect extends React.Component { this.setState({ emsTmsOptions, hasLoaded: true }); }; - _onChange = e => { + _onChange = (e) => { const value = e.target.value; const isAutoSelect = value === AUTO_SELECT; this.props.onTileSelect({ diff --git a/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js b/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js index 22c8293132b42..97afac9ef1745 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js @@ -15,7 +15,7 @@ export class AbstractESAggSource extends AbstractESSource { super(descriptor, inspectorAdapters); this._metricFields = []; if (this._descriptor.metrics) { - this._descriptor.metrics.forEach(aggDescriptor => { + this._descriptor.metrics.forEach((aggDescriptor) => { this._metricFields.push( ...esAggFieldsFactory(aggDescriptor, this, this.getOriginForField()) ); @@ -37,7 +37,7 @@ export class AbstractESAggSource extends AbstractESSource { } getMetricFieldForName(fieldName) { - return this.getMetricFields().find(metricField => { + return this.getMetricFields().find((metricField) => { return metricField.getName() === fieldName; }); } @@ -47,7 +47,7 @@ export class AbstractESAggSource extends AbstractESSource { } getMetricFields() { - const metrics = this._metricFields.filter(esAggField => esAggField.isValid()); + const metrics = this._metricFields.filter((esAggField) => esAggField.isValid()); return metrics.length === 0 ? esAggFieldsFactory({ type: AGG_TYPE.COUNT }, this, this.getOriginForField()) : metrics; @@ -80,7 +80,7 @@ export class AbstractESAggSource extends AbstractESSource { getValueAggsDsl(indexPattern) { const valueAggsDsl = {}; - this.getMetricFields().forEach(esAggMetric => { + this.getMetricFields().forEach((esAggMetric) => { const aggDsl = esAggMetric.getValueAggDsl(indexPattern); if (aggDsl) { valueAggsDsl[esAggMetric.getName()] = esAggMetric.getValueAggDsl(indexPattern); @@ -92,7 +92,7 @@ export class AbstractESAggSource extends AbstractESSource { async filterAndFormatPropertiesToHtmlForMetricFields(properties) { const metricFields = this.getMetricFields(); const tooltipPropertiesPromises = []; - metricFields.forEach(metricField => { + metricFields.forEach((metricField) => { let value; for (const key in properties) { if (properties.hasOwnProperty(key) && metricField.getName() === key) { diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js index 121ce3c7ffe92..a95a8be4b24c8 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js @@ -16,10 +16,10 @@ export function convertCompositeRespToGeoJson(esResponse, renderAs) { return convertToGeoJson( esResponse, renderAs, - esResponse => { + (esResponse) => { return _.get(esResponse, 'aggregations.compositeSplit.buckets', []); }, - gridBucket => { + (gridBucket) => { return gridBucket.key.gridSplit; } ); @@ -29,10 +29,10 @@ export function convertRegularRespToGeoJson(esResponse, renderAs) { return convertToGeoJson( esResponse, renderAs, - esResponse => { + (esResponse) => { return _.get(esResponse, 'aggregations.gridSplit.buckets', []); }, - gridBucket => { + (gridBucket) => { return gridBucket.key; } ); diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js index 77d2ffb8c577e..7661ad7020194 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js @@ -38,7 +38,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - onIndexPatternSelect = indexPatternId => { + onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -47,7 +47,7 @@ export class CreateSourceEditor extends Component { ); }; - loadIndexPattern = indexPatternId => { + loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -58,7 +58,7 @@ export class CreateSourceEditor extends Component { ); }; - debouncedLoad = _.debounce(async indexPatternId => { + debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -93,7 +93,7 @@ export class CreateSourceEditor extends Component { } }, 300); - _onGeoFieldSelect = geoField => { + _onGeoFieldSelect = (geoField) => { this.setState( { geoField, @@ -102,7 +102,7 @@ export class CreateSourceEditor extends Component { ); }; - _onRequestTypeSelect = newValue => { + _onRequestTypeSelect = (newValue) => { this.setState( { requestType: newValue, diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js index 053af4bfebe61..e77fd93872612 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js @@ -95,7 +95,7 @@ export class ESGeoGridSource extends AbstractESAggSource { } getFieldNames() { - return this.getMetricFields().map(esAggMetricField => esAggMetricField.getName()); + return this.getMetricFields().map((esAggMetricField) => esAggMetricField.getName()); } isGeoGridPrecisionAware() { @@ -270,7 +270,7 @@ export class ESGeoGridSource extends AbstractESAggSource { const searchSource = await this.makeSearchSource(searchFilters, 0); let bucketsPerGrid = 1; - this.getMetricFields().forEach(metricField => { + this.getMetricFields().forEach((metricField) => { bucketsPerGrid += metricField.getBucketCount(); }); diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx index 899f4a797ea75..8813264b21b05 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx @@ -41,7 +41,7 @@ export function RenderAsSelect(props: { } const selectedOptions = []; - const selectedOption = options.find(option => option.value === props.renderAs); + const selectedOption = options.find((option) => option.value === props.renderAs); if (selectedOption) { selectedOptions.push(selectedOption); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js index b2314dd007509..28c24f58a0efc 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js @@ -41,7 +41,7 @@ export function ResolutionEditor({ resolution, onChange }) { onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} compressed /> diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js index c0d6cba3a024a..ac7d809c40f61 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js @@ -54,26 +54,26 @@ export class UpdateSourceEditor extends Component { } this.setState({ - fields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + fields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), }); } - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ propName: 'metrics', value: metrics }); }; - _onResolutionChange = e => { + _onResolutionChange = (e) => { this.props.onChange({ propName: 'resolution', value: e }); }; - _onRequestTypeSelect = requestType => { + _onRequestTypeSelect = (requestType) => { this.props.onChange({ propName: 'requestType', value: requestType }); }; _renderMetricsPanel() { const metricsFilter = this.props.renderAs === RENDER_AS.HEATMAP - ? metric => { + ? (metric) => { //these are countable metrics, where blending heatmap color blobs make sense return isMetricCountable(metric.value); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js index 78c16130891b8..f599ba93d40d6 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js @@ -38,7 +38,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - onIndexPatternSelect = indexPatternId => { + onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -47,7 +47,7 @@ export class CreateSourceEditor extends Component { ); }; - loadIndexPattern = indexPatternId => { + loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -60,7 +60,7 @@ export class CreateSourceEditor extends Component { ); }; - debouncedLoad = _.debounce(async indexPatternId => { + debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -91,7 +91,7 @@ export class CreateSourceEditor extends Component { }); }, 300); - _onSourceGeoSelect = sourceGeoField => { + _onSourceGeoSelect = (sourceGeoField) => { this.setState( { sourceGeoField, @@ -100,7 +100,7 @@ export class CreateSourceEditor extends Component { ); }; - _onDestGeoSelect = destGeoField => { + _onDestGeoSelect = (destGeoField) => { this.setState( { destGeoField, diff --git a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js index dea59a1c82f8a..344b6187bad48 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js @@ -50,11 +50,11 @@ export class UpdateSourceEditor extends Component { } this.setState({ - fields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + fields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), }); } - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ propName: 'metrics', value: metrics }); }; diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js index 3a25bd90384e9..2f90b9b50d3d9 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js @@ -20,7 +20,7 @@ import { ScalingForm } from './scaling_form'; import { getTermsFields, supportsGeoTileAgg } from '../../../index_pattern_util'; function getGeoFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { return ( !indexPatterns.isNestedField(field) && [ES_GEO_FIELD_TYPE.GEO_POINT, ES_GEO_FIELD_TYPE.GEO_SHAPE].includes(field.type) @@ -63,7 +63,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - _onIndexPatternSelect = indexPatternId => { + _onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -72,7 +72,7 @@ export class CreateSourceEditor extends Component { ); }; - _loadIndexPattern = indexPatternId => { + _loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -82,7 +82,7 @@ export class CreateSourceEditor extends Component { ); }; - _debouncedLoad = _.debounce(async indexPatternId => { + _debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -114,7 +114,7 @@ export class CreateSourceEditor extends Component { if (geoFields.length) { // make default selection, prefer aggregatable field over the first available - const firstAggregatableGeoField = geoFields.find(geoField => { + const firstAggregatableGeoField = geoFields.find((geoField) => { return geoField.aggregatable; }); const defaultGeoFieldName = firstAggregatableGeoField @@ -124,7 +124,7 @@ export class CreateSourceEditor extends Component { } }, 300); - _onGeoFieldSelect = geoFieldName => { + _onGeoFieldSelect = (geoFieldName) => { // Respect previous scaling type selection unless newly selected geo field does not support clustering. const scalingType = this.state.scalingType === SCALING_TYPES.CLUSTERS && diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js index 21fd8b205b033..51dd57ffad0d1 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js @@ -38,7 +38,7 @@ function getDocValueAndSourceFields(indexPattern, fieldNames) { const docValueFields = []; const sourceOnlyFields = []; const scriptFields = {}; - fieldNames.forEach(fieldName => { + fieldNames.forEach((fieldName) => { const field = getField(indexPattern, fieldName); if (field.scripted) { scriptFields[field.name] = { @@ -87,7 +87,7 @@ export class ESSearchSource extends AbstractESSource { constructor(descriptor, inspectorAdapters) { super(ESSearchSource.createDescriptor(descriptor), inspectorAdapters); - this._tooltipFields = this._descriptor.tooltipProperties.map(property => + this._tooltipFields = this._descriptor.tooltipProperties.map((property) => this.createField({ fieldName: property }) ); } @@ -124,12 +124,12 @@ export class ESSearchSource extends AbstractESSource { try { const indexPattern = await this.getIndexPattern(); return indexPattern.fields - .filter(field => { + .filter((field) => { // Ensure fielddata is enabled for field. // Search does not request _source return field.aggregatable; }) - .map(field => { + .map((field) => { return this.createField({ fieldName: field.name }); }); } catch (error) { @@ -254,7 +254,7 @@ export class ESSearchSource extends AbstractESSource { // can not compare entityBuckets.length to totalEntities because totalEntities is an approximate const areEntitiesTrimmed = entityBuckets.length >= DEFAULT_MAX_BUCKETS_LIMIT; let areTopHitsTrimmed = false; - entityBuckets.forEach(entityBucket => { + entityBuckets.forEach((entityBucket) => { const total = _.get(entityBucket, 'entityHits.hits.total', 0); const hits = _.get(entityBucket, 'entityHits.hits.hits', []); // Reverse hits list so top documents by sort are drawn on top @@ -347,18 +347,18 @@ export class ESSearchSource extends AbstractESSource { registerCancelCallback ); - const unusedMetaFields = indexPattern.metaFields.filter(metaField => { + const unusedMetaFields = indexPattern.metaFields.filter((metaField) => { return !['_id', '_index'].includes(metaField); }); - const flattenHit = hit => { + const flattenHit = (hit) => { const properties = indexPattern.flattenHit(hit); // remove metaFields - unusedMetaFields.forEach(metaField => { + unusedMetaFields.forEach((metaField) => { delete properties[metaField]; }); return properties; }; - const epochMillisFields = searchFilters.fieldNames.filter(fieldName => { + const epochMillisFields = searchFilters.fieldNames.filter((fieldName) => { const field = getField(indexPattern, fieldName); return field.readFromDocValues && field.type === 'date'; }); @@ -425,7 +425,7 @@ export class ESSearchSource extends AbstractESSource { } const properties = indexPattern.flattenHit(hit); - indexPattern.metaFields.forEach(metaField => { + indexPattern.metaFields.forEach((metaField) => { if (!this._getTooltipPropertyNames().includes(metaField)) { delete properties[metaField]; } @@ -440,7 +440,7 @@ export class ESSearchSource extends AbstractESSource { properties._index, indexPattern ); - const tooltipProperties = this._tooltipFields.map(field => { + const tooltipProperties = this._tooltipFields.map((field) => { const value = propertyValues[field.getName()]; return field.createTooltipProperty(value); }); @@ -456,7 +456,7 @@ export class ESSearchSource extends AbstractESSource { async getLeftJoinFields() { const indexPattern = await this.getIndexPattern(); // Left fields are retrieved from _source. - return getSourceFields(indexPattern.fields).map(field => + return getSourceFields(indexPattern.fields).map((field) => this.createField({ fieldName: field.name }) ); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js index 59b41c2a79532..95e48c9629f57 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js @@ -82,7 +82,7 @@ export class UpdateSourceEditor extends Component { //todo move this all to the source const rawTooltipFields = getSourceFields(indexPattern.fields); - const sourceFields = rawTooltipFields.map(field => { + const sourceFields = rawTooltipFields.map((field) => { return new ESDocField({ fieldName: field.name, source: this.props.source, @@ -94,19 +94,19 @@ export class UpdateSourceEditor extends Component { sourceFields: sourceFields, termFields: getTermsFields(indexPattern.fields), //todo change term fields to use fields sortFields: indexPattern.fields.filter( - field => field.sortable && !indexPatterns.isNestedField(field) + (field) => field.sortable && !indexPatterns.isNestedField(field) ), //todo change sort fields to use fields }); } - _onTooltipPropertiesChange = propertyNames => { + _onTooltipPropertiesChange = (propertyNames) => { this.props.onChange({ propName: 'tooltipProperties', value: propertyNames }); }; - _onSortFieldChange = sortField => { + _onSortFieldChange = (sortField) => { this.props.onChange({ propName: 'sortField', value: sortField }); }; - _onSortOrderChange = e => { + _onSortOrderChange = (e) => { this.props.onChange({ propName: 'sortOrder', value: e.target.value }); }; diff --git a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js index 0302531117a6f..072f952fb8a13 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js @@ -280,7 +280,7 @@ export class AbstractESSource extends AbstractVectorSource { registerCancelCallback, searchFilters ) { - const promises = dynamicStyleProps.map(dynamicStyleProp => { + const promises = dynamicStyleProps.map((dynamicStyleProp) => { return dynamicStyleProp.getFieldMetaRequest(); }); diff --git a/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js b/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js index a6c4afa71dbb2..8cc8dd5c4a080 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js @@ -24,7 +24,7 @@ const TERMS_BUCKET_KEYS_TO_IGNORE = ['key', 'doc_count']; export function extractPropertiesMap(rawEsData, countPropertyName) { const propertiesMap = new Map(); - _.get(rawEsData, ['aggregations', TERMS_AGG_NAME, 'buckets'], []).forEach(termBucket => { + _.get(rawEsData, ['aggregations', TERMS_AGG_NAME, 'buckets'], []).forEach((termBucket) => { const properties = extractPropertiesFromBucket(termBucket, TERMS_BUCKET_KEYS_TO_IGNORE); if (countPropertyName) { properties[countPropertyName] = termBucket.doc_count; @@ -134,6 +134,6 @@ export class ESTermSource extends AbstractESAggSource { } getFieldNames() { - return this.getMetricFields().map(esAggMetricField => esAggMetricField.getName()); + return this.getMetricFields().map((esAggMetricField) => esAggMetricField.getName()); } } diff --git a/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js b/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js index fb5a2e4f42f1d..eeb34ed672221 100644 --- a/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js +++ b/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js @@ -51,7 +51,7 @@ export class KibanaRegionmapSource extends AbstractVectorSource { async getVectorFileMeta() { const regionList = getKibanaRegionList(); - const meta = regionList.find(source => source.name === this._descriptor.name); + const meta = regionList.find((source) => source.name === this._descriptor.name); if (!meta) { throw new Error( i18n.translate('xpack.maps.source.kbnRegionMap.noConfigErrorMessage', { @@ -79,7 +79,7 @@ export class KibanaRegionmapSource extends AbstractVectorSource { async getLeftJoinFields() { const vectorFileMeta = await this.getVectorFileMeta(); - return vectorFileMeta.fields.map(f => this.createField({ fieldName: f.name })); + return vectorFileMeta.fields.map((f) => this.createField({ fieldName: f.name })); } async getDisplayName() { diff --git a/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js b/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js index 13b8da11633bc..7fd83f1201846 100644 --- a/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js +++ b/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js @@ -12,7 +12,7 @@ export class AbstractTMSSource extends AbstractSource { } convertMarkdownLinkToObjectArr(markdown) { - return markdown.split('|').map(attribution => { + return markdown.split('|').map((attribution) => { attribution = attribution.trim(); //this assumes attribution is plain markdown link const extractLink = /\[(.*)\]\((.*)\)/; diff --git a/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js b/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js index 12e1780d9cad5..ccf6c7963c9b4 100644 --- a/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js +++ b/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js @@ -73,7 +73,7 @@ export class AbstractVectorSource extends AbstractSource { } _getTooltipPropertyNames() { - return this._tooltipFields.map(field => field.getName()); + return this._tooltipFields.map((field) => field.getName()); } isFilterByMapBounds() { diff --git a/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js index f676abc668341..df00faf43daa3 100644 --- a/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js @@ -102,7 +102,7 @@ export class WMSCreateSourceEditor extends Component { }); }; - _handleServiceUrlChange = e => { + _handleServiceUrlChange = (e) => { this.setState( { serviceUrl: e.target.value, @@ -118,16 +118,16 @@ export class WMSCreateSourceEditor extends Component { ); }; - _handleLayersChange = e => { + _handleLayersChange = (e) => { this.setState({ layers: e.target.value }, this._previewIfPossible); }; - _handleLayerOptionsChange = selectedOptions => { + _handleLayerOptionsChange = (selectedOptions) => { this.setState( { selectedLayerOptions: selectedOptions, layers: selectedOptions - .map(selectedOption => { + .map((selectedOption) => { return selectedOption.value; }) .join(','), @@ -136,16 +136,16 @@ export class WMSCreateSourceEditor extends Component { ); }; - _handleStylesChange = e => { + _handleStylesChange = (e) => { this.setState({ styles: e.target.value }, this._previewIfPossible); }; - _handleStyleOptionsChange = selectedOptions => { + _handleStyleOptionsChange = (selectedOptions) => { this.setState( { selectedStyleOptions: selectedOptions, styles: selectedOptions - .map(selectedOption => { + .map((selectedOption) => { return selectedOption.value; }) .join(','), diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx index 0ee0fbb23bcff..715ff0e4c2fdd 100644 --- a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx @@ -81,7 +81,7 @@ export class XYZTMSEditor extends Component { this._handleTMSInputChange(e)} + onChange={(e) => this._handleTMSInputChange(e)} /> - tinycolor(color) - .darken() - .toHexString() - ), + ...DEFAULT_FILL_COLORS.map((color) => tinycolor(color).darken().toHexString()), // Explicitly add black & white as border color options '#000', '#FFF', @@ -61,7 +57,7 @@ export function getRGBColorRangeStrings(colorRampName, numberColors = GRADIENT_I } export function getHexColorRangeStrings(colorRampName, numberColors = GRADIENT_INTERVALS) { - return getRGBColorRangeStrings(colorRampName, numberColors).map(rgbColor => + return getRGBColorRangeStrings(colorRampName, numberColors).map((rgbColor) => chroma(rgbColor).hex() ); } @@ -99,7 +95,7 @@ export function getOrdinalColorRampStops(colorRampName, min, max) { }, []); } -export const COLOR_GRADIENTS = Object.keys(vislibColorMaps).map(colorRampName => ({ +export const COLOR_GRADIENTS = Object.keys(vislibColorMaps).map((colorRampName) => ({ value: colorRampName, inputDisplay: , })); @@ -132,12 +128,12 @@ const COLOR_PALETTES_CONFIGS = [ ]; export function getColorPalette(paletteId) { - const palette = COLOR_PALETTES_CONFIGS.find(palette => palette.id === paletteId); + const palette = COLOR_PALETTES_CONFIGS.find((palette) => palette.id === paletteId); return palette ? palette.colors : null; } -export const COLOR_PALETTES = COLOR_PALETTES_CONFIGS.map(palette => { - const paletteDisplay = palette.colors.map(color => { +export const COLOR_PALETTES = COLOR_PALETTES_CONFIGS.map((palette) => { + const paletteDisplay = palette.colors.map((color) => { const style = { backgroundColor: color, width: `${100 / palette.colors.length}%`, diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js index a0f86dcf5130b..6d38a7985269e 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js @@ -16,7 +16,7 @@ import { } from './heatmap_constants'; export function HeatmapStyleEditor({ colorRampName, onHeatmapColorChange }) { - const onColorRampChange = selectedColorRampName => { + const onColorRampChange = (selectedColorRampName) => { onHeatmapColorChange({ colorRampName: selectedColorRampName, }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js index eadaf42ca694d..b7a80562f10ca 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js @@ -65,7 +65,7 @@ export class ColorMapSelect extends Component { ); } - _onColorMapSelect = selectedValue => { + _onColorMapSelect = (selectedValue) => { const useCustomColorMap = selectedValue === CUSTOM_COLOR_MAP; this.props.onChange({ color: useCustomColorMap ? null : selectedValue, @@ -134,7 +134,9 @@ export class ColorMapSelect extends Component { if (this.props.useCustomColorMap) { valueOfSelected = CUSTOM_COLOR_MAP; } else { - valueOfSelected = this.props.colorMapOptions.find(option => option.value === this.props.color) + valueOfSelected = this.props.colorMapOptions.find( + (option) => option.value === this.props.color + ) ? this.props.color : ''; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js index 20fd97a229352..4a632153c4596 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js @@ -22,7 +22,7 @@ export const ColorStops = ({ swatches, }) => { function getStopInput(stop, index) { - const onStopChange = newStopValue => { + const onStopChange = (newStopValue) => { const newColorStops = _.cloneDeep(colorStops); newColorStops[index].stop = newStopValue; onChange({ @@ -38,7 +38,7 @@ export const ColorStops = ({ } const rows = colorStops.map((colorStop, index) => { - const onColorChange = color => { + const onColorChange = (color) => { const newColorStops = _.cloneDeep(colorStops); newColorStops[index].color = color; onChange({ diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js index 4e2d07b9dfea0..d52c769c95a7d 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js @@ -57,7 +57,7 @@ export const ColorStopsOrdinal = ({ ); }; - const canDeleteStop = colorStops => { + const canDeleteStop = (colorStops) => { return colorStops.length > 1; }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js index 3eaa6acf435dc..c8888b2e438f1 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js @@ -61,7 +61,7 @@ export function isOrdinalStopInvalid(stop) { export function isCategoricalStopsInvalid(colorStops) { const nonDefaults = colorStops.slice(1); // - const values = nonDefaults.map(stop => stop.stop); + const values = nonDefaults.map((stop) => stop.stop); const uniques = _.uniq(values); return values.length !== uniques.length; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js index 460e7379920c4..fa13e1cf66664 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js @@ -60,7 +60,7 @@ export function DynamicColorForm({ }); }; - const onColorMapTypeChange = async e => { + const onColorMapTypeChange = async (e) => { const colorMapType = e.target.value; onDynamicStyleChange(styleProperty.getStyleName(), { ...styleOptions, @@ -74,7 +74,7 @@ export function DynamicColorForm({ return null; } - return fields.find(field => { + return fields.find((field) => { return field.name === fieldName; }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js index a295556ee3126..cfd7a8e41fe1c 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js @@ -14,7 +14,7 @@ export function StaticColorForm({ styleProperty, swatches, }) { - const onColorChange = color => { + const onColorChange = (color) => { onStaticStyleChange(styleProperty.getStyleName(), { color }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js index ed2e7a4eab7ec..51700a5e83394 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js @@ -27,7 +27,7 @@ function renderOption(option, searchValue, contentClassName) { function groupFieldsByOrigin(fields) { const fieldsByOriginMap = new Map(); - fields.forEach(field => { + fields.forEach((field) => { if (fieldsByOriginMap.has(field.origin)) { const fieldsList = fieldsByOriginMap.get(field.origin); fieldsList.push(field); @@ -39,7 +39,7 @@ function groupFieldsByOrigin(fields) { function fieldsListToOptions(fieldsList) { return fieldsList - .map(field => { + .map((field) => { return { value: field, label: field.label }; }) .sort((a, b) => { @@ -73,7 +73,7 @@ function groupFieldsByOrigin(fields) { } export function FieldSelect({ fields, selectedFieldName, onChange, styleName, ...rest }) { - const onFieldChange = selectedFields => { + const onFieldChange = (selectedFields) => { onChange({ field: selectedFields.length > 0 ? selectedFields[0].value : null, }); @@ -81,7 +81,7 @@ export function FieldSelect({ fields, selectedFieldName, onChange, styleName, .. let selectedOption; if (selectedFieldName) { - selectedOption = fields.find(field => { + selectedOption = fields.find((field) => { return field.name === selectedFieldName; }); } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js index 3b7145fdfc884..399d9beddb47a 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import { EuiFieldText, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticLabelForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onValueChange = event => { + const onValueChange = (event) => { onStaticStyleChange(styleProperty.getStyleName(), { value: event.target.value }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js index a7e98c83468ae..f535385b1f756 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js @@ -7,7 +7,7 @@ import React, { Fragment } from 'react'; export function VectorStyleLegend({ isLinesOnly, isPointsOnly, styles, symbolId }) { - return styles.map(style => { + return styles.map((style) => { return ( {style.renderLegendDetailRow({ diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js index b28743f426262..0d24fb5a5f155 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js @@ -9,7 +9,7 @@ import { ValidatedRange } from '../../../../../components/validated_range'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticOrientationForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onOrientationChange = orientation => { + const onOrientationChange = (orientation) => { onStaticStyleChange(styleProperty.getStyleName(), { orientation }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js index 90e540cc6802a..8845e113ec7ae 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticSizeForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onSizeChange = size => { + const onSizeChange = (size) => { onStaticStyleChange(styleProperty.getStyleName(), { size }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js b/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js index 93d9375972545..64a5f806e34c4 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js @@ -45,15 +45,15 @@ export class StopInput extends Component { } }; - _onChange = selectedOptions => { + _onChange = (selectedOptions) => { this.props.onChange(_.get(selectedOptions, '[0].label', '')); }; - _onCreateOption = newValue => { + _onCreateOption = (newValue) => { this.props.onChange(newValue); }; - _onSearchChange = async searchValue => { + _onSearchChange = async (searchValue) => { this.setState( { isLoadingSuggestions: true, @@ -65,7 +65,7 @@ export class StopInput extends Component { ); }; - _loadSuggestions = _.debounce(async searchValue => { + _loadSuggestions = _.debounce(async (searchValue) => { let suggestions = []; try { suggestions = await this.props.getValueSuggestions(searchValue); @@ -81,7 +81,7 @@ export class StopInput extends Component { } }, 300); - _onFieldTextChange = event => { + _onFieldTextChange = (event) => { this.setState({ localFieldTextValue: event.target.value }); // onChange can cause UI lag, ensure smooth input typing by debouncing onChange this._debouncedOnFieldTextChange(); @@ -92,7 +92,7 @@ export class StopInput extends Component { }, 500); _renderSuggestionInput() { - const suggestionOptions = this.state.suggestions.map(suggestion => { + const suggestionOptions = this.state.suggestions.map((suggestion) => { return { label: `${suggestion}` }; }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js index 28d5454afa4ba..e285d91dcd7a4 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js @@ -24,7 +24,7 @@ export class StyleMapSelect extends Component { }; } - _onMapSelect = selectedValue => { + _onMapSelect = (selectedValue) => { const useCustomMap = selectedValue === CUSTOM_MAP; this.props.onChange({ selectedMapId: useCustomMap ? null : selectedValue, @@ -71,7 +71,9 @@ export class StyleMapSelect extends Component { if (this.props.useCustomMap) { valueOfSelected = CUSTOM_MAP; } else { - valueOfSelected = this.props.options.find(option => option.value === this.props.selectedMapId) + valueOfSelected = this.props.options.find( + (option) => option.value === this.props.selectedMapId + ) ? this.props.selectedMapId : ''; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js index 005bc11aa1bd8..e7df47bc6d4cb 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js @@ -41,7 +41,7 @@ export class StylePropEditor extends Component { } }; - _onFieldMetaOptionsChange = fieldMetaOptions => { + _onFieldMetaOptionsChange = (fieldMetaOptions) => { const options = { ...this.props.styleProperty.getOptions(), fieldMetaOptions, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js index 6b79ac17f2e22..f9f8a67846470 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js @@ -28,7 +28,7 @@ export function DynamicIconForm({ }); }; - const onIconMapChange = newOptions => { + const onIconMapChange = (newOptions) => { onDynamicStyleChange(styleProperty.getStyleName(), { ...styleOptions, ...newOptions, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js index a036423e71709..01c1719f5bcef 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js @@ -34,12 +34,12 @@ export class IconSelect extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; - _handleKeyboardActivity = e => { + _handleKeyboardActivity = (e) => { if (isKeyboardEvent(e)) { if (e.keyCode === keyCodes.ENTER) { e.preventDefault(); @@ -50,8 +50,8 @@ export class IconSelect extends Component { } }; - _onIconSelect = options => { - const selectedOption = options.find(option => { + _onIconSelect = (options) => { + const selectedOption = options.find((option) => { return option.checked === 'on'; }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js index 0da3074f55e49..81a44fcaadbd3 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js @@ -21,7 +21,7 @@ function isDuplicateStop(targetStop, iconStops) { } export function getFirstUnusedSymbol(symbolOptions, iconStops) { - const firstUnusedPreferredIconId = PREFERRED_ICONS.find(iconId => { + const firstUnusedPreferredIconId = PREFERRED_ICONS.find((iconId) => { const isSymbolBeingUsed = iconStops.some(({ icon }) => { return icon === iconId; }); @@ -56,7 +56,7 @@ export function IconStops({ symbolOptions, }) { return iconStops.map(({ stop, icon }, index) => { - const onIconSelect = selectedIconId => { + const onIconSelect = (selectedIconId) => { const newIconStops = [...iconStops]; newIconStops[index] = { ...iconStops[index], @@ -64,7 +64,7 @@ export function IconStops({ }; onChange({ customMapStops: newIconStops }); }; - const onStopChange = newStopValue => { + const onStopChange = (newStopValue) => { const newIconStops = [...iconStops]; newIconStops[index] = { ...iconStops[index], diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js index 9b00b2fe38d7b..56e5737f72449 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js @@ -15,7 +15,7 @@ export function StaticIconForm({ styleProperty, symbolOptions, }) { - const onChange = selectedIconId => { + const onChange = (selectedIconId) => { onStaticStyleChange(styleProperty.getStyleName(), { value: selectedIconId }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js index cf287e8b1fd5f..12b9fb846df58 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js @@ -38,7 +38,7 @@ export function VectorStyleSymbolizeAsEditor({ return id === styleOptions.value; }); - const onSymbolizeAsChange = optionId => { + const onSymbolizeAsChange = (optionId) => { const styleDescriptor = { options: { value: optionId, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js index c46dc2cb4b73e..3424a972fed06 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js @@ -56,7 +56,7 @@ export class VectorStyleEditor extends Component { } async _loadFields() { - const getFieldMeta = async field => { + const getFieldMeta = async (field) => { return { label: await field.getLabel(), name: field.getName(), @@ -75,13 +75,13 @@ export class VectorStyleEditor extends Component { this.setState({ fields: fieldsArrayAll, - ordinalAndCategoricalFields: fieldsArrayAll.filter(field => { + ordinalAndCategoricalFields: fieldsArrayAll.filter((field) => { return ( CATEGORICAL_DATA_TYPES.includes(field.type) || ORDINAL_DATA_TYPES.includes(field.type) ); }), - dateFields: fieldsArrayAll.filter(field => field.type === 'date'), - numberFields: fieldsArrayAll.filter(field => field.type === 'number'), + dateFields: fieldsArrayAll.filter((field) => field.type === 'date'), + numberFields: fieldsArrayAll.filter((field) => field.type === 'number'), }); } @@ -112,11 +112,11 @@ export class VectorStyleEditor extends Component { return [...this.state.dateFields, ...this.state.numberFields]; } - _handleSelectedFeatureChange = selectedFeature => { + _handleSelectedFeatureChange = (selectedFeature) => { this.setState({ selectedFeature }); }; - _onIsTimeAwareChange = event => { + _onIsTimeAwareChange = (event) => { this.props.onIsTimeAwareChange(event.target.checked); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js index f4c2b8d926075..afcdf1e3cfc5b 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js @@ -20,7 +20,7 @@ import { mockField, MockLayer } from './__tests__/test_util'; const makeProperty = (options, field = mockField) => { return new DynamicColorProperty(options, VECTOR_STYLES.LINE_COLOR, field, new MockLayer(), () => { - return x => x + '_format'; + return (x) => x + '_format'; }); }; @@ -63,7 +63,7 @@ test('Should render ordinal legend with breaks', async () => { const component = shallow(legendRow); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -82,7 +82,7 @@ test('Should render categorical legend with breaks from default', async () => { const component = shallow(legendRow); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -117,7 +117,7 @@ test('Should render categorical legend with breaks from custom', async () => { }); function makeFeatures(foobarPropValues) { - return foobarPropValues.map(value => { + return foobarPropValues.map((value) => { return { type: 'Feature', properties: { @@ -194,7 +194,7 @@ describe('supportsFieldMeta', () => { test('should not support it when field does not', () => { const field = Object.create(mockField); - field.supportsFieldMeta = function() { + field.supportsFieldMeta = function () { return false; }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx index c271943213027..505c08ac35ba7 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx @@ -54,7 +54,7 @@ test('Should render categorical legend with breaks', async () => { const legendRow = iconStyle.renderLegendDetailRow({ isPointsOnly: true, isLinesOnly: false }); const component = shallow(legendRow); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js index 56a461a3bb147..82645b3a29319 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js @@ -24,7 +24,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { this._getFieldFormatter = getFieldFormatter; } - getValueSuggestions = query => { + getValueSuggestions = (query) => { const field = this.getField(); const fieldSource = this._getFieldSource(); return fieldSource && field ? fieldSource.getValueSuggestions(field, query) : []; @@ -35,7 +35,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { return SOURCE_META_ID_ORIGIN; } - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldName); }); return join ? join.getSourceMetaDataRequestId() : null; @@ -258,7 +258,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { return null; } - const ordered = fieldMetaData[rootFieldName].buckets.map(bucket => { + const ordered = fieldMetaData[rootFieldName].buckets.map((bucket) => { return { key: bucket.key, count: bucket.doc_count, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js index c1c4375faaeb1..1672af8eccff8 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js @@ -16,7 +16,7 @@ export const SMALL_MAKI_ICON_SIZE = 11; export const HALF_LARGE_MAKI_ICON_SIZE = Math.ceil(LARGE_MAKI_ICON_SIZE); export const SYMBOLS = {}; -maki.svgArray.forEach(svgString => { +maki.svgArray.forEach((svgString) => { const ID_FRAG = 'id="'; const index = svgString.indexOf(ID_FRAG); if (index !== -1) { @@ -32,7 +32,7 @@ maki.svgArray.forEach(svgString => { } }); -export const SYMBOL_OPTIONS = Object.keys(SYMBOLS).map(symbolId => { +export const SYMBOL_OPTIONS = Object.keys(SYMBOLS).map((symbolId) => { return { value: symbolId, label: symbolId, @@ -103,8 +103,8 @@ const ICON_PALETTES = [ // PREFERRED_ICONS is used to provide less random default icon values for forms that need default icon values export const PREFERRED_ICONS = []; -ICON_PALETTES.forEach(iconPalette => { - iconPalette.icons.forEach(iconId => { +ICON_PALETTES.forEach((iconPalette) => { + iconPalette.icons.forEach((iconId) => { if (!PREFERRED_ICONS.includes(iconId)) { PREFERRED_ICONS.push(iconId); } @@ -113,7 +113,7 @@ ICON_PALETTES.forEach(iconPalette => { export function getIconPaletteOptions(isDarkMode) { return ICON_PALETTES.map(({ id, icons }) => { - const iconsDisplay = icons.map(iconId => { + const iconsDisplay = icons.map((iconId) => { const style = { width: '10%', position: 'relative', diff --git a/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js b/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js index 5a4edd9c93a05..f3ed18bd1302e 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js @@ -151,17 +151,17 @@ export class VectorStyle extends AbstractStyle { onStyleDescriptorChange(vectorStyleDescriptor); }; - const onIsTimeAwareChange = isTimeAware => { + const onIsTimeAwareChange = (isTimeAware) => { const vectorStyleDescriptor = VectorStyle.createDescriptor(rawProperties, isTimeAware); onStyleDescriptorChange(vectorStyleDescriptor); }; - const propertiesWithFieldMeta = this.getDynamicPropertiesArray().filter(dynamicStyleProp => { + const propertiesWithFieldMeta = this.getDynamicPropertiesArray().filter((dynamicStyleProp) => { return dynamicStyleProp.isFieldMetaEnabled(); }); const styleProperties = {}; - this.getAllStyleProperties().forEach(styleProperty => { + this.getAllStyleProperties().forEach((styleProperty) => { styleProperties[styleProperty.getStyleName()] = styleProperty; }); @@ -195,12 +195,12 @@ export class VectorStyle extends AbstractStyle { const originalProperties = this.getRawProperties(); const updatedProperties = {}; - const dynamicProperties = Object.keys(originalProperties).filter(key => { + const dynamicProperties = Object.keys(originalProperties).filter((key) => { const { type, options } = originalProperties[key] || {}; return type === STYLE_TYPE.DYNAMIC && options.field && options.field.name; }); - dynamicProperties.forEach(key => { + dynamicProperties.forEach((key) => { const dynamicProperty = originalProperties[key]; const fieldName = dynamicProperty && dynamicProperty.options.field && dynamicProperty.options.field.name; @@ -208,7 +208,7 @@ export class VectorStyle extends AbstractStyle { return; } - const matchingOrdinalField = nextFields.find(ordinalField => { + const matchingOrdinalField = nextFields.find((ordinalField) => { return fieldName === ordinalField.getName(); }); @@ -298,7 +298,7 @@ export class VectorStyle extends AbstractStyle { return styleMeta; } - dynamicProperties.forEach(dynamicProperty => { + dynamicProperties.forEach((dynamicProperty) => { const categoricalStyleMeta = dynamicProperty.pluckCategoricalStyleMetaFromFeatures(features); const ordinalStyleMeta = dynamicProperty.pluckOrdinalStyleMetaFromFeatures(features); const name = dynamicProperty.getField().getName(); @@ -319,7 +319,7 @@ export class VectorStyle extends AbstractStyle { getSourceFieldNames() { const fieldNames = []; - this.getDynamicPropertiesArray().forEach(styleProperty => { + this.getDynamicPropertiesArray().forEach((styleProperty) => { if (styleProperty.getFieldOrigin() === FIELD_ORIGIN.SOURCE) { fieldNames.push(styleProperty.getField().getName()); } @@ -338,7 +338,7 @@ export class VectorStyle extends AbstractStyle { getDynamicPropertiesArray() { const styleProperties = this.getAllStyleProperties(); return styleProperties.filter( - styleProperty => styleProperty.isDynamic() && styleProperty.isComplete() + (styleProperty) => styleProperty.isDynamic() && styleProperty.isComplete() ); } @@ -356,7 +356,7 @@ export class VectorStyle extends AbstractStyle { _getDynamicPropertyByFieldName(fieldName) { const dynamicProps = this.getDynamicPropertiesArray(); - return dynamicProps.find(dynamicProp => { + return dynamicProps.find((dynamicProp) => { return fieldName === dynamicProp.getField().getName(); }); } @@ -365,7 +365,7 @@ export class VectorStyle extends AbstractStyle { return this._styleMeta; } - _getFieldFormatter = fieldName => { + _getFieldFormatter = (fieldName) => { const dynamicProp = this._getDynamicPropertyByFieldName(fieldName); if (!dynamicProp) { return null; @@ -375,7 +375,7 @@ export class VectorStyle extends AbstractStyle { if (dynamicProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE) { dataRequestId = SOURCE_FORMATTERS_ID_ORIGIN; } else { - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldName); }); if (join) { @@ -435,7 +435,7 @@ export class VectorStyle extends AbstractStyle { }; _getLegendDetailStyleProperties = () => { - return this.getDynamicPropertiesArray().filter(styleProperty => { + return this.getDynamicPropertiesArray().filter((styleProperty) => { const styleName = styleProperty.getStyleName(); if ([VECTOR_STYLES.ICON_ORIENTATION, VECTOR_STYLES.LABEL_TEXT].includes(styleName)) { return false; @@ -528,7 +528,7 @@ export class VectorStyle extends AbstractStyle { //this return-value is used in an optimization for style-updates with mapbox-gl. //`true` indicates the entire data needs to reset on the source (otherwise the style-rules will not be reapplied) //`false` indicates the data does not need to be reset on the store, because styles are re-evaluated if they use featureState - return dynamicStyleProps.some(dynamicStyleProp => !dynamicStyleProp.supportsMbFeatureState()); + return dynamicStyleProps.some((dynamicStyleProp) => !dynamicStyleProp.supportsMbFeatureState()); } arePointsSymbolizedAsCircles() { @@ -588,7 +588,7 @@ export class VectorStyle extends AbstractStyle { if (fieldDescriptor.origin === FIELD_ORIGIN.SOURCE) { return this._source.getFieldByName(fieldDescriptor.name); } else if (fieldDescriptor.origin === FIELD_ORIGIN.JOIN) { - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldDescriptor.name); }); return join ? join.getRightJoinSource().getMetricFieldForName(fieldDescriptor.name) : null; diff --git a/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts b/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts index 4247233b295e1..aa78d7064fb0a 100644 --- a/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts +++ b/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts @@ -19,7 +19,7 @@ export function getFeatureCollectionBounds( } const visibleFeatures = hasJoins - ? featureCollection.features.filter(feature => { + ? featureCollection.features.filter((feature) => { return feature.properties && feature.properties[FEATURE_VISIBLE_PROPERTY_NAME]; }) : featureCollection.features; diff --git a/x-pack/plugins/maps/public/components/geometry_filter_form.js b/x-pack/plugins/maps/public/components/geometry_filter_form.js index ac6461345e8bf..d5cdda3c1c324 100644 --- a/x-pack/plugins/maps/public/components/geometry_filter_form.js +++ b/x-pack/plugins/maps/public/components/geometry_filter_form.js @@ -41,17 +41,17 @@ export class GeometryFilterForm extends Component { relation: ES_SPATIAL_RELATIONS.INTERSECTS, }; - _onGeoFieldChange = selectedField => { + _onGeoFieldChange = (selectedField) => { this.setState({ selectedField }); }; - _onGeometryLabelChange = e => { + _onGeometryLabelChange = (e) => { this.setState({ geometryLabel: e.target.value, }); }; - _onRelationChange = e => { + _onRelationChange = (e) => { this.setState({ relation: e.target.value, }); @@ -78,11 +78,11 @@ export class GeometryFilterForm extends Component { const spatialRelations = this.props.isFilterGeometryClosed ? Object.values(ES_SPATIAL_RELATIONS) - : Object.values(ES_SPATIAL_RELATIONS).filter(relation => { + : Object.values(ES_SPATIAL_RELATIONS).filter((relation) => { // can not filter by within relation when filtering geometry is not closed return relation !== ES_SPATIAL_RELATIONS.WITHIN; }); - const options = spatialRelations.map(relation => { + const options = spatialRelations.map((relation) => { return { value: relation, text: getEsSpatialRelationLabel(relation), diff --git a/x-pack/plugins/maps/public/components/global_filter_checkbox.js b/x-pack/plugins/maps/public/components/global_filter_checkbox.js index a8c2908e75424..004bb73f357e1 100644 --- a/x-pack/plugins/maps/public/components/global_filter_checkbox.js +++ b/x-pack/plugins/maps/public/components/global_filter_checkbox.js @@ -8,7 +8,7 @@ import React from 'react'; import { EuiFormRow, EuiSwitch } from '@elastic/eui'; export function GlobalFilterCheckbox({ applyGlobalQuery, label, setApplyGlobalQuery }) { - const onApplyGlobalQueryChange = event => { + const onApplyGlobalQueryChange = (event) => { setApplyGlobalQuery(event.target.checked); }; diff --git a/x-pack/plugins/maps/public/components/map_listing.js b/x-pack/plugins/maps/public/components/map_listing.js index ee10fe30130f3..030b67185c106 100644 --- a/x-pack/plugins/maps/public/components/map_listing.js +++ b/x-pack/plugins/maps/public/components/map_listing.js @@ -58,7 +58,7 @@ export class MapListing extends React.Component { addHelpMenuToAppChrome(); } - debouncedFetch = _.debounce(async filter => { + debouncedFetch = _.debounce(async (filter) => { const response = await this.props.find(filter); if (!this._isMounted) { @@ -282,7 +282,7 @@ export class MapListing extends React.Component { })} fullWidth value={this.state.filter} - onChange={e => { + onChange={(e) => { this.setState( { filter: e.target.value, @@ -333,9 +333,9 @@ export class MapListing extends React.Component { let selection = false; if (!this.props.readOnly) { selection = { - onSelectionChange: selection => { + onSelectionChange: (selection) => { this.setState({ - selectedIds: selection.map(item => { + selectedIds: selection.map((item) => { return item.id; }), }); diff --git a/x-pack/plugins/maps/public/components/metric_editor.js b/x-pack/plugins/maps/public/components/metric_editor.js index d1affe2f42190..96b52d84653b2 100644 --- a/x-pack/plugins/maps/public/components/metric_editor.js +++ b/x-pack/plugins/maps/public/components/metric_editor.js @@ -29,13 +29,13 @@ function filterFieldsForAgg(fields, aggType) { metricAggFieldTypes.push('date'); } - return fields.filter(field => { + return fields.filter((field) => { return field.aggregatable && metricAggFieldTypes.includes(field.type); }); } export function MetricEditor({ fields, metricsFilter, metric, onChange, removeButton }) { - const onAggChange = metricAggregationType => { + const onAggChange = (metricAggregationType) => { const newMetricProps = { ...metric, type: metricAggregationType, @@ -44,7 +44,7 @@ export function MetricEditor({ fields, metricsFilter, metric, onChange, removeBu // unset field when new agg type does not support currently selected field. if (metric.field && metricAggregationType !== AGG_TYPE.COUNT) { const fieldsForNewAggType = filterFieldsForAgg(fields, metricAggregationType); - const found = fieldsForNewAggType.find(field => { + const found = fieldsForNewAggType.find((field) => { return field.name === metric.field; }); if (!found) { @@ -54,13 +54,13 @@ export function MetricEditor({ fields, metricsFilter, metric, onChange, removeBu onChange(newMetricProps); }; - const onFieldChange = fieldName => { + const onFieldChange = (fieldName) => { onChange({ ...metric, field: fieldName, }); }; - const onLabelChange = e => { + const onLabelChange = (e) => { onChange({ ...metric, label: e.target.value, diff --git a/x-pack/plugins/maps/public/components/metric_select.js b/x-pack/plugins/maps/public/components/metric_select.js index cf29583eeab44..2ebfcf99dece6 100644 --- a/x-pack/plugins/maps/public/components/metric_select.js +++ b/x-pack/plugins/maps/public/components/metric_select.js @@ -79,7 +79,7 @@ export function MetricSelect({ value, onChange, metricsFilter, ...rest }) { singleSelection={true} isClearable={false} options={options} - selectedOptions={AGG_OPTIONS.filter(option => { + selectedOptions={AGG_OPTIONS.filter((option) => { return value === option.value; })} onChange={onAggChange} diff --git a/x-pack/plugins/maps/public/components/metrics_editor.js b/x-pack/plugins/maps/public/components/metrics_editor.js index f81e56a83266d..6c5a9af8f0f02 100644 --- a/x-pack/plugins/maps/public/components/metrics_editor.js +++ b/x-pack/plugins/maps/public/components/metrics_editor.js @@ -15,7 +15,7 @@ import { AGG_TYPE } from '../../common/constants'; export function MetricsEditor({ fields, metrics, onChange, allowMultipleMetrics, metricsFilter }) { function renderMetrics() { return metrics.map((metric, index) => { - const onMetricChange = metric => { + const onMetricChange = (metric) => { onChange([...metrics.slice(0, index), metric, ...metrics.slice(index + 1)]); }; diff --git a/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx b/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx index 0e5b94f0c6427..c7a45df51f061 100644 --- a/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx +++ b/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx @@ -34,7 +34,7 @@ export function MultiIndexGeoFieldSelect({ fields, onChange, selectedField }: Pr function onFieldSelect(selectedOptionId: string) { const { indexPatternId, geoFieldName } = splitOptionId(selectedOptionId); - const newSelectedField = fields.find(field => { + const newSelectedField = fields.find((field) => { return field.indexPatternId === indexPatternId && field.geoFieldName === geoFieldName; }); onChange(newSelectedField); diff --git a/x-pack/plugins/maps/public/components/single_field_select.js b/x-pack/plugins/maps/public/components/single_field_select.js index aadc619b029a8..a4db361da9c62 100644 --- a/x-pack/plugins/maps/public/components/single_field_select.js +++ b/x-pack/plugins/maps/public/components/single_field_select.js @@ -17,7 +17,7 @@ function fieldsToOptions(fields) { } return fields - .map(field => { + .map((field) => { return { value: field, label: 'label' in field ? field.label : field.name, @@ -42,7 +42,7 @@ function renderOption(option, searchValue, contentClassName) { } export function SingleFieldSelect({ fields, onChange, value, placeholder, ...rest }) { - const onSelection = selectedOptions => { + const onSelection = (selectedOptions) => { onChange(_.get(selectedOptions, '0.value.name')); }; diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx index 782e5e878164e..cbeb4e79a38d7 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx @@ -37,14 +37,14 @@ function getOptions(fields: FieldProps[], selectedFields: FieldProps[]): EuiSele } return fields - .filter(field => { + .filter((field) => { // remove selected fields - const isFieldSelected = !!selectedFields.find(selectedField => { + const isFieldSelected = !!selectedFields.find((selectedField) => { return field.name === selectedField.name; }); return !isFieldSelected; }) - .map(field => { + .map((field) => { return { value: field.name, prepend: @@ -107,10 +107,10 @@ export class AddTooltipFieldPopover extends Component { _onSelect = (options: EuiSelectableOption[]) => { const checkedFields: string[] = options - .filter(option => { + .filter((option) => { return option.checked === 'on'; }) - .map(option => { + .map((option) => { return option.value as string; }); diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx index f3ac62717519d..a33add0f6e344 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx @@ -42,7 +42,7 @@ describe('TooltipSelector', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); expect(component).toMatchSnapshot(); diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx index 34c58c4c8a183..6c07c322d5c49 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx @@ -117,7 +117,7 @@ export class TooltipSelector extends Component { }; _getTooltipFieldNames(): string[] { - return this.props.tooltipFields ? this.props.tooltipFields.map(field => field.getName()) : []; + return this.props.tooltipFields ? this.props.tooltipFields.map((field) => field.getName()) : []; } _onAdd = (properties: string[]) => { diff --git a/x-pack/plugins/maps/public/components/validated_range.js b/x-pack/plugins/maps/public/components/validated_range.js index f21dae7feb9b2..3fba45c930abe 100644 --- a/x-pack/plugins/maps/public/components/validated_range.js +++ b/x-pack/plugins/maps/public/components/validated_range.js @@ -34,7 +34,7 @@ export class ValidatedRange extends React.Component { return null; } - _onRangeChange = e => { + _onRangeChange = (e) => { const sanitizedValue = parseFloat(e.target.value, 10); let newValue = isNaN(sanitizedValue) ? '' : sanitizedValue; // work around for https://github.com/elastic/eui/issues/1458 diff --git a/x-pack/plugins/maps/public/connected_components/gis_map/view.js b/x-pack/plugins/maps/public/connected_components/gis_map/view.js index 621db4971b5d7..f733d08cf0b71 100644 --- a/x-pack/plugins/maps/public/connected_components/gis_map/view.js +++ b/x-pack/plugins/maps/public/connected_components/gis_map/view.js @@ -73,7 +73,7 @@ export class GisMap extends Component { } }; - _loadGeoFields = async nextIndexPatternIds => { + _loadGeoFields = async (nextIndexPatternIds) => { if (_.isEqual(nextIndexPatternIds, this._prevIndexPatternIds)) { // all ready loaded index pattern ids return; @@ -84,8 +84,8 @@ export class GisMap extends Component { const geoFields = []; try { const indexPatterns = await getIndexPatternsFromIds(nextIndexPatternIds); - indexPatterns.forEach(indexPattern => { - indexPattern.fields.forEach(field => { + indexPatterns.forEach((indexPattern) => { + indexPattern.fields.forEach((field) => { if ( !indexPatternsUtils.isNestedField(field) && (field.type === ES_GEO_FIELD_TYPE.GEO_POINT || diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js index fba2ec05d0b1d..75b6b5d66f1de 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js @@ -42,7 +42,7 @@ export class FilterEditor extends Component { // Filter only effects source so only load source indices. const indexPatternIds = this.props.layer.getSource().getIndexPatternIds(); const indexPatterns = []; - const getIndexPatternPromises = indexPatternIds.map(async indexPatternId => { + const getIndexPatternPromises = indexPatternIds.map(async (indexPatternId) => { try { const indexPattern = await getIndexPatternService().get(indexPatternId); indexPatterns.push(indexPattern); @@ -61,7 +61,7 @@ export class FilterEditor extends Component { }; _toggle = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -75,7 +75,7 @@ export class FilterEditor extends Component { this._close(); }; - _onApplyGlobalQueryChange = applyGlobalQuery => { + _onApplyGlobalQueryChange = (applyGlobalQuery) => { this.props.updateSourceProp(this.props.layer.getId(), 'applyGlobalQuery', applyGlobalQuery); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js index bd8b302c9ee17..c45c9c88a8716 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js @@ -22,7 +22,7 @@ function mapStateToProps(state = {}) { }; } -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { cancelLayerPanel: () => { dispatch(updateFlyout(FLYOUT_STATE.NONE)); diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/index.js index 8a18191ada1e8..ff088e9306a8c 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/index.js @@ -19,7 +19,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - fitToBounds: layerId => { + fitToBounds: (layerId) => { dispatch(fitToLayerExtent(layerId)); }, updateSourceProp: (id, propName, value, newLayerType) => diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js index 0d26354e2449b..25083822a6183 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js @@ -58,12 +58,12 @@ export class Join extends Component { } this.setState({ - rightFields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + rightFields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), indexPattern, }); } - _onLeftFieldChange = leftField => { + _onLeftFieldChange = (leftField) => { this.props.onChange({ leftField: leftField, right: this.props.join.right, @@ -86,7 +86,7 @@ export class Join extends Component { }); }; - _onRightFieldChange = term => { + _onRightFieldChange = (term) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -96,7 +96,7 @@ export class Join extends Component { }); }; - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -106,7 +106,7 @@ export class Join extends Component { }); }; - _onWhereQueryChange = whereQuery => { + _onWhereQueryChange = (whereQuery) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -116,7 +116,7 @@ export class Join extends Component { }); }; - _onApplyGlobalQueryChange = applyGlobalQuery => { + _onApplyGlobalQueryChange = (applyGlobalQuery) => { this.props.onChange({ leftField: this.props.join.leftField, right: { diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js index 12ca2f3c514a0..60f8c8005fe4c 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js @@ -32,7 +32,7 @@ export class JoinExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -43,7 +43,7 @@ export class JoinExpression extends Component { }); }; - _onRightSourceChange = async indexPatternId => { + _onRightSourceChange = async (indexPatternId) => { try { const indexPattern = await getIndexPatternService().get(indexPatternId); this.props.onRightSourceChange({ @@ -55,7 +55,7 @@ export class JoinExpression extends Component { } }; - _onLeftFieldChange = selectedFields => { + _onLeftFieldChange = (selectedFields) => { this.props.onLeftFieldChange(_.get(selectedFields, '[0].value.name', null)); }; @@ -66,7 +66,7 @@ export class JoinExpression extends Component { return null; } - const options = leftFields.map(field => { + const options = leftFields.map((field) => { return { value: field, label: field.label, @@ -75,7 +75,7 @@ export class JoinExpression extends Component { let leftFieldOption; if (leftValue) { - leftFieldOption = options.find(option => { + leftFieldOption = options.find((option) => { const field = option.value; return field.name === leftValue; }); diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js index 8c83743ac4c96..6b119ba6d850d 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js @@ -25,7 +25,7 @@ export class MetricsExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js index 7c9b4f7b7b9a4..d87761d3dabe8 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js @@ -16,7 +16,7 @@ export class WhereExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js index 92e32885d43a8..900f5c9ff53ea 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js @@ -23,7 +23,7 @@ import { i18n } from '@kbn/i18n'; export function JoinEditor({ joins, layer, onChange, leftJoinFields, layerDisplayName }) { const renderJoins = () => { return joins.map((joinDescriptor, index) => { - const handleOnChange = updatedDescriptor => { + const handleOnChange = (updatedDescriptor) => { onChange(layer, [...joins.slice(0, index), updatedDescriptor, ...joins.slice(index + 1)]); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js b/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js index d84d05260f982..bc99285cfc7aa 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js @@ -13,7 +13,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { ValidatedDualRange } from '../../../../../../../src/plugins/kibana_react/public'; export function LayerSettings(props) { - const onLabelChange = event => { + const onLabelChange = (event) => { const label = event.target.value; props.updateLabel(props.layerId, label); }; @@ -23,7 +23,7 @@ export function LayerSettings(props) { props.updateMaxZoom(props.layerId, Math.min(props.maxVisibilityZoom, parseInt(max, 10))); }; - const onAlphaChange = alpha => { + const onAlphaChange = (alpha) => { props.updateAlpha(props.layerId, alpha); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js index f024956f61cf8..aa04e1d6b2f31 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js @@ -17,7 +17,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - updateStyleDescriptor: styleDescriptor => { + updateStyleDescriptor: (styleDescriptor) => { dispatch(updateLayerStyleForSelectedLayer(styleDescriptor)); }, }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/view.js b/x-pack/plugins/maps/public/connected_components/layer_panel/view.js index f8b7c417e67fd..f34c402a4d417 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/view.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/view.js @@ -83,7 +83,7 @@ export class LayerPanel extends React.Component { let leftJoinFields; try { const leftFieldsInstances = await this.props.selectedLayer.getLeftJoinFields(); - const leftFieldPromises = leftFieldsInstances.map(async field => { + const leftFieldPromises = leftFieldsInstances.map(async (field) => { return { name: field.getName(), label: await field.getLabel(), diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js b/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js index 9f882cd467527..99893c1bc5bee 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js @@ -80,7 +80,7 @@ describe('LayerPanel', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -91,7 +91,7 @@ describe('LayerPanel', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js index 825c1ad7e7da3..362186a8f5549 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js @@ -149,7 +149,7 @@ export class FeatureProperties extends React.Component { ); } - const rows = this.state.properties.map(tooltipProperty => { + const rows = this.state.properties.map((tooltipProperty) => { const label = tooltipProperty.getPropertyName(); return (
@@ -172,7 +172,7 @@ export class FeatureProperties extends React.Component { return (
{getColumnName(col)}   @@ -69,7 +69,7 @@ export const Datatable = ({ datatable, perPage, paginate, showHeader }) => (
{getFormattedValue(row[getColumnName(col)], getColumnType(col))}
(this._node = node)} + ref={(node) => (this._node = node)} > {rows}
diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js index 10c3711392fb3..c6db9cd96a429 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js @@ -55,7 +55,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -74,7 +74,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -93,7 +93,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js index 8a1b556d21c1f..e5b97947602b0 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js @@ -32,7 +32,7 @@ export class FeaturesTooltip extends React.Component { return null; } - _setCurrentFeature = feature => { + _setCurrentFeature = (feature) => { this.setState({ currentFeature: feature }); }; diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js index 9d4b8bf356dca..6a249ad7b3592 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js @@ -64,7 +64,7 @@ export class TooltipHeader extends Component { countByLayerId.forEach((count, layerId) => { layers.push(this.props.findLayerById(layerId)); }); - const layerNamePromises = layers.map(layer => { + const layerNamePromises = layers.map((layer) => { return layer.getDisplayName(); }); const layerNames = await Promise.all(layerNamePromises); @@ -88,12 +88,12 @@ export class TooltipHeader extends Component { } }; - _onPageChange = pageNumber => { + _onPageChange = (pageNumber) => { this.setState({ pageNumber }); this.props.setCurrentFeature(this.state.filteredFeatures[pageNumber]); }; - _onLayerChange = e => { + _onLayerChange = (e) => { const newLayerId = e.target.value; if (this.state.selectedLayerId === newLayerId) { return; @@ -102,7 +102,7 @@ export class TooltipHeader extends Component { const filteredFeatures = newLayerId === ALL_LAYERS ? this.props.features - : this.props.features.filter(feature => { + : this.props.features.filter((feature) => { return feature.layerId === newLayerId; }); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js index 329e52b3519cf..342817f8171f2 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js @@ -23,7 +23,7 @@ class MockLayer { const defaultProps = { onClose: () => {}, isLocked: false, - findLayerById: id => { + findLayerById: (id) => { return new MockLayer(id); }, setCurrentFeature: () => {}, @@ -42,7 +42,7 @@ describe('TooltipHeader', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -56,7 +56,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -83,7 +83,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -97,7 +97,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -128,7 +128,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -142,7 +142,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js index a69e06458a6a0..ac28a2d5d5a6d 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js @@ -57,7 +57,7 @@ export class DrawControl extends React.Component { } }, 256); - _onDraw = e => { + _onDraw = (e) => { if (!e.features.length) { return; } diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts b/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts index 30e3b9b46916b..b9d446d390ffb 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts +++ b/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts @@ -24,7 +24,7 @@ export async function getInitialView( return await new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( // success callback - pos => { + (pos) => { resolve({ lat: pos.coords.latitude, lon: pos.coords.longitude, diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/index.js b/x-pack/plugins/maps/public/connected_components/map/mb/index.js index a617ae92dea15..189d6bc1f0a43 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/index.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/index.js @@ -46,10 +46,10 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - extentChanged: e => { + extentChanged: (e) => { dispatch(mapExtentChanged(e)); }, - onMapReady: e => { + onMapReady: (e) => { dispatch(clearGoto()); dispatch(mapExtentChanged(e)); dispatch(mapReady()); diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js index 4774cdc556c24..376010f0df9ba 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js @@ -18,14 +18,14 @@ class MockMbMap { } moveLayer(mbLayerId, nextMbLayerId) { - const indexOfLayerToMove = this._style.layers.findIndex(layer => { + const indexOfLayerToMove = this._style.layers.findIndex((layer) => { return layer.id === mbLayerId; }); const layerToMove = this._style.layers[indexOfLayerToMove]; this._style.layers.splice(indexOfLayerToMove, 1); - const indexOfNextLayer = this._style.layers.findIndex(layer => { + const indexOfNextLayer = this._style.layers.findIndex((layer) => { return layer.id === nextMbLayerId; }); @@ -37,7 +37,7 @@ class MockMbMap { } removeLayer(layerId) { - const layerToRemove = this._style.layers.findIndex(layer => { + const layerToRemove = this._style.layers.findIndex((layer) => { return layer.id === layerId; }); this._style.layers.splice(layerToRemove, 1); @@ -65,13 +65,13 @@ class MockLayer { } ownsMbLayerId(mbLayerId) { - return this._mbLayerIdsToSource.some(mbLayerToSource => { + return this._mbLayerIdsToSource.some((mbLayerToSource) => { return mbLayerToSource.id === mbLayerId; }); } ownsMbSourceId(mbSourceId) { - return this._mbSourceIds.some(id => mbSourceId === id); + return this._mbSourceIds.some((id) => mbSourceId === id); } } @@ -81,8 +81,8 @@ function getMockStyle(orderedMockLayerList) { layers: [], }; - orderedMockLayerList.forEach(mockLayer => { - mockLayer.getMbSourceIds().forEach(mbSourceId => { + orderedMockLayerList.forEach((mockLayer) => { + mockLayer.getMbSourceIds().forEach((mbSourceId) => { mockStyle.sources[mbSourceId] = {}; }); mockLayer.getMbLayersIdsToSource().forEach(({ id, source }) => { diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js index 329d2b7fd2985..7c86d729577e2 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js @@ -47,7 +47,7 @@ export class TooltipControl extends React.Component { }; _getLayerByMbLayerId(mbLayerId) { - return this.props.layerList.find(layer => { + return this.props.layerList.find((layer) => { const mbLayerIds = layer.getMbLayerIds(); return mbLayerIds.indexOf(mbLayerId) > -1; }); @@ -81,7 +81,7 @@ export class TooltipControl extends React.Component { return uniqueFeatures; } - _lockTooltip = e => { + _lockTooltip = (e) => { if (this.props.isDrawingFilter) { // ignore click events when in draw mode return; @@ -105,7 +105,7 @@ export class TooltipControl extends React.Component { }); }; - _updateHoverTooltipState = _.debounce(e => { + _updateHoverTooltipState = _.debounce((e) => { if (this.props.isDrawingFilter || this.props.hasLockedTooltips) { // ignore hover events when in draw mode or when there are locked tooltips return; @@ -144,7 +144,7 @@ export class TooltipControl extends React.Component { //For example: //a vector or heatmap layer will not add a source and layer to the mapbox-map, until that data is available. //during that data-fetch window, the app should not query for layers that do not exist. - return mbLayerIds.filter(mbLayerId => { + return mbLayerIds.filter((mbLayerId) => { return !!this.props.mbMap.getLayer(mbLayerId); }); } diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js index 620d7cb9ff756..31964c3395417 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js @@ -37,7 +37,7 @@ const mockMBMap = { on: (eventName, callback) => { mockMbMapHandlers[eventName] = callback; }, - off: eventName => { + off: (eventName) => { delete mockMbMapHandlers[eventName]; }, getLayer: () => {}, diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js index 867c779bc4dba..03c2aeb2edd0a 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js @@ -97,13 +97,13 @@ export class TooltipPopover extends Component { return await tooltipLayer.getSource().getPreIndexedShape(targetFeature.properties); }; - _findLayerById = layerId => { - return this.props.layerList.find(layer => { + _findLayerById = (layerId) => { + return this.props.layerList.find((layer) => { return layer.getId() === layerId; }); }; - _getLayerName = async layerId => { + _getLayerName = async (layerId) => { const layer = this._findLayerById(layerId); if (!layer) { return null; diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js index bcef03c205b2b..205ca7337277d 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js @@ -23,7 +23,7 @@ const layerId = 'tfi3f'; const mockMbMapHandlers = {}; const mockMBMap = { - project: lonLatArray => { + project: (lonLatArray) => { const lonDistanceFromCenter = Math.abs(lonLatArray[0] - mapCenter[0]); const latDistanceFromCenter = Math.abs(lonLatArray[1] - mapCenter[1]); return { @@ -34,7 +34,7 @@ const mockMBMap = { on: (eventName, callback) => { mockMbMapHandlers[eventName] = callback; }, - off: eventName => { + off: (eventName) => { delete mockMbMapHandlers[eventName]; }, getBounds: () => { @@ -95,7 +95,7 @@ describe('TooltipPopover', () => { const component = shallow( { + renderTooltipContent={(props) => { return
Custom tooltip content
; }} /> diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/utils.js b/x-pack/plugins/maps/public/connected_components/map/mb/utils.js index adf109a087d27..a5934038f83df 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/utils.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/utils.js @@ -11,20 +11,20 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa const mbStyle = mbMap.getStyle(); const mbLayerIdsToRemove = []; - mbStyle.layers.forEach(mbLayer => { + mbStyle.layers.forEach((mbLayer) => { // ignore mapbox layers from spatial filter layer if (spatialFilterLayer.ownsMbLayerId(mbLayer.id)) { return; } - const layer = layerList.find(layer => { + const layer = layerList.find((layer) => { return layer.ownsMbLayerId(mbLayer.id); }); if (!layer) { mbLayerIdsToRemove.push(mbLayer.id); } }); - mbLayerIdsToRemove.forEach(mbLayerId => mbMap.removeLayer(mbLayerId)); + mbLayerIdsToRemove.forEach((mbLayerId) => mbMap.removeLayer(mbLayerId)); const mbSourcesToRemove = []; for (const mbSourceId in mbStyle.sources) { @@ -34,7 +34,7 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa return; } - const layer = layerList.find(layer => { + const layer = layerList.find((layer) => { return layer.ownsMbSourceId(mbSourceId); }); if (!layer) { @@ -42,7 +42,7 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa } } } - mbSourcesToRemove.forEach(mbSourceId => mbMap.removeSource(mbSourceId)); + mbSourcesToRemove.forEach((mbSourceId) => mbMap.removeSource(mbSourceId)); } export function moveLayerToTop(mbMap, layer) { @@ -52,7 +52,7 @@ export function moveLayerToTop(mbMap, layer) { return; } - layer.getMbLayerIds().forEach(mbLayerId => { + layer.getMbLayerIds().forEach((mbLayerId) => { const mbLayer = mbMap.getLayer(mbLayerId); if (mbLayer) { mbMap.moveLayer(mbLayerId); @@ -73,8 +73,8 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { const mbLayers = mbMap.getStyle().layers.slice(); const layerIds = []; - mbLayers.forEach(mbLayer => { - const layer = layerList.find(layer => layer.ownsMbLayerId(mbLayer.id)); + mbLayers.forEach((mbLayer) => { + const layer = layerList.find((layer) => layer.ownsMbLayerId(mbLayer.id)); if (layer) { layerIds.push(layer.getId()); } @@ -82,15 +82,15 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { const currentLayerOrderLayerIds = _.uniq(layerIds); - const newLayerOrderLayerIdsUnfiltered = layerList.map(l => l.getId()); - const newLayerOrderLayerIds = newLayerOrderLayerIdsUnfiltered.filter(layerId => + const newLayerOrderLayerIdsUnfiltered = layerList.map((l) => l.getId()); + const newLayerOrderLayerIds = newLayerOrderLayerIdsUnfiltered.filter((layerId) => currentLayerOrderLayerIds.includes(layerId) ); let netPos = 0; let netNeg = 0; const movementArr = currentLayerOrderLayerIds.reduce((accu, id, idx) => { - const movement = newLayerOrderLayerIds.findIndex(newOId => newOId === id) - idx; + const movement = newLayerOrderLayerIds.findIndex((newOId) => newOId === id) - idx; movement > 0 ? netPos++ : movement < 0 && netNeg++; accu.push({ id, movement }); return accu; @@ -99,9 +99,9 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { return; } const movedLayerId = - (netPos >= netNeg && movementArr.find(l => l.movement < 0).id) || - (netPos < netNeg && movementArr.find(l => l.movement > 0).id); - const nextLayerIdx = newLayerOrderLayerIds.findIndex(layerId => layerId === movedLayerId) + 1; + (netPos >= netNeg && movementArr.find((l) => l.movement < 0).id) || + (netPos < netNeg && movementArr.find((l) => l.movement > 0).id); + const nextLayerIdx = newLayerOrderLayerIds.findIndex((layerId) => layerId === movedLayerId) + 1; let nextMbLayerId; if (nextLayerIdx === newLayerOrderLayerIds.length) { @@ -109,13 +109,13 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { } else { const foundLayer = mbLayers.find(({ id: mbLayerId }) => { const layerId = newLayerOrderLayerIds[nextLayerIdx]; - const layer = layerList.find(layer => layer.getId() === layerId); + const layer = layerList.find((layer) => layer.getId() === layerId); return layer.ownsMbLayerId(mbLayerId); }); nextMbLayerId = foundLayer.id; } - const movedLayer = layerList.find(layer => layer.getId() === movedLayerId); + const movedLayer = layerList.find((layer) => layer.getId() === movedLayerId); mbLayers.forEach(({ id: mbLayerId }) => { if (movedLayer.ownsMbLayerId(mbLayerId)) { mbMap.moveLayer(mbLayerId, nextMbLayerId); @@ -156,11 +156,11 @@ export async function loadSpriteSheetImageData(imgUrl) { if (isCrossOriginUrl(imgUrl)) { image.crossOrigin = 'Anonymous'; } - image.onload = el => { + image.onload = (el) => { const imgData = getImageData(el.currentTarget); resolve(imgData); }; - image.onerror = e => { + image.onerror = (e) => { reject(e); }; image.src = imgUrl; diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/view.js b/x-pack/plugins/maps/public/connected_components/map/mb/view.js index 800daec76989c..c4b28e33747ee 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/view.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/view.js @@ -113,7 +113,7 @@ export class MBMapContainer extends React.Component { async _createMbMapInstance() { const initialView = await getInitialView(this.props.goto, this.props.settings); - return new Promise(resolve => { + return new Promise((resolve) => { const mbStyle = { version: 8, sources: {}, @@ -151,7 +151,7 @@ export class MBMapContainer extends React.Component { } let emptyImage; - mbMap.on('styleimagemissing', e => { + mbMap.on('styleimagemissing', (e) => { if (emptyImage) { mbMap.addImage(e.id, emptyImage); } @@ -201,7 +201,7 @@ export class MBMapContainer extends React.Component { ); // Attach event only if view control is visible, which shows lat/lon if (!this.props.hideViewControl) { - const throttledSetMouseCoordinates = _.throttle(e => { + const throttledSetMouseCoordinates = _.throttle((e) => { this.props.setMouseCoordinates({ lat: e.lngLat.lat, lon: e.lngLat.lng, @@ -267,7 +267,7 @@ export class MBMapContainer extends React.Component { this.props.layerList, this.props.spatialFiltersLayer ); - this.props.layerList.forEach(layer => layer.syncLayerWithMB(this.state.mbMap)); + this.props.layerList.forEach((layer) => layer.syncLayerWithMB(this.state.mbMap)); syncLayerOrderForSingleLayer(this.state.mbMap, this.props.layerList); moveLayerToTop(this.state.mbMap, this.props.spatialFiltersLayer); }; diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js index 2c10728f78e5c..87b636da543fc 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js @@ -49,15 +49,15 @@ export class SetViewControl extends Component { this.props.openSetView(); }; - _onLatChange = evt => { + _onLatChange = (evt) => { this._onChange('lat', evt); }; - _onLonChange = evt => { + _onLonChange = (evt) => { this._onChange('lon', evt); }; - _onZoomChange = evt => { + _onZoomChange = (evt) => { this._onChange('zoom', evt); }; diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js index 7ed6f07a168ea..5812604a91b87 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js @@ -17,7 +17,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - initiateDraw: options => { + initiateDraw: (options) => { dispatch(updateDrawState(options)); }, cancelDraw: () => { diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js index e7c125abe70c7..a06def086b861 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js @@ -52,7 +52,7 @@ export class ToolsControl extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -61,7 +61,7 @@ export class ToolsControl extends Component { this.setState({ isPopoverOpen: false }); }; - _initiateShapeDraw = options => { + _initiateShapeDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.POLYGON, ...options, @@ -69,7 +69,7 @@ export class ToolsControl extends Component { this._closePopover(); }; - _initiateBoundsDraw = options => { + _initiateBoundsDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.BOUNDS, ...options, @@ -77,7 +77,7 @@ export class ToolsControl extends Component { this._closePopover(); }; - _initiateDistanceDraw = options => { + _initiateDistanceDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.DISTANCE, ...options, diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js index 8f11d1b23376c..0e5048a1e9190 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js @@ -28,7 +28,7 @@ export class AttributionControl extends React.Component { } _loadAttributions = async () => { - const attributionPromises = this.props.layerList.map(async layer => { + const attributionPromises = this.props.layerList.map(async (layer) => { try { return await layer.getAttributions(); } catch (error) { @@ -44,7 +44,7 @@ export class AttributionControl extends React.Component { for (let i = 0; i < attributions.length; i++) { for (let j = 0; j < attributions[i].length; j++) { const testAttr = attributions[i][j]; - const attr = uniqueAttributions.find(added => { + const attr = uniqueAttributions.find((added) => { return added.url === testAttr.url && added.label === testAttr.label; }); if (!attr) { diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js index 7ec64a94e8f47..2e85e8ab792d3 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js @@ -24,7 +24,7 @@ describe('AttributionControl', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js index 68e689d9c789e..fa7ddc4d31eaa 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js @@ -11,7 +11,7 @@ import { getLayerList } from '../../../../selectors/map_selectors'; import { getIsReadOnly } from '../../../../selectors/ui_selectors'; const mapDispatchToProps = { - updateLayerOrder: newOrder => updateLayerOrder(newOrder), + updateLayerOrder: (newOrder) => updateLayerOrder(newOrder), }; function mapStateToProps(state = {}) { diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js index da4107e747ce6..e4dc9bd84b517 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js @@ -40,15 +40,15 @@ function mapStateToProps(state = {}, ownProps) { function mapDispatchToProps(dispatch) { return { - openLayerPanel: async layerId => { + openLayerPanel: async (layerId) => { await dispatch(removeTransientLayer()); await dispatch(setSelectedLayer(layerId)); dispatch(updateFlyout(FLYOUT_STATE.LAYER_PANEL)); }, - hideTOCDetails: layerId => { + hideTOCDetails: (layerId) => { dispatch(hideTOCDetails(layerId)); }, - showTOCDetails: layerId => { + showTOCDetails: (layerId) => { dispatch(showTOCDetails(layerId)); }, }; diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx index 5eaba5330a3a7..c7ed5ec74ac7a 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx @@ -79,7 +79,7 @@ describe('TOCEntryActionsPopover', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -92,7 +92,7 @@ describe('TOCEntryActionsPopover', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -104,7 +104,7 @@ describe('TOCEntryActionsPopover', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx index 344e96e511f2e..5baac0a474ffa 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx @@ -55,7 +55,7 @@ export class TOCEntryActionsPopover extends Component { } _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js index fa200660d8e4c..90d756484c47f 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js @@ -51,7 +51,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -63,7 +63,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -74,7 +74,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -85,7 +85,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -102,7 +102,7 @@ describe('TOCEntry', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js index 49ccd503793e4..7414d810a8654 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js @@ -28,7 +28,7 @@ export class LayerTOC extends React.Component { } // Layer list is displayed in reverse order so index needs to reversed to get back to original reference. - const reverseIndex = index => { + const reverseIndex = (index) => { return this.props.layerList.length - index - 1; }; @@ -49,7 +49,7 @@ export class LayerTOC extends React.Component { const reverseLayerList = [...this.props.layerList].reverse(); if (this.props.isReadOnly) { - return reverseLayerList.map(layer => { + return reverseLayerList.map((layer) => { return ; }); } diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js index 180dc2e3933c3..9596a4df2cf17 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js @@ -60,10 +60,10 @@ export function LayerControl({ isFlyoutOpen, }) { if (!isLayerTOCOpen) { - const hasErrors = layerList.some(layer => { + const hasErrors = layerList.some((layer) => { return layer.hasErrors(); }); - const isLoading = layerList.some(layer => { + const isLoading = layerList.some((layer) => { return layer.isLayerLoading(); }); diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js index 419b169138ef1..b89fda29554ee 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js @@ -438,10 +438,10 @@ export function clamp(val, min, max) { export function extractFeaturesFromFilters(filters) { const features = []; filters - .filter(filter => { + .filter((filter) => { return filter.meta.key && filter.meta.type === SPATIAL_FILTER_TYPE; }) - .forEach(filter => { + .forEach((filter) => { let geometry; if (filter.geo_distance && filter.geo_distance[filter.meta.key]) { const distanceSplit = filter.geo_distance.distance.split('km'); diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js index c0baf5e4bcb6e..05f6a9eec5bd5 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js @@ -24,7 +24,7 @@ import { indexPatterns } from '../../../../src/plugins/data/public'; const geoFieldName = 'location'; -const flattenHitMock = hit => { +const flattenHitMock = (hit) => { const properties = {}; for (const fieldName in hit._source) { if (hit._source.hasOwnProperty(fieldName)) { @@ -173,7 +173,7 @@ describe('hitsToGeoJson', () => { describe('dot in geoFieldName', () => { const indexPatternMock = { fields: { - getByName: name => { + getByName: (name) => { const fields = { ['my.location']: { type: 'geo_point', diff --git a/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx b/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx index 01cbece32c64c..c644481d4d92e 100644 --- a/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx +++ b/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx @@ -104,7 +104,7 @@ export class MapEmbeddable extends Embeddable this.onContainerStateChanged(input)); + this._subscription = this.getInput$().subscribe((input) => this.onContainerStateChanged(input)); } setRenderTooltipContent = (renderTooltipContent: RenderToolTipContent) => { @@ -149,7 +149,7 @@ export class MapEmbeddable extends Embeddable !filter.meta.disabled), + filters: filters.filter((filter) => !filter.meta.disabled), query, timeFilters: timeRange, refresh, diff --git a/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts b/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts index f33885c2a2462..46199d59af7b5 100644 --- a/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts +++ b/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts @@ -48,7 +48,7 @@ async function waitForMapDependencies(): Promise { return whenModulesLoadedPromise; } - whenModulesLoadedPromise = new Promise(async resolve => { + whenModulesLoadedPromise = new Promise(async (resolve) => { ({ // @ts-ignore getMapsSavedObjectLoader, @@ -111,7 +111,7 @@ export class MapEmbeddableFactory implements EmbeddableFactoryDefinition { ); } - const promises = queryableIndexPatternIds.map(async indexPatternId => { + const promises = queryableIndexPatternIds.map(async (indexPatternId) => { try { // @ts-ignore return await getIndexPatternService().get(indexPatternId); diff --git a/x-pack/plugins/maps/public/index_pattern_util.js b/x-pack/plugins/maps/public/index_pattern_util.js index bbea4a9e3ab2a..d695d1087a38d 100644 --- a/x-pack/plugins/maps/public/index_pattern_util.js +++ b/x-pack/plugins/maps/public/index_pattern_util.js @@ -10,7 +10,7 @@ import { ES_GEO_FIELD_TYPE } from '../common/constants'; export async function getIndexPatternsFromIds(indexPatternIds = []) { const promises = []; - indexPatternIds.forEach(id => { + indexPatternIds.forEach((id) => { const indexPatternPromise = getIndexPatternService().get(id); if (indexPatternPromise) { promises.push(indexPatternPromise); @@ -21,7 +21,7 @@ export async function getIndexPatternsFromIds(indexPatternIds = []) { } export function getTermsFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { return ( field.aggregatable && !indexPatterns.isNestedField(field) && @@ -48,7 +48,7 @@ export function supportsGeoTileAgg(field) { // Returns filtered fields list containing only fields that exist in _source. export function getSourceFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { // Multi fields are not stored in _source and only exist in index. const isMultiField = field.subType && field.subType.multi; return !isMultiField && !indexPatterns.isNestedField(field); diff --git a/x-pack/plugins/maps/public/inspector/views/map_details.js b/x-pack/plugins/maps/public/inspector/views/map_details.js index e84cf51ed34c1..29553c75592ca 100644 --- a/x-pack/plugins/maps/public/inspector/views/map_details.js +++ b/x-pack/plugins/maps/public/inspector/views/map_details.js @@ -43,7 +43,7 @@ class MapDetails extends Component { selectedTabId: DETAILS_TAB_ID, }; - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); diff --git a/x-pack/plugins/maps/public/kibana_services.js b/x-pack/plugins/maps/public/kibana_services.js index 4e874d45bf128..ba7be7a3b2464 100644 --- a/x-pack/plugins/maps/public/kibana_services.js +++ b/x-pack/plugins/maps/public/kibana_services.js @@ -10,51 +10,52 @@ export const SPATIAL_FILTER_TYPE = esFilters.FILTERS.SPATIAL_FILTER; const { getRequestInspectorStats, getResponseInspectorStats } = search; let indexPatternService; -export const setIndexPatternService = dataIndexPatterns => +export const setIndexPatternService = (dataIndexPatterns) => (indexPatternService = dataIndexPatterns); export const getIndexPatternService = () => indexPatternService; let autocompleteService; -export const setAutocompleteService = dataAutoComplete => (autocompleteService = dataAutoComplete); +export const setAutocompleteService = (dataAutoComplete) => + (autocompleteService = dataAutoComplete); export const getAutocompleteService = () => autocompleteService; let licenseId; -export const setLicenseId = latestLicenseId => (licenseId = latestLicenseId); +export const setLicenseId = (latestLicenseId) => (licenseId = latestLicenseId); export const getLicenseId = () => { return licenseId; }; let inspector; -export const setInspector = newInspector => (inspector = newInspector); +export const setInspector = (newInspector) => (inspector = newInspector); export const getInspector = () => { return inspector; }; let fileUploadPlugin; -export const setFileUpload = fileUpload => (fileUploadPlugin = fileUpload); +export const setFileUpload = (fileUpload) => (fileUploadPlugin = fileUpload); export const getFileUploadComponent = () => { return fileUploadPlugin.JsonUploadAndParse; }; let uiSettings; -export const setUiSettings = coreUiSettings => (uiSettings = coreUiSettings); +export const setUiSettings = (coreUiSettings) => (uiSettings = coreUiSettings); export const getUiSettings = () => uiSettings; let indexPatternSelectComponent; -export const setIndexPatternSelect = indexPatternSelect => +export const setIndexPatternSelect = (indexPatternSelect) => (indexPatternSelectComponent = indexPatternSelect); export const getIndexPatternSelectComponent = () => indexPatternSelectComponent; let coreHttp; -export const setHttp = http => (coreHttp = http); +export const setHttp = (http) => (coreHttp = http); export const getHttp = () => coreHttp; let dataTimeFilter; -export const setTimeFilter = timeFilter => (dataTimeFilter = timeFilter); +export const setTimeFilter = (timeFilter) => (dataTimeFilter = timeFilter); export const getTimeFilter = () => dataTimeFilter; let toast; -export const setToasts = notificationToast => (toast = notificationToast); +export const setToasts = (notificationToast) => (toast = notificationToast); export const getToasts = () => toast; export async function fetchSearchSourceAndRecordWithInspector({ @@ -72,7 +73,7 @@ export async function fetchSearchSourceAndRecordWithInspector({ let resp; try { inspectorRequest.stats(getRequestInspectorStats(searchSource)); - searchSource.getSearchRequestBody().then(body => { + searchSource.getSearchRequestBody().then((body) => { inspectorRequest.json(body); }); resp = await searchSource.fetch({ abortSignal }); @@ -86,62 +87,62 @@ export async function fetchSearchSourceAndRecordWithInspector({ } let savedObjectsClient; -export const setSavedObjectsClient = coreSavedObjectsClient => +export const setSavedObjectsClient = (coreSavedObjectsClient) => (savedObjectsClient = coreSavedObjectsClient); export const getSavedObjectsClient = () => savedObjectsClient; let chrome; -export const setCoreChrome = coreChrome => (chrome = coreChrome); +export const setCoreChrome = (coreChrome) => (chrome = coreChrome); export const getCoreChrome = () => chrome; let mapsCapabilities; -export const setMapsCapabilities = coreAppMapsCapabilities => +export const setMapsCapabilities = (coreAppMapsCapabilities) => (mapsCapabilities = coreAppMapsCapabilities); export const getMapsCapabilities = () => mapsCapabilities; let visualizations; -export const setVisualizations = visPlugin => (visualizations = visPlugin); +export const setVisualizations = (visPlugin) => (visualizations = visPlugin); export const getVisualizations = () => visualizations; let docLinks; -export const setDocLinks = coreDocLinks => (docLinks = coreDocLinks); +export const setDocLinks = (coreDocLinks) => (docLinks = coreDocLinks); export const getDocLinks = () => docLinks; let overlays; -export const setCoreOverlays = coreOverlays => (overlays = coreOverlays); +export const setCoreOverlays = (coreOverlays) => (overlays = coreOverlays); export const getCoreOverlays = () => overlays; let data; -export const setData = dataPlugin => (data = dataPlugin); +export const setData = (dataPlugin) => (data = dataPlugin); export const getData = () => data; let uiActions; -export const setUiActions = pluginUiActions => (uiActions = pluginUiActions); +export const setUiActions = (pluginUiActions) => (uiActions = pluginUiActions); export const getUiActions = () => uiActions; let core; -export const setCore = kibanaCore => (core = kibanaCore); +export const setCore = (kibanaCore) => (core = kibanaCore); export const getCore = () => core; let navigation; -export const setNavigation = pluginNavigation => (navigation = pluginNavigation); +export const setNavigation = (pluginNavigation) => (navigation = pluginNavigation); export const getNavigation = () => navigation; let coreI18n; -export const setCoreI18n = kibanaCoreI18n => (coreI18n = kibanaCoreI18n); +export const setCoreI18n = (kibanaCoreI18n) => (coreI18n = kibanaCoreI18n); export const getCoreI18n = () => coreI18n; let dataSearchService; -export const setSearchService = searchService => (dataSearchService = searchService); +export const setSearchService = (searchService) => (dataSearchService = searchService); export const getSearchService = () => dataSearchService; let kibanaVersion; -export const setKibanaVersion = version => (kibanaVersion = version); +export const setKibanaVersion = (version) => (kibanaVersion = version); export const getKibanaVersion = () => kibanaVersion; // xpack.maps.* kibana.yml settings from this plugin let mapAppConfig; -export const setMapAppConfig = config => (mapAppConfig = config); +export const setMapAppConfig = (config) => (mapAppConfig = config); export const getMapAppConfig = () => mapAppConfig; export const getEnabled = () => getMapAppConfig().enabled; @@ -152,7 +153,7 @@ export const getEnableVectorTiles = () => getMapAppConfig().enableVectorTiles; // map.* kibana.yml settings from maps_legacy plugin that are shared between OSS map visualizations and maps app let kibanaCommonConfig; -export const setKibanaCommonConfig = config => (kibanaCommonConfig = config); +export const setKibanaCommonConfig = (config) => (kibanaCommonConfig = config); export const getKibanaCommonConfig = () => kibanaCommonConfig; export const getIsEmsEnabled = () => getKibanaCommonConfig().includeElasticMapsService; diff --git a/x-pack/plugins/maps/public/reducers/map.js b/x-pack/plugins/maps/public/reducers/map.js index d0f4b07a2d90d..c5f3968b749f1 100644 --- a/x-pack/plugins/maps/public/reducers/map.js +++ b/x-pack/plugins/maps/public/reducers/map.js @@ -283,15 +283,15 @@ export function map(state = DEFAULT_MAP_STATE, action) { }, }; case SET_SELECTED_LAYER: - const selectedMatch = state.layerList.find(layer => layer.id === action.selectedLayerId); + const selectedMatch = state.layerList.find((layer) => layer.id === action.selectedLayerId); return { ...state, selectedLayerId: selectedMatch ? action.selectedLayerId : null }; case SET_TRANSIENT_LAYER: - const transientMatch = state.layerList.find(layer => layer.id === action.transientLayerId); + const transientMatch = state.layerList.find((layer) => layer.id === action.transientLayerId); return { ...state, __transientLayerId: transientMatch ? action.transientLayerId : null }; case UPDATE_LAYER_ORDER: return { ...state, - layerList: action.newLayerOrder.map(layerNumber => state.layerList[layerNumber]), + layerList: action.newLayerOrder.map((layerNumber) => state.layerList[layerNumber]), }; case UPDATE_LAYER_PROP: return updateLayerInList(state, action.id, action.propName, action.newValue); @@ -299,12 +299,12 @@ export function map(state = DEFAULT_MAP_STATE, action) { return updateLayerSourceDescriptorProp(state, action.layerId, action.propName, action.value); case SET_JOINS: const layerDescriptor = state.layerList.find( - descriptor => descriptor.id === action.layer.getId() + (descriptor) => descriptor.id === action.layer.getId() ); if (layerDescriptor) { const newLayerDescriptor = { ...layerDescriptor, joins: action.joins.slice() }; const index = state.layerList.findIndex( - descriptor => descriptor.id === action.layer.getId() + (descriptor) => descriptor.id === action.layer.getId() ); const newLayerList = state.layerList.slice(); newLayerList[index] = newLayerDescriptor; @@ -403,7 +403,7 @@ export function map(state = DEFAULT_MAP_STATE, action) { case SET_WAITING_FOR_READY_HIDDEN_LAYERS: return { ...state, - waitingForMapReadyLayerList: state.waitingForMapReadyLayerList.map(layer => ({ + waitingForMapReadyLayerList: state.waitingForMapReadyLayerList.map((layer) => ({ ...layer, visible: !action.hiddenLayerIds.includes(layer.id), })), @@ -418,7 +418,7 @@ function findDataRequest(layerDescriptor, dataRequestAction) { return; } - return layerDescriptor.__dataRequests.find(dataRequest => { + return layerDescriptor.__dataRequests.find((dataRequest) => { return dataRequest.dataId === dataRequestAction.dataId; }); } @@ -447,7 +447,7 @@ function updateSourceDataRequest(state, action) { if (!layerDescriptor) { return state; } - const dataRequest = layerDescriptor.__dataRequests.find(dataRequest => { + const dataRequest = layerDescriptor.__dataRequests.find((dataRequest) => { return dataRequest.dataId === SOURCE_DATA_ID_ORIGIN; }); if (!dataRequest) { @@ -517,7 +517,7 @@ function getValidDataRequest(state, action, checkRequestToken = true) { } function findLayerById(state, id) { - return state.layerList.find(layer => layer.id === id); + return state.layerList.find((layer) => layer.id === id); } function trackCurrentLayerState(state, layerId) { diff --git a/x-pack/plugins/maps/public/reducers/non_serializable_instances.js b/x-pack/plugins/maps/public/reducers/non_serializable_instances.js index bbefe09bb6e43..e567a62c0c7b6 100644 --- a/x-pack/plugins/maps/public/reducers/non_serializable_instances.js +++ b/x-pack/plugins/maps/public/reducers/non_serializable_instances.js @@ -76,14 +76,14 @@ export const registerCancelCallback = (requestToken, callback) => { }; }; -export const unregisterCancelCallback = requestToken => { +export const unregisterCancelCallback = (requestToken) => { return { type: UNREGISTER_CANCEL_CALLBACK, requestToken, }; }; -export const cancelRequest = requestToken => { +export const cancelRequest = (requestToken) => { return (dispatch, getState) => { if (!requestToken) { return; diff --git a/x-pack/plugins/maps/public/reducers/ui.ts b/x-pack/plugins/maps/public/reducers/ui.ts index 5f532fea018ea..ff521c92568b3 100644 --- a/x-pack/plugins/maps/public/reducers/ui.ts +++ b/x-pack/plugins/maps/public/reducers/ui.ts @@ -81,7 +81,7 @@ export function ui(state: MapUiState = DEFAULT_MAP_UI_STATE, action: any) { case HIDE_TOC_DETAILS: return { ...state, - openTOCDetails: state.openTOCDetails.filter(layerId => { + openTOCDetails: state.openTOCDetails.filter((layerId) => { return layerId !== action.layerId; }), }; diff --git a/x-pack/plugins/maps/public/selectors/map_selectors.ts b/x-pack/plugins/maps/public/selectors/map_selectors.ts index b0e1400d513fe..90cd4f08eecdf 100644 --- a/x-pack/plugins/maps/public/selectors/map_selectors.ts +++ b/x-pack/plugins/maps/public/selectors/map_selectors.ts @@ -66,7 +66,7 @@ function createLayerInstance( const joins: IJoin[] = []; const vectorLayerDescriptor = layerDescriptor as VectorLayerDescriptor; if (vectorLayerDescriptor.joins) { - vectorLayerDescriptor.joins.forEach(joinDescriptor => { + vectorLayerDescriptor.joins.forEach((joinDescriptor) => { const join = new InnerJoin(joinDescriptor, source); joins.push(join); }); @@ -183,7 +183,7 @@ export const getQuery = ({ map }: MapStoreState): MapQuery | undefined => map.ma export const getFilters = ({ map }: MapStoreState): Filter[] => map.mapState.filters; export const isUsingSearch = (state: MapStoreState): boolean => { - const filters = getFilters(state).filter(filter => !filter.meta.disabled); + const filters = getFilters(state).filter((filter) => !filter.meta.disabled); const queryString = _.get(getQuery(state), 'query', ''); return !!filters.length || !!queryString.length; }; @@ -212,7 +212,7 @@ export const getRefreshTimerLastTriggeredAt = ({ map }: MapStoreState): string | function getLayerDescriptor(state: MapStoreState, layerId: string) { const layerListRaw = getLayerListRaw(state); - return layerListRaw.find(layer => layer.id === layerId); + return layerListRaw.find((layer) => layer.id === layerId); } export function getDataRequestDescriptor(state: MapStoreState, layerId: string, dataId: string) { @@ -294,20 +294,20 @@ export const getLayerList = createSelector( getLayerListRaw, getInspectorAdapters, (layerDescriptorList, inspectorAdapters) => { - return layerDescriptorList.map(layerDescriptor => + return layerDescriptorList.map((layerDescriptor) => createLayerInstance(layerDescriptor, inspectorAdapters) ); } ); export function getLayerById(layerId: string, state: MapStoreState): ILayer | undefined { - return getLayerList(state).find(layer => { + return getLayerList(state).find((layer) => { return layerId === layer.getId(); }); } -export const getFittableLayers = createSelector(getLayerList, layerList => { - return layerList.filter(layer => { +export const getFittableLayers = createSelector(getLayerList, (layerList) => { + return layerList.filter((layer) => { // These are the only layer-types that implement bounding-box retrieval reliably // This will _not_ work if Maps will allow register custom layer types const isFittable = @@ -319,15 +319,15 @@ export const getFittableLayers = createSelector(getLayerList, layerList => { }); }); -export const getHiddenLayerIds = createSelector(getLayerListRaw, layers => - layers.filter(layer => !layer.visible).map(layer => layer.id) +export const getHiddenLayerIds = createSelector(getLayerListRaw, (layers) => + layers.filter((layer) => !layer.visible).map((layer) => layer.id) ); export const getSelectedLayer = createSelector( getSelectedLayerId, getLayerList, (selectedLayerId, layerList) => { - return layerList.find(layer => layer.getId() === selectedLayerId); + return layerList.find((layer) => layer.getId() === selectedLayerId); } ); @@ -345,7 +345,7 @@ export const getMapColors = createSelector( }, []) ); -export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, selectedLayer => { +export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, (selectedLayer) => { if (!selectedLayer || !('getJoins' in selectedLayer)) { return []; } @@ -356,18 +356,18 @@ export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, }); // Get list of unique index patterns used by all layers -export const getUniqueIndexPatternIds = createSelector(getLayerList, layerList => { +export const getUniqueIndexPatternIds = createSelector(getLayerList, (layerList) => { const indexPatternIds: string[] = []; - layerList.forEach(layer => { + layerList.forEach((layer) => { indexPatternIds.push(...layer.getIndexPatternIds()); }); return _.uniq(indexPatternIds).sort(); }); // Get list of unique index patterns, excluding index patterns from layers that disable applyGlobalQuery -export const getQueryableUniqueIndexPatternIds = createSelector(getLayerList, layerList => { +export const getQueryableUniqueIndexPatternIds = createSelector(getLayerList, (layerList) => { const indexPatternIds: string[] = []; - layerList.forEach(layer => { + layerList.forEach((layer) => { indexPatternIds.push(...layer.getQueryableIndexPatternIds()); }); return _.uniq(indexPatternIds); @@ -381,7 +381,7 @@ export const hasDirtyState = createSelector( return true; } - return layerListRaw.some(layerDescriptor => { + return layerListRaw.some((layerDescriptor) => { const trackedState = layerDescriptor[TRACKED_LAYER_DESCRIPTOR]; if (!trackedState) { return false; diff --git a/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js b/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js index 066996ef8a6b9..27b6ff0fc6a51 100644 --- a/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js +++ b/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js @@ -10,7 +10,7 @@ import { DEFAULT_MAX_RESULT_WINDOW, DEFAULT_MAX_INNER_RESULT_WINDOW } from '../. export function getIndexPatternSettings(indicesSettingsResp) { let maxResultWindow = Infinity; let maxInnerResultWindow = Infinity; - Object.values(indicesSettingsResp).forEach(indexSettings => { + Object.values(indicesSettingsResp).forEach((indexSettings) => { const indexMaxResultWindow = _.get( indexSettings, 'settings.index.max_result_window', diff --git a/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts b/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts index 6c62ceb347c85..463d3f3b3939d 100644 --- a/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts +++ b/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts @@ -36,7 +36,7 @@ interface ILayerTypeCount { } function getUniqueLayerCounts(layerCountsList: ILayerTypeCount[], mapsCount: number) { - const uniqueLayerTypes = _.uniq(_.flatten(layerCountsList.map(lTypes => Object.keys(lTypes)))); + const uniqueLayerTypes = _.uniq(_.flatten(layerCountsList.map((lTypes) => Object.keys(lTypes)))); return uniqueLayerTypes.reduce((accu: IStats, type: string) => { const typeCounts = layerCountsList.reduce( @@ -59,24 +59,24 @@ function getUniqueLayerCounts(layerCountsList: ILayerTypeCount[], mapsCount: num } function getIndexPatternsWithGeoFieldCount(indexPatterns: IIndexPattern[]) { - const fieldLists = indexPatterns.map(indexPattern => + const fieldLists = indexPatterns.map((indexPattern) => indexPattern.attributes && indexPattern.attributes.fields ? JSON.parse(indexPattern.attributes.fields) : [] ); - const fieldListsWithGeoFields = fieldLists.filter(fields => + const fieldListsWithGeoFields = fieldLists.filter((fields) => fields.some( (field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_POINT || field.type === ES_GEO_FIELD_TYPE.GEO_SHAPE ) ); - const fieldListsWithGeoPointFields = fieldLists.filter(fields => + const fieldListsWithGeoPointFields = fieldLists.filter((fields) => fields.some((field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_POINT) ); - const fieldListsWithGeoShapeFields = fieldLists.filter(fields => + const fieldListsWithGeoShapeFields = fieldLists.filter((fields) => fields.some((field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_SHAPE) ); @@ -96,25 +96,25 @@ export function buildMapsTelemetry({ indexPatternSavedObjects: IIndexPattern[]; settings: SavedObjectAttribute; }): SavedObjectAttributes { - const layerLists = mapSavedObjects.map(savedMapObject => + const layerLists = mapSavedObjects.map((savedMapObject) => savedMapObject.attributes && savedMapObject.attributes.layerListJSON ? JSON.parse(savedMapObject.attributes.layerListJSON) : [] ); const mapsCount = layerLists.length; - const dataSourcesCount = layerLists.map(lList => { + const dataSourcesCount = layerLists.map((lList) => { // todo: not every source-descriptor has an id // @ts-ignore const sourceIdList = lList.map((layer: LayerDescriptor) => layer.sourceDescriptor.id); return _.uniq(sourceIdList).length; }); - const layersCount = layerLists.map(lList => lList.length); - const layerTypesCount = layerLists.map(lList => _.countBy(lList, 'type')); + const layersCount = layerLists.map((lList) => lList.length); + const layerTypesCount = layerLists.map((lList) => _.countBy(lList, 'type')); // Count of EMS Vector layers used - const emsLayersCount = layerLists.map(lList => + const emsLayersCount = layerLists.map((lList) => _(lList) .countBy((layer: LayerDescriptor) => { const isEmsFile = _.get(layer, 'sourceDescriptor.type') === SOURCE_TYPES.EMS_FILE; diff --git a/x-pack/plugins/maps/server/routes.js b/x-pack/plugins/maps/server/routes.js index de07472275c0c..766ba72b2dcef 100644 --- a/x-pack/plugins/maps/server/routes.js +++ b/x-pack/plugins/maps/server/routes.js @@ -87,7 +87,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const fileLayers = await emsClient.getFileLayers(); - const layer = fileLayers.find(layer => layer.getId() === request.query.id); + const layer = fileLayers.find((layer) => layer.getId() === request.query.id); if (!layer) { return null; } @@ -124,7 +124,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -155,8 +155,8 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { }; //rewrite the urls to the submanifest - const tileService = main.services.find(service => service.type === 'tms'); - const fileService = main.services.find(service => service.type === 'file'); + const tileService = main.services.find((service) => service.type === 'tms'); + const fileService = main.services.find((service) => service.type === 'file'); if (tileService) { proxiedManifest.services.push({ ...tileService, @@ -186,7 +186,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const file = await emsClient.getDefaultFileManifest(); - const layers = file.layers.map(layer => { + const layers = file.layers.map((layer) => { const newLayer = { ...layer }; const id = encodeURIComponent(layer.layer_id); const newUrl = `${EMS_FILES_DEFAULT_JSON_PATH}?id=${id}`; @@ -216,13 +216,13 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tilesManifest = await emsClient.getDefaultTMSManifest(); - const newServices = tilesManifest.services.map(service => { + const newServices = tilesManifest.services.map((service) => { const newService = { ...service, }; newService.formats = []; - const rasterFormats = service.formats.filter(format => format.format === 'raster'); + const rasterFormats = service.formats.filter((format) => format.format === 'raster'); if (rasterFormats.length) { const newUrl = `${EMS_TILES_RASTER_STYLE_PATH}?id=${service.id}`; newService.formats.push({ @@ -230,7 +230,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { url: newUrl, }); } - const vectorFormats = service.formats.filter(format => format.format === 'vector'); + const vectorFormats = service.formats.filter((format) => format.format === 'vector'); if (vectorFormats.length) { const newUrl = `${EMS_TILES_VECTOR_STYLE_PATH}?id=${service.id}`; newService.formats.push({ @@ -269,7 +269,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -305,7 +305,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -355,7 +355,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -403,7 +403,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -455,7 +455,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.params.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.params.id); if (!tmsService) { return null; } diff --git a/x-pack/plugins/maps/server/saved_objects/migrations.js b/x-pack/plugins/maps/server/saved_objects/migrations.js index 13b38353d6807..5f9576740db29 100644 --- a/x-pack/plugins/maps/server/saved_objects/migrations.js +++ b/x-pack/plugins/maps/server/saved_objects/migrations.js @@ -15,7 +15,7 @@ import { migrateJoinAggKey } from '../../common/migrations/join_agg_key'; export const migrations = { map: { - '7.2.0': doc => { + '7.2.0': (doc) => { const { attributes, references } = extractReferences(doc); return { @@ -24,7 +24,7 @@ export const migrations = { references, }; }, - '7.4.0': doc => { + '7.4.0': (doc) => { const attributes = emsRasterTileToEmsVectorTile(doc); return { @@ -32,7 +32,7 @@ export const migrations = { attributes, }; }, - '7.5.0': doc => { + '7.5.0': (doc) => { const attributes = topHitsTimeToSort(doc); return { @@ -40,7 +40,7 @@ export const migrations = { attributes, }; }, - '7.6.0': doc => { + '7.6.0': (doc) => { const attributesPhase1 = moveApplyGlobalQueryToSources(doc); const attributesPhase2 = addFieldMetaOptions({ attributes: attributesPhase1 }); @@ -49,7 +49,7 @@ export const migrations = { attributes: attributesPhase2, }; }, - '7.7.0': doc => { + '7.7.0': (doc) => { const attributesPhase1 = migrateSymbolStyleDescriptor(doc); const attributesPhase2 = migrateUseTopHitsToScalingType({ attributes: attributesPhase1 }); @@ -58,7 +58,7 @@ export const migrations = { attributes: attributesPhase2, }; }, - '7.8.0': doc => { + '7.8.0': (doc) => { const attributes = migrateJoinAggKey(doc); return { diff --git a/x-pack/plugins/ml/common/license/ml_license.ts b/x-pack/plugins/ml/common/license/ml_license.ts index 25b5b4992b227..e4367c9b921f4 100644 --- a/x-pack/plugins/ml/common/license/ml_license.ts +++ b/x-pack/plugins/ml/common/license/ml_license.ts @@ -31,7 +31,7 @@ export class MlLicense { license$: Observable, postInitFunctions?: Array<(lic: MlLicense) => void> ) { - this._licenseSubscription = license$.subscribe(async license => { + this._licenseSubscription = license$.subscribe(async (license) => { const { isEnabled: securityIsEnabled } = license.getFeature('security'); this._license = license; @@ -42,7 +42,7 @@ export class MlLicense { this._isFullLicense = isFullLicense(this._license); if (this._initialized === false && postInitFunctions !== undefined) { - postInitFunctions.forEach(f => f(this)); + postInitFunctions.forEach((f) => f(this)); } this._initialized = true; }); diff --git a/x-pack/plugins/ml/common/types/capabilities.ts b/x-pack/plugins/ml/common/types/capabilities.ts index 572217ce16eee..9216430ab7830 100644 --- a/x-pack/plugins/ml/common/types/capabilities.ts +++ b/x-pack/plugins/ml/common/types/capabilities.ts @@ -73,11 +73,11 @@ export function getPluginPrivileges() { return { user: { ui: userMlCapabilitiesKeys, - api: userMlCapabilitiesKeys.map(k => `ml:${k}`), + api: userMlCapabilitiesKeys.map((k) => `ml:${k}`), }, admin: { ui: allMlCapabilities, - api: allMlCapabilities.map(k => `ml:${k}`), + api: allMlCapabilities.map((k) => `ml:${k}`), }, }; } diff --git a/x-pack/plugins/ml/common/types/common.ts b/x-pack/plugins/ml/common/types/common.ts index 691b3e9eb1163..f04ff2539e4e9 100644 --- a/x-pack/plugins/ml/common/types/common.ts +++ b/x-pack/plugins/ml/common/types/common.ts @@ -11,7 +11,7 @@ export interface Dictionary { // converts a dictionary to an array. note this loses the dictionary `key` information. // however it's able to retain the type information of the dictionary elements. export function dictionaryToArray(dict: Dictionary): TValue[] { - return Object.keys(dict).map(key => dict[key]); + return Object.keys(dict).map((key) => dict[key]); } // A recursive partial type to allow passing nested partial attributes. diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index 3822e54ddd53c..1fef0e6e2ecba 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -178,7 +178,7 @@ export function isModelPlotEnabled( if (detectorHasPartitionField) { const partitionEntity = entityFields.find( - entityField => entityField.fieldName === detector.partition_field_name + (entityField) => entityField.fieldName === detector.partition_field_name ); isEnabled = partitionEntity?.fieldValue !== undefined && @@ -187,7 +187,7 @@ export function isModelPlotEnabled( if (isEnabled === true && detectorHasByField === true) { const byEntity = entityFields.find( - entityField => entityField.fieldName === detector.by_field_name + (entityField) => entityField.fieldName === detector.by_field_name ); isEnabled = byEntity?.fieldValue !== undefined && terms.indexOf(String(byEntity.fieldValue)) !== -1; @@ -349,7 +349,7 @@ export function basicJobValidation( // Analysis Configuration if (job.analysis_config.categorization_filters) { let v = true; - _.each(job.analysis_config.categorization_filters, d => { + _.each(job.analysis_config.categorization_filters, (d) => { try { new RegExp(d); } catch (e) { @@ -381,7 +381,7 @@ export function basicJobValidation( valid = false; } else { let v = true; - _.each(job.analysis_config.detectors, d => { + _.each(job.analysis_config.detectors, (d) => { if (_.isEmpty(d.function)) { v = false; } @@ -398,7 +398,7 @@ export function basicJobValidation( if (job.analysis_config.detectors.length >= 2) { // create an array of objects with a subset of the attributes // where we want to make sure they are not be the same across detectors - const compareSubSet = job.analysis_config.detectors.map(d => + const compareSubSet = job.analysis_config.detectors.map((d) => _.pick(d, [ 'function', 'field_name', @@ -479,8 +479,8 @@ export function basicJobValidation( return { messages, valid, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -507,8 +507,8 @@ export function basicDatafeedValidation(datafeed: Datafeed): ValidationResults { return { messages, valid, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -540,8 +540,8 @@ export function validateModelMemoryLimit(job: Job, limits: MlServerLimits): Vali return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -567,16 +567,16 @@ export function validateModelMemoryLimitUnits( return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } export function validateGroupNames(job: Job): ValidationResults { const { groups = [] } = job; const errorMessages: ValidationResults['messages'] = [ - ...(groups.some(group => !isJobIdValid(group)) ? [{ id: 'job_group_id_invalid' }] : []), - ...(groups.some(group => maxLengthValidator(JOB_ID_MAX_LENGTH)(group)) + ...(groups.some((group) => !isJobIdValid(group)) ? [{ id: 'job_group_id_invalid' }] : []), + ...(groups.some((group) => maxLengthValidator(JOB_ID_MAX_LENGTH)(group)) ? [{ id: 'job_group_id_invalid_max_length' }] : []), ]; @@ -586,8 +586,8 @@ export function validateGroupNames(job: Job): ValidationResults { return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -626,6 +626,6 @@ export function processCreatedBy(customSettings: CustomSettings) { export function splitIndexPatternNames(indexPatternName: string): string[] { return indexPatternName.includes(',') - ? indexPatternName.split(',').map(i => i.trim()) + ? indexPatternName.split(',').map((i) => i.trim()) : [indexPatternName]; } diff --git a/x-pack/plugins/ml/common/util/parse_interval.ts b/x-pack/plugins/ml/common/util/parse_interval.ts index 98a41be96941b..0f348f43d47b3 100644 --- a/x-pack/plugins/ml/common/util/parse_interval.ts +++ b/x-pack/plugins/ml/common/util/parse_interval.ts @@ -26,9 +26,7 @@ const SUPPORT_ZERO_DURATION_UNITS: SupportedUnits[] = ['ms', 's', 'm', 'h']; // 3. Fractional intervals e.g. 1.5h or 4.5d are not allowed, in line with the behaviour // of the Elasticsearch date histogram aggregation. export function parseInterval(interval: string): Duration | null { - const matches = String(interval) - .trim() - .match(INTERVAL_STRING_RE); + const matches = String(interval).trim().match(INTERVAL_STRING_RE); if (!Array.isArray(matches) || matches.length < 3) { return null; } diff --git a/x-pack/plugins/ml/common/util/string_utils.ts b/x-pack/plugins/ml/common/util/string_utils.ts index 9dd2ce3d74cd5..bd4ca02bf93cc 100644 --- a/x-pack/plugins/ml/common/util/string_utils.ts +++ b/x-pack/plugins/ml/common/util/string_utils.ts @@ -10,7 +10,7 @@ export function renderTemplate(str: string, data?: Record): stri const matches = str.match(/{{(.*?)}}/g); if (Array.isArray(matches) && data !== undefined) { - matches.forEach(v => { + matches.forEach((v) => { str = str.replace(v, data[v.replace(/{{|}}/g, '')]); }); } @@ -19,6 +19,6 @@ export function renderTemplate(str: string, data?: Record): stri } export function getMedianStringLength(strings: string[]) { - const sortedStringLengths = strings.map(s => s.length).sort((a, b) => a - b); + const sortedStringLengths = strings.map((s) => s.length).sort((a, b) => a - b); return sortedStringLengths[Math.floor(sortedStringLengths.length / 2)] || 0; } diff --git a/x-pack/plugins/ml/common/util/validation_utils.ts b/x-pack/plugins/ml/common/util/validation_utils.ts index 1ae5a899a4b4d..ee4be34c6f600 100644 --- a/x-pack/plugins/ml/common/util/validation_utils.ts +++ b/x-pack/plugins/ml/common/util/validation_utils.ts @@ -10,7 +10,7 @@ import { VALIDATION_STATUS } from '../constants/validation'; const contains = (arr: string[], str: string) => arr.indexOf(str) >= 0; export function getMostSevereMessageStatus(messages: Array<{ status: string }>): VALIDATION_STATUS { - const statuses = messages.map(m => m.status); + const statuses = messages.map((m) => m.status); return [VALIDATION_STATUS.INFO, VALIDATION_STATUS.WARNING, VALIDATION_STATUS.ERROR].reduce( (previous, current) => { return contains(statuses, current) ? current : previous; diff --git a/x-pack/plugins/ml/common/util/validators.ts b/x-pack/plugins/ml/common/util/validators.ts index 304d9a0029540..6f959c50219cf 100644 --- a/x-pack/plugins/ml/common/util/validators.ts +++ b/x-pack/plugins/ml/common/util/validators.ts @@ -13,7 +13,7 @@ import { ALLOWED_DATA_UNITS } from '../constants/validation'; export function maxLengthValidator( maxLength: number ): (value: string) => { maxLength: { requiredLength: number; actualLength: number } } | null { - return value => + return (value) => value && value.length > maxLength ? { maxLength: { @@ -31,7 +31,7 @@ export function maxLengthValidator( export function patternValidator( pattern: RegExp ): (value: string) => { pattern: { matchPattern: string } } | null { - return value => + return (value) => pattern.test(value) ? null : { @@ -48,7 +48,7 @@ export function patternValidator( export function composeValidators( ...validators: Array<(value: any) => { [key: string]: any } | null> ): (value: any) => { [key: string]: any } | null { - return value => { + return (value) => { const validationResult = validators.reduce((acc, validator) => { return { ...acc, diff --git a/x-pack/plugins/ml/public/application/app.tsx b/x-pack/plugins/ml/public/application/app.tsx index e9796fcbb0fe4..4b6ff8c64822b 100644 --- a/x-pack/plugins/ml/public/application/app.tsx +++ b/x-pack/plugins/ml/public/application/app.tsx @@ -78,7 +78,7 @@ export const renderApp = ( const mlLicense = setLicenseCache(deps.licensing); - appMountParams.onAppLeave(actions => actions.default()); + appMountParams.onAppLeave((actions) => actions.default()); ReactDOM.render(, appMountParams.element); diff --git a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts index 1ca176d8d09ce..65ea03caef526 100644 --- a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts @@ -20,7 +20,7 @@ export function checkGetManagementMlJobsResolver() { ({ capabilities, isPlatinumOrTrialLicense, mlFeatureEnabledInSpace }) => { _capabilities = capabilities; // Loop through all capabilities to ensure they are all set to true. - const isManageML = Object.values(_capabilities).every(p => p === true); + const isManageML = Object.values(_capabilities).every((p) => p === true); if (isManageML === true && isPlatinumOrTrialLicense === true) { return resolve({ mlFeatureEnabledInSpace }); diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx index ceaf986b0d54f..f341f129e4653 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx @@ -185,7 +185,7 @@ class AnnotationFlyoutUI extends Component { ); } }) - .catch(resp => { + .catch((resp) => { const toastNotifications = getToastNotifications(); if (typeof annotation._id === 'undefined') { toastNotifications.addDanger( @@ -339,7 +339,7 @@ class AnnotationFlyoutUI extends Component { } } -export const AnnotationFlyout: FC = props => { +export const AnnotationFlyout: FC = (props) => { const annotationProp = useObservable(annotation$); if (annotationProp === undefined) { diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js index d9c32be41cd72..52d266cde1a2c 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js @@ -95,7 +95,7 @@ export class AnnotationsTable extends Component { maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, }) .toPromise() - .then(resp => { + .then((resp) => { this.setState((prevState, props) => ({ annotations: resp.annotations[props.jobs[0].job_id] || [], errorMessage: undefined, @@ -103,7 +103,7 @@ export class AnnotationsTable extends Component { jobId: props.jobs[0].job_id, })); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of annotations for jobs list:', resp); this.setState({ annotations: [], @@ -225,7 +225,7 @@ export class AnnotationsTable extends Component { window.open(`#/timeseriesexplorer${url}`, '_self'); }; - onMouseOverRow = record => { + onMouseOverRow = (record) => { if (this.mouseOverRecord !== undefined) { if (this.mouseOverRecord.rowId !== record.rowId) { // Mouse is over a different row, fire mouseleave on the previous record. @@ -354,7 +354,7 @@ export class AnnotationsTable extends Component { }, ]; - const jobIds = _.uniq(annotations.map(a => a.job_id)); + const jobIds = _.uniq(annotations.map((a) => a.job_id)); if (jobIds.length > 1) { columns.unshift({ field: 'job_id', @@ -373,7 +373,7 @@ export class AnnotationsTable extends Component { }), sortable: true, width: '60px', - render: key => { + render: (key) => { return {key}; }, }); @@ -382,7 +382,7 @@ export class AnnotationsTable extends Component { const actions = []; actions.push({ - render: annotation => { + render: (annotation) => { const editAnnotationsTooltipText = ( { + render: (annotation) => { const isDrillDownAvailable = isTimeSeriesViewJob(this.getJob(annotation.job_id)); const openInSingleMetricViewerTooltipText = isDrillDownAvailable ? ( { + const getRowProps = (item) => { return { onMouseOver: () => this.onMouseOverRow(item), onMouseLeave: () => this.onMouseLeaveRow(), diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js index 6728f019a6bd5..2a890f75fecd8 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js @@ -44,8 +44,8 @@ class AnomaliesTable extends Component { // Update the itemIdToExpandedRowMap state if a change to the table data has resulted // in an anomaly that was previously expanded no longer being in the data. const itemIdToExpandedRowMap = prevState.itemIdToExpandedRowMap; - const prevExpandedNotInData = Object.keys(itemIdToExpandedRowMap).find(rowId => { - const matching = nextProps.tableData.anomalies.find(anomaly => { + const prevExpandedNotInData = Object.keys(itemIdToExpandedRowMap).find((rowId) => { + const matching = nextProps.tableData.anomalies.find((anomaly) => { return anomaly.rowId === rowId; }); @@ -108,7 +108,7 @@ class AnomaliesTable extends Component { this.setState({ itemIdToExpandedRowMap }); }; - onMouseOverRow = record => { + onMouseOverRow = (record) => { if (this.mouseOverRecord !== undefined) { if (this.mouseOverRecord.rowId !== record.rowId) { // Mouse is over a different row, fire mouseleave on the previous record. @@ -132,7 +132,7 @@ class AnomaliesTable extends Component { } }; - setShowRuleEditorFlyoutFunction = func => { + setShowRuleEditorFlyoutFunction = (func) => { this.setState({ showRuleEditorFlyout: func, }); @@ -191,7 +191,7 @@ class AnomaliesTable extends Component { }, }; - const getRowProps = item => { + const getRowProps = (item) => { return { onMouseOver: () => this.onMouseOverRow(item), onMouseLeave: () => this.onMouseLeaveRow(), diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js index 8f79ce4a6c08a..af7c6c8e289f3 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js @@ -76,7 +76,7 @@ export function getColumns(

), - render: item => ( + render: (item) => ( toggleRow(item)} iconType={itemIdToExpandedRowMap[item.rowId] ? 'arrowDown' : 'arrowRight'} @@ -102,7 +102,7 @@ export function getColumns( }), dataType: 'date', scope: 'row', - render: date => renderTime(date, interval), + render: (date) => renderTime(date, interval), textOnly: true, sortable: true, }, @@ -131,7 +131,7 @@ export function getColumns( }, ]; - if (items.some(item => item.entityValue !== undefined)) { + if (items.some((item) => item.entityValue !== undefined)) { columns.push({ field: 'entityValue', 'data-test-subj': 'mlAnomaliesListColumnFoundFor', @@ -151,14 +151,14 @@ export function getColumns( }); } - if (items.some(item => item.influencers !== undefined)) { + if (items.some((item) => item.influencers !== undefined)) { columns.push({ field: 'influencers', 'data-test-subj': 'mlAnomaliesListColumnInfluencers', name: i18n.translate('xpack.ml.anomaliesTable.influencersColumnName', { defaultMessage: 'influenced by', }), - render: influencers => ( + render: (influencers) => ( item.actual !== undefined)) { + if (items.some((item) => item.actual !== undefined)) { columns.push({ field: 'actualSort', 'data-test-subj': 'mlAnomaliesListColumnActual', @@ -191,7 +191,7 @@ export function getColumns( }); } - if (items.some(item => item.typical !== undefined)) { + if (items.some((item) => item.typical !== undefined)) { columns.push({ field: 'typicalSort', 'data-test-subj': 'mlAnomaliesListColumnTypical', @@ -210,7 +210,7 @@ export function getColumns( // Assume that if we are showing typical, there will be an actual too, // so we can add a column to describe how actual compares to typical. - const nonTimeOfDayOrWeek = items.some(item => { + const nonTimeOfDayOrWeek = items.some((item) => { const summaryRecFunc = item.source.function; return summaryRecFunc !== 'time_of_day' && summaryRecFunc !== 'time_of_week'; }); @@ -241,7 +241,7 @@ export function getColumns( }); } - const showExamples = items.some(item => item.entityName === 'mlcategory'); + const showExamples = items.some((item) => item.entityName === 'mlcategory'); if (showExamples === true) { columns.push({ 'data-test-subj': 'mlAnomaliesListColumnCategoryExamples', @@ -250,7 +250,7 @@ export function getColumns( }), sortable: false, truncateText: true, - render: item => { + render: (item) => { const examples = _.get(examplesByJobId, [item.jobId, item.entityValue], []); return ( showLinksMenuForItem(item, showViewSeriesLink)); + const showLinks = items.some((item) => showLinksMenuForItem(item, showViewSeriesLink)); if (showLinks === true) { columns.push({ @@ -280,7 +280,7 @@ export function getColumns( name: i18n.translate('xpack.ml.anomaliesTable.actionsColumnName', { defaultMessage: 'actions', }), - render: item => { + render: (item) => { if (showLinksMenuForItem(item, showViewSeriesLink) === true) { return ( { + causes = sourceCauses.map((cause) => { const simplified = _.pick(cause, 'typical', 'actual', 'probability'); // Get the 'entity field name/value' to display in the cause - // For by and over, use by_field_name/value (over_field_name/value are in the top level fields) @@ -229,7 +229,7 @@ function getInfluencersItems(anomalyInfluencers, influencerFilter, numToDisplay) const items = []; for (let i = 0; i < numToDisplay; i++) { - Object.keys(anomalyInfluencers[i]).forEach(influencerFieldName => { + Object.keys(anomalyInfluencers[i]).forEach((influencerFieldName) => { const value = anomalyInfluencers[i][influencerFieldName]; items.push({ diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js index f4b16dab5ef52..2e42606c048d7 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js @@ -147,7 +147,7 @@ export class InfluencersCell extends Component { const recordInfluencers = this.props.influencers || []; const influencers = []; - recordInfluencers.forEach(influencer => { + recordInfluencers.forEach((influencer) => { _.each(influencer, (influencerFieldValue, influencerFieldName) => { influencers.push({ influencerFieldName, diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js index ef4f35591edf4..4850d583a626c 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js @@ -51,7 +51,7 @@ class LinksMenuUI extends Component { }; } - openCustomUrl = customUrl => { + openCustomUrl = (customUrl) => { const { anomaly, interval, isAggregatedData } = this.props; console.log('Anomalies Table - open customUrl for record:', anomaly); @@ -107,10 +107,10 @@ class LinksMenuUI extends Component { ml.results .getCategoryDefinition(jobId, categoryId) - .then(resp => { + .then((resp) => { // Prefix each of the terms with '+' so that the Elasticsearch Query String query // run in a drilldown Kibana dashboard has to match on all terms. - const termsArray = resp.terms.split(' ').map(term => `+${term}`); + const termsArray = resp.terms.split(' ').map((term) => `+${term}`); record.mlcategoryterms = termsArray.join(' '); record.mlcategoryregex = resp.regex; @@ -119,7 +119,7 @@ class LinksMenuUI extends Component { const urlPath = replaceStringTokens(customUrl.url_value, record, true); openCustomUrlWindow(urlPath, customUrl); }) - .catch(resp => { + .catch((resp) => { console.log('openCustomUrl(): error loading categoryDefinition:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -267,7 +267,7 @@ class LinksMenuUI extends Component { // categorization field is of mapping type text (preferred) or keyword. ml.results .getCategoryDefinition(record.job_id, categoryId) - .then(resp => { + .then((resp) => { let query = null; // Build query using categorization regex (if keyword type) or terms (if text type). // Check for terms or regex in case categoryId represents an anomaly from the absence of the @@ -327,7 +327,7 @@ class LinksMenuUI extends Component { path += '&_a=' + encodeURIComponent(_a); window.open(path, '_blank'); }) - .catch(resp => { + .catch((resp) => { console.log('viewExamples(): error loading categoryDefinition:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -344,7 +344,7 @@ class LinksMenuUI extends Component { function findFieldType(index) { getFieldTypeFromMapping(index, categorizationFieldName) - .then(resp => { + .then((resp) => { if (resp !== '') { createAndOpenUrl(index, resp); } else { @@ -363,7 +363,7 @@ class LinksMenuUI extends Component { }; onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx index 3ca191d6251cf..7897ef5cad0df 100644 --- a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx +++ b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx @@ -27,7 +27,7 @@ const Tooltip: FC<{ service: ChartTooltipService }> = React.memo(({ service }) = const refCallback = useRef(); useEffect(() => { - const subscription = service.tooltipState$.subscribe(tooltipState => { + const subscription = service.tooltipState$.subscribe((tooltipState) => { if (refCallback.current) { // update trigger refCallback.current(tooltipState.target); diff --git a/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx b/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx index d6f0d347a57ec..25af3f0ec2f7f 100644 --- a/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx +++ b/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx @@ -36,7 +36,7 @@ export const ColorRangeLegend: FC = ({ }) => { const d3Container = useRef(null); - const scale = d3.range(COLOR_RANGE_RESOLUTION + 1).map(d => ({ + const scale = d3.range(COLOR_RANGE_RESOLUTION + 1).map((d) => ({ offset: (d / COLOR_RANGE_RESOLUTION) * 100, stopColor: colorRange(d / COLOR_RANGE_RESOLUTION), })); @@ -59,9 +59,7 @@ export const ColorRangeLegend: FC = ({ const legendHeight = wrapperHeight - margin.top - margin.bottom; // remove, then redraw the legend - d3.select(d3Container.current) - .selectAll('*') - .remove(); + d3.select(d3Container.current).selectAll('*').remove(); const wrapper = d3 .select(d3Container.current) @@ -82,7 +80,7 @@ export const ColorRangeLegend: FC = ({ .attr('y2', '0%') .attr('spreadMethod', 'pad'); - scale.forEach(function(d) { + scale.forEach(function (d) { gradient .append('stop') .attr('offset', `${d.offset}%`) @@ -98,10 +96,7 @@ export const ColorRangeLegend: FC = ({ .attr('height', legendHeight) .style('fill', 'url(#mlColorRangeGradient)'); - const axisScale = d3.scale - .linear() - .domain([0, 1]) - .range([0, legendWidth]); + const axisScale = d3.scale.linear().domain([0, 1]).range([0, legendWidth]); // Using this formatter ensures we get e.g. `0` and not `0.0`, but still `0.1`, `0.2` etc. const tickFormat = d3.format(''); diff --git a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx index e1861b887b2a9..83e7b82986cf8 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx @@ -26,7 +26,7 @@ describe('SelectInterval', () => { expect(defaultSelectedValue).toBe('auto'); }); - test('currently selected value is updated correctly on click', done => { + test('currently selected value is updated correctly on click', (done) => { const wrapper = mount( diff --git a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx index cea3ef2a497b0..307900c6985ff 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx @@ -47,7 +47,7 @@ const OPTIONS = [ function optionValueToInterval(value: string) { // Builds the corresponding interval object with the required display and val properties // from the specified value. - const option = OPTIONS.find(opt => opt.value === value); + const option = OPTIONS.find((opt) => opt.value === value); // Default to auto if supplied value doesn't map to one of the options. let interval: TableInterval = { display: OPTIONS[0].text, val: OPTIONS[0].value }; diff --git a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx index e30c48c10a194..484a0c395f3f8 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx @@ -62,7 +62,7 @@ describe('SelectSeverity', () => { ); }); - test('state for currently selected value is updated correctly on click', done => { + test('state for currently selected value is updated correctly on click', (done) => { const wrapper = mount( diff --git a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx index a03594a5f213e..b8333e72c9ffb 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx @@ -67,7 +67,7 @@ export const SEVERITY_OPTIONS: TableSeverity[] = [ function optionValueToThreshold(value: number) { // Get corresponding threshold object with required display and val properties from the specified value. - let threshold = SEVERITY_OPTIONS.find(opt => opt.val === value); + let threshold = SEVERITY_OPTIONS.find((opt) => opt.val === value); // Default to warning if supplied value doesn't map to one of the options. if (threshold === undefined) { diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index d141b68b5d03f..44a2473f75937 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts @@ -55,8 +55,8 @@ export const euiDataGridToolbarSettings = { }; export const getFieldsFromKibanaIndexPattern = (indexPattern: IndexPattern): string[] => { - const allFields = indexPattern.fields.map(f => f.name); - const indexPatternFields: string[] = allFields.filter(f => { + const allFields = indexPattern.fields.map((f) => f.name); + const indexPatternFields: string[] = allFields.filter((f) => { if (indexPattern.metaFields.includes(f)) { return false; } @@ -78,7 +78,7 @@ export interface FieldTypes { } export const getDataGridSchemasFromFieldTypes = (fieldTypes: FieldTypes, resultsField: string) => { - return Object.keys(fieldTypes).map(field => { + return Object.keys(fieldTypes).map((field) => { // Built-in values are ['boolean', 'currency', 'datetime', 'numeric', 'json'] // To fall back to the default string schema it needs to be undefined. let schema; diff --git a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx index aeb774a224021..618075a77d906 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx +++ b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx @@ -52,7 +52,7 @@ function isWithHeader(arg: any): arg is PropsWithHeader { type Props = PropsWithHeader | PropsWithoutHeader; export const DataGrid: FC = memo( - props => { + (props) => { const { columns, dataTestSubj, @@ -75,7 +75,7 @@ export const DataGrid: FC = memo( useEffect(() => { if (invalidSortingColumnns.length > 0) { - invalidSortingColumnns.forEach(columnId => { + invalidSortingColumnns.forEach((columnId) => { toastNotifications.addDanger( i18n.translate('xpack.ml.dataGrid.invalidSortingColumnError', { defaultMessage: `The column '{columnId}' cannot be used for sorting.`, diff --git a/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts b/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts index c7c4f46031b6e..7843bf2ea801b 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts @@ -37,15 +37,15 @@ export const useDataGrid = ( const [pagination, setPagination] = useState(defaultPagination); const [sortingColumns, setSortingColumns] = useState([]); - const onChangeItemsPerPage: OnChangeItemsPerPage = useCallback(pageSize => { - setPagination(p => { + const onChangeItemsPerPage: OnChangeItemsPerPage = useCallback((pageSize) => { + setPagination((p) => { const pageIndex = Math.floor((p.pageSize * p.pageIndex) / pageSize); return { pageIndex, pageSize }; }); }, []); const onChangePage: OnChangePage = useCallback( - pageIndex => setPagination(p => ({ ...p, pageIndex })), + (pageIndex) => setPagination((p) => ({ ...p, pageIndex })), [] ); @@ -54,7 +54,7 @@ export const useDataGrid = ( // Column visibility const [visibleColumns, setVisibleColumns] = useState([]); - const columnIds = columns.map(c => c.id); + const columnIds = columns.map((c) => c.id); const filteredColumnIds = defaultVisibleColumnsFilter !== undefined ? columnIds.filter(defaultVisibleColumnsFilter) @@ -69,10 +69,10 @@ export const useDataGrid = ( const [invalidSortingColumnns, setInvalidSortingColumnns] = useState([]); const onSort: OnSort = useCallback( - sc => { + (sc) => { // Check if an unsupported column type for sorting was selected. const updatedInvalidSortingColumnns = sc.reduce((arr, current) => { - const columnType = columns.find(dgc => dgc.id === current.id); + const columnType = columns.find((dgc) => dgc.id === current.id); if (columnType?.schema === 'json') { arr.push(current.id); } diff --git a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js index fd19e6b2f06b6..5790b8bd239e0 100644 --- a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js +++ b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js @@ -28,8 +28,8 @@ export class DataRecognizer extends Component { componentDidMount() { // once the mount is complete, call the recognize endpoint to see if the index format is known to us, ml.recognizeIndex({ indexPatternTitle: this.indexPattern.title }) - .then(resp => { - const results = resp.map(r => ( + .then((resp) => { + const results = resp.map((r) => ( { + .catch((e) => { console.error('Error attempting to recognize index', e); }); } diff --git a/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js b/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js index 1044caa83e2ad..06978dc0aa736 100644 --- a/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js +++ b/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js @@ -103,7 +103,7 @@ Influencer.propTypes = { }; function InfluencersByName({ influencerFieldName, influencerFilter, fieldValues }) { - const influencerValues = fieldValues.map(valueData => ( + const influencerValues = fieldValues.map((valueData) => ( ( + const influencersByName = Object.keys(influencers).map((influencerFieldName) => ( = 0} - onChange={e => { + onChange={(e) => { setItemSelected(item, e.target.checked); }} /> diff --git a/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js b/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js index b76cb5d66a35f..8d170e76664b1 100644 --- a/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js +++ b/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js @@ -48,11 +48,11 @@ export class ItemsGridPagination extends Component { }); }; - onPageClick = pageNumber => { + onPageClick = (pageNumber) => { this.props.setActivePage(pageNumber); }; - onChangeItemsPerPage = pageSize => { + onChangeItemsPerPage = (pageSize) => { this.closePopover(); this.props.setItemsPerPage(pageSize); }; @@ -78,7 +78,7 @@ export class ItemsGridPagination extends Component { const pageCount = Math.ceil(itemCount / itemsPerPage); - const items = itemsPerPageOptions.map(pageSize => { + const items = itemsPerPageOptions.map((pageSize) => { return ( { + selectedIds.forEach((id) => { selectedIdsMap[id] = true; }); return selectedIdsMap; @@ -100,10 +100,10 @@ export function CustomSelectionTable({ function handleTableChange({ isSelected, itemId }) { const selectedMapIds = Object.getOwnPropertyNames(itemIdToSelectedMap); - const currentItemIds = currentItems.map(item => item.id); + const currentItemIds = currentItems.map((item) => item.id); let currentSelected = selectedMapIds.filter( - id => itemIdToSelectedMap[id] === true && id !== itemId + (id) => itemIdToSelectedMap[id] === true && id !== itemId ); if (itemId !== 'all') { @@ -113,7 +113,7 @@ export function CustomSelectionTable({ } else { if (isSelected === false) { // don't include any current items in the selection update since we're deselecting 'all' - currentSelected = currentSelected.filter(id => currentItemIds.includes(id) === false); + currentSelected = currentSelected.filter((id) => currentItemIds.includes(id) === false); } else { // grab all id's currentSelected = [...currentSelected, ...currentItemIds]; @@ -161,7 +161,7 @@ export function CustomSelectionTable({ } function areAllItemsSelected() { - const indexOfUnselectedItem = currentItems.findIndex(item => !isItemSelected(item.id)); + const indexOfUnselectedItem = currentItems.findIndex((item) => !isItemSelected(item.id)); return indexOfUnselectedItem === -1; } @@ -199,7 +199,7 @@ export function CustomSelectionTable({ function toggleAll() { const allSelected = areAllItemsSelected() || itemIdToSelectedMap.all === true; const newItemIdToSelectedMap = {}; - currentItems.forEach(item => (newItemIdToSelectedMap[item.id] = !allSelected)); + currentItems.forEach((item) => (newItemIdToSelectedMap[item.id] = !allSelected)); setItemIdToSelectedMap(newItemIdToSelectedMap); handleTableChange({ isSelected: !allSelected, itemId: 'all' }); } @@ -244,8 +244,8 @@ export function CustomSelectionTable({ } function renderRows() { - const renderRow = item => { - const cells = columns.map(column => { + const renderRow = (item) => { + const cells = columns.map((column) => { const cell = item[column.id]; let child; @@ -371,7 +371,7 @@ export function CustomSelectionTable({ itemsPerPageOptions={[10, JOBS_PER_PAGE, 50]} pageCount={pager.getTotalPages()} onChangeItemsPerPage={handleChangeItemsPerPage} - onChangePage={pageIndex => handlePageChange(pageIndex)} + onChangePage={(pageIndex) => handlePageChange(pageIndex)} /> )} diff --git a/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js b/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js index 1810896770c7a..8afe9aa06fb09 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js +++ b/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js @@ -38,7 +38,7 @@ export function IdBadges({ limit, maps, onLinkClick, selectedIds, showAllBarBadg if (maps.groupsMap[currentId] === undefined) { const jobGroups = maps.jobsMap[currentId] || []; - if (jobGroups.some(g => currentGroups.includes(g)) === false) { + if (jobGroups.some((g) => currentGroups.includes(g)) === false) { badges.push( diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts b/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts index 3a215f8cfb46d..3f3de405711c5 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts @@ -15,10 +15,10 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { const groups: Dictionary = {}; const groupsMap: Dictionary = {}; - jobs.forEach(job => { + jobs.forEach((job) => { // Organize job by group if (job.groups !== undefined) { - job.groups.forEach(g => { + job.groups.forEach((g) => { if (groups[g] === undefined) { groups[g] = { id: g, @@ -61,7 +61,7 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { } }); - Object.keys(groups).forEach(groupId => { + Object.keys(groups).forEach((groupId) => { const group = groups[groupId]; group.timeRange.widthPx = group.timeRange.toPx - group.timeRange.fromPx; group.timeRange.toMoment = moment(group.timeRange.to); @@ -78,13 +78,13 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { }); }); - return { groups: Object.keys(groups).map(g => groups[g]), groupsMap }; + return { groups: Object.keys(groups).map((g) => groups[g]), groupsMap }; } export function getTimeRangeFromSelection(jobs: MlJobWithTimeRange[], selection: string[]) { if (jobs.length > 0) { const times: number[] = []; - jobs.forEach(job => { + jobs.forEach((job) => { if (selection.includes(job.job_id)) { if (job.timeRange.from !== undefined) { times.push(job.timeRange.from); @@ -110,18 +110,15 @@ export function normalizeTimes( dateFormatTz: string, ganttBarWidth: number ) { - const jobsWithTimeRange = jobs.filter(job => { + const jobsWithTimeRange = jobs.filter((job) => { return job.timeRange.to !== undefined && job.timeRange.from !== undefined; }); - const min = Math.min(...jobsWithTimeRange.map(job => +job.timeRange.from)); - const max = Math.max(...jobsWithTimeRange.map(job => +job.timeRange.to)); - const ganttScale = d3.scale - .linear() - .domain([min, max]) - .range([1, ganttBarWidth]); + const min = Math.min(...jobsWithTimeRange.map((job) => +job.timeRange.from)); + const max = Math.max(...jobsWithTimeRange.map((job) => +job.timeRange.to)); + const ganttScale = d3.scale.linear().domain([min, max]).range([1, ganttBarWidth]); - jobs.forEach(job => { + jobs.forEach((job) => { if (job.timeRange.to !== undefined && job.timeRange.from !== undefined) { job.timeRange.fromPx = ganttScale(job.timeRange.from); job.timeRange.toPx = ganttScale(job.timeRange.to); diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx index f709c161bef17..6bdf2fdb7caa2 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx @@ -33,12 +33,12 @@ function mergeSelection( const selectedIds: string[] = []; const alreadySelected: string[] = []; - groupObjs.forEach(group => { + groupObjs.forEach((group) => { selectedIds.push(group.groupId); alreadySelected.push(...group.jobIds); }); - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { // Add jobId if not already included in group selection if (alreadySelected.includes(jobId) === false) { selectedIds.push(jobId); @@ -53,7 +53,7 @@ export function getInitialGroupsMap(selectedGroups: GroupObj[]): GroupsMap { const map: GroupsMap = {}; if (selectedGroups.length) { - selectedGroups.forEach(group => { + selectedGroups.forEach((group) => { map[group.groupId] = group.jobIds; }); } diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx index 66aa05d2aaa97..3fb654f35be4d 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx @@ -85,7 +85,7 @@ export const JobSelectorFlyout: FC = ({ const allNewSelection: string[] = []; const groupSelection: Array<{ groupId: string; jobIds: string[] }> = []; - newSelection.forEach(id => { + newSelection.forEach((id) => { if (jobGroupsMaps.groupsMap[id] !== undefined) { // Push all jobs from selected groups into the newSelection list allNewSelection.push(...jobGroupsMaps.groupsMap[id]); @@ -111,7 +111,7 @@ export const JobSelectorFlyout: FC = ({ } function removeId(id: string) { - setNewSelection(newSelection.filter(item => item !== id)); + setNewSelection(newSelection.filter((item) => item !== id)); } function toggleTimerangeSwitch() { diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js index c55e03776c09d..4eeef560dd6d1 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js @@ -38,12 +38,12 @@ export function JobSelectorTable({ sortablePropertyItems = [ { name: 'job_id', - getValue: item => item.job_id.toLowerCase(), + getValue: (item) => item.job_id.toLowerCase(), isAscending: true, }, { name: 'groups', - getValue: item => (item.groups && item.groups[0] ? item.groups[0].toLowerCase() : ''), + getValue: (item) => (item.groups && item.groups[0] ? item.groups[0].toLowerCase() : ''), isAscending: true, }, ]; @@ -52,7 +52,7 @@ export function JobSelectorTable({ sortablePropertyItems = [ { name: 'id', - getValue: item => item.id.toLowerCase(), + getValue: (item) => item.id.toLowerCase(), isAscending: true, }, ]; @@ -81,7 +81,7 @@ export function JobSelectorTable({ ]; function getGroupOptions() { - return groupsList.map(g => ({ + return groupsList.map((g) => ({ value: g.id, view: ( @@ -121,7 +121,9 @@ export function JobSelectorTable({ isSortable: true, alignment: LEFT_ALIGNMENT, render: ({ groups = [] }) => - groups.map(group => ), + groups.map((group) => ( + + )), }, { label: 'time range', @@ -154,7 +156,7 @@ export function JobSelectorTable({ filters={filters} filterDefaultFields={!singleSelection ? JOB_FILTER_FIELDS : undefined} items={jobs} - onTableChange={selectionFromTable => onSelection({ selectionFromTable })} + onTableChange={(selectionFromTable) => onSelection({ selectionFromTable })} selectedIds={selectedIds} singleSelection={singleSelection} sortableProperties={sortableProperties} @@ -200,7 +202,7 @@ export function JobSelectorTable({ columns={groupColumns} filterDefaultFields={!singleSelection ? GROUP_FILTER_FIELDS : undefined} items={groupsList} - onTableChange={selectionFromTable => onSelection({ selectionFromTable })} + onTableChange={(selectionFromTable) => onSelection({ selectionFromTable })} selectedIds={selectedIds} sortableProperties={sortableProperties} /> @@ -213,7 +215,7 @@ export function JobSelectorTable({ size="s" tabs={tabs} initialSelectedTab={tabs[0]} - onTabClick={tab => { + onTabClick={(tab) => { setCurrentTab(tab.id); }} /> diff --git a/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts b/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts index d3fad9ae6bc2c..74c238a0895ca 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts +++ b/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts @@ -19,8 +19,8 @@ import { getTimeRangeFromSelection } from './job_select_service_utils'; // check that the ids read from the url exist by comparing them to the // jobs loaded via mlJobsService. function getInvalidJobIds(jobs: MlJobWithTimeRange[], ids: string[]) { - return ids.filter(id => { - const jobExists = jobs.some(job => job.job_id === id); + return ids.filter((id) => { + const jobExists = jobs.some((job) => job.job_id === id); return jobExists === false && id !== '*'; }); } diff --git a/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx b/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx index edc6aece265f3..abaaf2cc3a185 100644 --- a/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx +++ b/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx @@ -27,7 +27,7 @@ interface RefreshInterval { } function getRecentlyUsedRangesFactory(timeHistory: TimeHistoryContract) { - return function(): Duration[] { + return function (): Duration[] { return ( timeHistory.get()?.map(({ from, to }: TimeRange) => { return { diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js b/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js index e6b1f55775608..ceb03b5f175ac 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js @@ -84,17 +84,17 @@ export class ConditionExpression extends Component { }); }; - changeAppliesTo = event => { + changeAppliesTo = (event) => { const { index, operator, value, updateCondition } = this.props; updateCondition(index, event.target.value, operator, value); }; - changeOperator = event => { + changeOperator = (event) => { const { index, appliesTo, value, updateCondition } = this.props; updateCondition(index, appliesTo, event.target.value, value); }; - changeValue = event => { + changeValue = (event) => { const { index, appliesTo, operator, updateCondition } = this.props; updateCondition(index, appliesTo, operator, +event.target.value); }; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js index f259a1f1ffb02..0f3b484402819 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js @@ -91,7 +91,7 @@ class RuleEditorFlyoutUI extends Component { } } - showFlyout = anomaly => { + showFlyout = (anomaly) => { let ruleIndex = -1; const job = mlJobService.getJob(anomaly.jobId); if (job === undefined) { @@ -144,13 +144,13 @@ class RuleEditorFlyoutUI extends Component { // Load the current list of filters. These are used for configuring rule scope. ml.filters .filters() - .then(filters => { - const filterListIds = filters.map(filter => filter.filter_id); + .then((filters) => { + const filterListIds = filters.map((filter) => filter.filter_id); this.setState({ filterListIds, }); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of filters:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -169,7 +169,7 @@ class RuleEditorFlyoutUI extends Component { this.setState({ isFlyoutVisible: false }); }; - setEditRuleIndex = ruleIndex => { + setEditRuleIndex = (ruleIndex) => { const detectorIndex = this.state.anomaly.detectorIndex; const detector = this.state.job.analysis_config.detectors[detectorIndex]; const rules = detector.custom_rules; @@ -182,7 +182,7 @@ class RuleEditorFlyoutUI extends Component { const isScopeEnabled = rule.scope !== undefined && Object.keys(rule.scope).length > 0; if (isScopeEnabled === true) { // Add 'enabled:true' to mark them as selected in the UI. - Object.keys(rule.scope).forEach(field => { + Object.keys(rule.scope).forEach((field) => { rule.scope[field].enabled = true; }); } @@ -195,9 +195,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onSkipResultChange = e => { + onSkipResultChange = (e) => { const checked = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const actions = [...prevState.rule.actions]; const idx = actions.indexOf(ACTION.SKIP_RESULT); if (idx === -1 && checked) { @@ -212,9 +212,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onSkipModelUpdateChange = e => { + onSkipModelUpdateChange = (e) => { const checked = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const actions = [...prevState.rule.actions]; const idx = actions.indexOf(ACTION.SKIP_MODEL_UPDATE); if (idx === -1 && checked) { @@ -229,9 +229,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onConditionsEnabledChange = e => { + onConditionsEnabledChange = (e) => { const isConditionsEnabled = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { let conditions; if (isConditionsEnabled === false) { // Clear any conditions that have been added. @@ -249,7 +249,7 @@ class RuleEditorFlyoutUI extends Component { }; addCondition = () => { - this.setState(prevState => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; conditions.push(getNewConditionDefaults()); @@ -260,7 +260,7 @@ class RuleEditorFlyoutUI extends Component { }; updateCondition = (index, appliesTo, operator, value) => { - this.setState(prevState => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; if (index < conditions.length) { conditions[index] = { @@ -276,8 +276,8 @@ class RuleEditorFlyoutUI extends Component { }); }; - deleteCondition = index => { - this.setState(prevState => { + deleteCondition = (index) => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; if (index < conditions.length) { conditions.splice(index, 1); @@ -289,9 +289,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onScopeEnabledChange = e => { + onScopeEnabledChange = (e) => { const isScopeEnabled = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const rule = { ...prevState.rule }; if (isScopeEnabled === false) { // Clear scope property. @@ -306,7 +306,7 @@ class RuleEditorFlyoutUI extends Component { }; updateScope = (fieldName, filterId, filterType, enabled) => { - this.setState(prevState => { + this.setState((prevState) => { let scope = { ...prevState.rule.scope }; if (scope === undefined) { scope = {}; @@ -338,7 +338,7 @@ class RuleEditorFlyoutUI extends Component { const detectorIndex = anomaly.detectorIndex; saveJobRule(job, detectorIndex, ruleIndex, editedRule) - .then(resp => { + .then((resp) => { if (resp.success) { toasts.add({ title: i18n.translate( @@ -370,7 +370,7 @@ class RuleEditorFlyoutUI extends Component { ); } }) - .catch(error => { + .catch((error) => { console.error(error); toasts.addDanger( i18n.translate( @@ -384,14 +384,14 @@ class RuleEditorFlyoutUI extends Component { }); }; - deleteRuleAtIndex = index => { + deleteRuleAtIndex = (index) => { const { toasts } = this.props.kibana.services.notifications; const { job, anomaly } = this.state; const jobId = job.job_id; const detectorIndex = anomaly.detectorIndex; deleteJobRule(job, detectorIndex, index) - .then(resp => { + .then((resp) => { if (resp.success) { toasts.addSuccess( i18n.translate( @@ -415,7 +415,7 @@ class RuleEditorFlyoutUI extends Component { ); } }) - .catch(error => { + .catch((error) => { console.error(error); let errorMessage = i18n.translate( 'xpack.ml.ruleEditor.ruleEditorFlyout.errorWithDeletingRuleFromJobDetectorNotificationMessage', @@ -456,7 +456,7 @@ class RuleEditorFlyoutUI extends Component { this.closeFlyout(); } }) - .catch(error => { + .catch((error) => { console.log(`Error adding ${item} to filter ${filterId}:`, error); toasts.addDanger( i18n.translate( diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js index 3e8a17eeb8617..79080ef0f9bb6 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js @@ -50,7 +50,7 @@ jest.mock('../../capabilities/check_capabilities', () => ({ })); jest.mock('../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js b/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js index d776ebb8c4cd5..a8c7ac0f6f598 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js @@ -29,7 +29,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; const POPOVER_STYLE = { zIndex: '200' }; function getFilterListOptions(filterListIds) { - return filterListIds.map(filterId => ({ value: filterId, text: filterId })); + return filterListIds.map((filterId) => ({ value: filterId, text: filterId })); } export class ScopeExpression extends Component { @@ -53,19 +53,19 @@ export class ScopeExpression extends Component { }); }; - onChangeFilterType = event => { + onChangeFilterType = (event) => { const { fieldName, filterId, enabled, updateScope } = this.props; updateScope(fieldName, filterId, event.target.value, enabled); }; - onChangeFilterId = event => { + onChangeFilterId = (event) => { const { fieldName, filterType, enabled, updateScope } = this.props; updateScope(fieldName, event.target.value, filterType, enabled); }; - onEnableChange = event => { + onEnableChange = (event) => { const { fieldName, filterId, filterType, updateScope } = this.props; updateScope(fieldName, filterId, filterType, event.target.checked); @@ -131,7 +131,7 @@ export class ScopeExpression extends Component { } value={fieldName} isActive={false} - onClick={event => event.preventDefault()} + onClick={(event) => event.preventDefault()} /> diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js index 189fb6a35d3e6..839dcee870983 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js @@ -12,7 +12,7 @@ jest.mock('../../services/job_service.js', () => 'mlJobService'); // with 'mock' so it can be used lazily. const mockCheckPermission = jest.fn(() => true); jest.mock('../../capabilities/check_capabilities', () => ({ - checkPermission: privilege => mockCheckPermission(privilege), + checkPermission: (privilege) => mockCheckPermission(privilege), })); import { shallowWithIntl } from 'test_utils/enzyme_helpers'; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js index 07ca459949947..612cebff60d02 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js @@ -52,7 +52,7 @@ export class EditConditionLink extends Component { this.state = { value }; } - onChangeValue = event => { + onChangeValue = (event) => { const enteredValue = event.target.value; this.setState({ value: enteredValue !== '' ? +enteredValue : '', diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js index ec966ec8bcded..c8071d2629eeb 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js @@ -57,13 +57,13 @@ export class RuleActionPanel extends Component { const filterId = scope[partitionFieldName].filter_id; ml.filters .filters({ filterId }) - .then(filter => { + .then((filter) => { const filterItems = filter.items; if (filterItems.indexOf(partitionFieldValue[0]) === -1) { this.setState({ showAddToFilterListLink: true }); } }) - .catch(resp => { + .catch((resp) => { console.log(`Error loading filter ${filterId}:`, resp); }); } diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js index f8787100d6b95..a697eed00fd66 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js @@ -60,7 +60,7 @@ export function isValidRule(rule) { } else { const scope = rule.scope; if (scope !== undefined) { - isValid = Object.keys(scope).some(field => scope[field].enabled === true); + isValid = Object.keys(scope).some((field) => scope[field].enabled === true); } } } @@ -76,7 +76,7 @@ export function saveJobRule(job, detectorIndex, ruleIndex, editedRule) { const clonedRule = cloneDeep(editedRule); const scope = clonedRule.scope; if (scope !== undefined) { - Object.keys(scope).forEach(field => { + Object.keys(scope).forEach((field) => { if (scope[field].enabled === false) { delete scope[field]; } else { @@ -148,7 +148,7 @@ export function updateJobRules(job, detectorIndex, rules) { return new Promise((resolve, reject) => { mlJobService .updateJob(jobId, jobData) - .then(resp => { + .then((resp) => { if (resp.success) { // Refresh the job data in the job service before resolving. mlJobService @@ -156,14 +156,14 @@ export function updateJobRules(job, detectorIndex, rules) { .then(() => { resolve({ success: true }); }) - .catch(refreshResp => { + .catch((refreshResp) => { reject(refreshResp); }); } else { reject(resp); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -175,10 +175,10 @@ export function addItemToFilter(item, filterId) { return new Promise((resolve, reject) => { ml.filters .updateFilter(filterId, undefined, [item], undefined) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); }); diff --git a/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx b/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx index 4ad1139bc9b52..0bd33a8c99f49 100644 --- a/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx +++ b/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx @@ -32,7 +32,7 @@ interface StatsBarProps { } export const StatsBar: FC = ({ stats, dataTestSub }) => { - const statsList = Object.keys(stats).map(k => stats[k as StatsKey]); + const statsList = Object.keys(stats).map((k) => stats[k as StatsKey]); return (
{statsList diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js index 6001d7cbf6f61..dde6925631d3e 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js @@ -47,7 +47,7 @@ const getDefaultState = () => ({ title: '', }); -const statusToEuiColor = status => { +const statusToEuiColor = (status) => { switch (status) { case VALIDATION_STATUS.INFO: return 'primary'; @@ -60,7 +60,7 @@ const statusToEuiColor = status => { } }; -const statusToEuiIconType = status => { +const statusToEuiIconType = (status) => { switch (status) { case VALIDATION_STATUS.INFO: return 'iInCircle'; @@ -104,7 +104,7 @@ Message.propTypes = { const MessageList = ({ messages, idFilterList }) => { const callouts = messages - .filter(m => idFilterList.includes(m.id) === false) + .filter((m) => idFilterList.includes(m.id) === false) .map((m, i) => ); // there could be no error or success messages due to the @@ -209,7 +209,7 @@ export class ValidateJob extends Component { if (typeof job === 'object') { let shouldShowLoadingIndicator = true; - this.props.mlJobService.validateJob({ duration, fields, job }).then(data => { + this.props.mlJobService.validateJob({ duration, fields, job }).then((data) => { shouldShowLoadingIndicator = false; this.setState({ ...this.state, @@ -224,7 +224,7 @@ export class ValidateJob extends Component { }); if (typeof this.props.setIsValid === 'function') { this.props.setIsValid( - data.messages.some(m => m.status === VALIDATION_STATUS.ERROR) === false + data.messages.some((m) => m.status === VALIDATION_STATUS.ERROR) === false ); } }); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts index 7501fe3d82fc6..7633e07e8f3dc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts @@ -343,7 +343,7 @@ export const useRefreshAnalyticsList = ( subscriptions.push( distinct$ - .pipe(filter(state => state === REFRESH_ANALYTICS_LIST_STATE.REFRESH)) + .pipe(filter((state) => state === REFRESH_ANALYTICS_LIST_STATE.REFRESH)) .subscribe(() => typeof callback.onRefresh === 'function' && callback.onRefresh()) ); } @@ -351,7 +351,7 @@ export const useRefreshAnalyticsList = ( if (typeof callback.isLoading === 'function') { subscriptions.push( distinct$.subscribe( - state => + (state) => typeof callback.isLoading === 'function' && callback.isLoading(state === REFRESH_ANALYTICS_LIST_STATE.LOADING) ) @@ -359,7 +359,7 @@ export const useRefreshAnalyticsList = ( } return () => { - subscriptions.map(sub => sub.unsubscribe()); + subscriptions.map((sub) => sub.unsubscribe()); }; }, []); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts index 8423bc1b94a09..8db349b395cfc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts @@ -51,7 +51,7 @@ export const ML__ID_COPY = 'ml__id_copy'; export const isKeywordAndTextType = (fieldName: string): boolean => { const { fields } = newJobCapsService; - const fieldType = fields.find(field => field.name === fieldName)?.type; + const fieldType = fields.find((field) => field.name === fieldName)?.type; let isBothTypes = false; // If it's a keyword type - check if it has a corresponding text type @@ -192,8 +192,8 @@ export const getDefaultFieldsFromJobCaps = ( featureInfluenceFields.push( ...fields - .filter(d => !jobConfig.analyzed_fields.excludes.includes(d.id)) - .map(d => ({ + .filter((d) => !jobConfig.analyzed_fields.excludes.includes(d.id)) + .map((d) => ({ id: `${resultsField}.${FEATURE_INFLUENCE}.${d.id}`, name: `${resultsField}.${FEATURE_INFLUENCE}.${d.name}`, type: KBN_FIELD_TYPES.NUMBER, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index 87b8c15aeaa78..eb38a23d10eef 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -34,7 +34,7 @@ export const getIndexData = async ( try { const sort: EsSorting = sortingColumns - .map(column => { + .map((column) => { const { id } = column; column.id = isKeywordAndTextType(id) ? `${id}.keyword` : id; return column; @@ -57,7 +57,7 @@ export const getIndexData = async ( setRowCount(resp.hits.total.value); - const docs = resp.hits.hits.map(d => d._source); + const docs = resp.hits.hits.map((d) => d._source); setTableItems(docs); setStatus(INDEX_STATUS.LOADED); } catch (e) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts index 12ae4a586e949..9aacf216dd2a5 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts @@ -29,13 +29,13 @@ export const getIndexFields = ( const types: FieldTypes = {}; const allFields: string[] = []; - docFields.forEach(field => { + docFields.forEach((field) => { types[field.id] = field.type; allFields.push(field.id); }); return { - defaultSelectedFields: defaultSelected.map(field => field.id), + defaultSelectedFields: defaultSelected.map((field) => field.id), fieldTypes: types, tableFields: allFields, }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts index 0bc9e78207596..2570dd20416be 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts @@ -34,7 +34,7 @@ export const useResultsViewConfig = (jobId: string) => { // get analytics configuration, index pattern and field caps useEffect(() => { - (async function() { + (async function () { setIsLoadingJobConfig(false); try { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx index 14493ab024f34..64fdf161b5615 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx @@ -36,7 +36,7 @@ export function getColumnData(confusionMatrixData: ConfusionMatrix[]) { let showOther = false; - confusionMatrixData.forEach(classData => { + confusionMatrixData.forEach((classData) => { const otherCount = classData.other_predicted_class_doc_count; if (otherCount > 0) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts index e664a1ddbdbcc..e391b90e6eb96 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts @@ -48,7 +48,7 @@ export const useExplorationResults = ( // reduce default selected rows from 20 to 8 for performance reasons. 8, // by default, hide feature-importance columns and the doc id copy - d => !d.includes(`.${FEATURE_IMPORTANCE}.`) && d !== ML__ID_COPY + (d) => !d.includes(`.${FEATURE_IMPORTANCE}.`) && d !== ML__ID_COPY ); useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts index bfd3dd33995aa..3746fa12bdc1e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts @@ -17,7 +17,7 @@ export const getFeatureCount = (resultsField: string, tableItems: DataGridItem[] return 0; } - return Object.keys(tableItems[0]).filter(key => + return Object.keys(tableItems[0]).filter((key) => key.includes(`${resultsField}.${FEATURE_INFLUENCE}.`) ).length; }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts index 75b2f6aa867df..ebac6ccb2298e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts @@ -55,7 +55,7 @@ export const useOutlierData = ( // reduce default selected rows from 20 to 8 for performance reasons. 8, // by default, hide feature-influence columns and the doc id copy - d => !d.includes(`.${FEATURE_INFLUENCE}.`) && d !== ML__ID_COPY + (d) => !d.includes(`.${FEATURE_INFLUENCE}.`) && d !== ML__ID_COPY ); useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx index 3e5224b76329e..2ef1515726d1b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx @@ -26,7 +26,7 @@ describe('DeleteAction', () => { test('When canDeleteDataFrameAnalytics permission is true, button should not be disabled.', () => { const mock = jest.spyOn(CheckPrivilige, 'checkPermission'); - mock.mockImplementation(p => p === 'canDeleteDataFrameAnalytics'); + mock.mockImplementation((p) => p === 'canDeleteDataFrameAnalytics'); const { getByTestId } = render(); expect(getByTestId('mlAnalyticsJobDeleteButton')).not.toHaveAttribute('disabled'); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx index 68e728c019873..4a99c042b108b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx @@ -59,7 +59,7 @@ function getItemIdToExpandedRowMap( dataFrameAnalytics: DataFrameAnalyticsListRow[] ): ItemIdToExpandedRowMap { return itemIds.reduce((m: ItemIdToExpandedRowMap, analyticsId: DataFrameAnalyticsId) => { - const item = dataFrameAnalytics.find(analytics => analytics.config.id === analyticsId); + const item = dataFrameAnalytics.find((analytics) => analytics.config.id === analyticsId); if (item !== undefined) { m[analyticsId] = ; } @@ -176,7 +176,7 @@ export const DataFrameAnalyticsList: FC = ({ return p; }, {}); - clauses.forEach(c => { + clauses.forEach((c) => { // the search term could be negated with a minus, e.g. -bananas const bool = c.match === 'must'; let ts: DataFrameAnalyticsListRow[]; @@ -187,12 +187,12 @@ export const DataFrameAnalyticsList: FC = ({ // if the term has been negated, AND the matches if (bool === true) { ts = analytics.filter( - d => stringMatch(d.id, c.value) === bool // || + (d) => stringMatch(d.id, c.value) === bool // || // stringMatch(d.config.description, c.value) === bool ); } else { ts = analytics.filter( - d => stringMatch(d.id, c.value) === bool // && + (d) => stringMatch(d.id, c.value) === bool // && // stringMatch(d.config.description, c.value) === bool ); } @@ -200,25 +200,25 @@ export const DataFrameAnalyticsList: FC = ({ // filter other clauses, i.e. the mode and status filters if (Array.isArray(c.value)) { if (c.field === 'job_type') { - ts = analytics.filter(d => + ts = analytics.filter((d) => (c.value as string).includes(getAnalysisType(d.config.analysis)) ); } else { // the status value is an array of string(s) e.g. ['failed', 'stopped'] - ts = analytics.filter(d => (c.value as string).includes(d.stats.state)); + ts = analytics.filter((d) => (c.value as string).includes(d.stats.state)); } } else { - ts = analytics.filter(d => d.mode === c.value); + ts = analytics.filter((d) => d.mode === c.value); } } - ts.forEach(t => matches[t.id].count++); + ts.forEach((t) => matches[t.id].count++); }); // loop through the matches and return only analytics which have match all the clauses const filtered = Object.values(matches) - .filter(m => (m && m.count) >= clauses.length) - .map(m => m.analytics); + .filter((m) => (m && m.count) >= clauses.length) + .map((m) => m.analytics); let pageStart = pageIndex * pageSize; if (pageStart >= filtered.length && filtered.length !== 0) { @@ -330,7 +330,7 @@ export const DataFrameAnalyticsList: FC = ({ defaultMessage: 'Type', }), multiSelect: 'or', - options: Object.values(ANALYSIS_CONFIG_TYPE).map(val => ({ + options: Object.values(ANALYSIS_CONFIG_TYPE).map((val) => ({ value: val, name: val, view: getJobTypeBadge(val), @@ -343,7 +343,7 @@ export const DataFrameAnalyticsList: FC = ({ defaultMessage: 'Status', }), multiSelect: 'or', - options: Object.values(DATA_FRAME_TASK_STATE).map(val => ({ + options: Object.values(DATA_FRAME_TASK_STATE).map((val) => ({ value: val, name: val, view: getTaskStateBadge(val), @@ -426,7 +426,7 @@ export const DataFrameAnalyticsList: FC = ({ sorting={sorting} search={search} data-test-subj={isLoading ? 'mlAnalyticsTable loading' : 'mlAnalyticsTable loaded'} - rowProps={item => ({ + rowProps={(item) => ({ 'data-test-subj': `mlAnalyticsTableRow row-${item.id}`, })} /> diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx index 94dc7ec87cc61..0ee57fe5be141 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx @@ -186,7 +186,7 @@ export const ExpandedRow: FC = ({ item }) => { ), description: `${currentPhase}/${totalPhases}`, }, - ...item.stats.progress.map(s => { + ...item.stats.progress.map((s) => { return { title: s.phase, description: , diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx index 32b2ca3472018..71ca2b6f60492 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx @@ -53,8 +53,8 @@ export const ExpandedRowDetailsPane: FC = ({ sectio {sections - .filter(s => s.position === 'left') - .map(s => ( + .filter((s) => s.position === 'left') + .map((s) => (
@@ -63,8 +63,8 @@ export const ExpandedRowDetailsPane: FC = ({ sectio {sections - .filter(s => s.position === 'right') - .map(s => ( + .filter((s) => s.position === 'right') + .map((s) => (
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx index cef03cc0d0c76..48eb95948bb12 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx @@ -101,7 +101,7 @@ export const CreateAnalyticsAdvancedEditor: FC = ({ ac ]} > { + inputRef={(input) => { if (input) { forceInput.current = input; } @@ -109,7 +109,7 @@ export const CreateAnalyticsAdvancedEditor: FC = ({ ac disabled={isJobCreated} placeholder="analytics job ID" value={jobId} - onChange={e => setFormState({ jobId: e.target.value })} + onChange={(e) => setFormState({ jobId: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.advancedEditor.jobIdInputAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx index 3c8c3c3b3aa55..952bd48468b0a 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { createPermissionFailureMessage } from '../../../../../capabilities/check_capabilities'; import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -export const CreateAnalyticsButton: FC = props => { +export const CreateAnalyticsButton: FC = (props) => { const { disabled } = props.state; const { openModal } = props.actions; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx index 8716f84be3d34..2f3c38b6ffe4e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx @@ -12,7 +12,7 @@ import { CreateAnalyticsAdvancedEditor } from '../create_analytics_advanced_edit import { CreateAnalyticsForm } from '../create_analytics_form'; import { CreateAnalyticsFlyout } from '../create_analytics_flyout'; -export const CreateAnalyticsFlyoutWrapper: FC = props => { +export const CreateAnalyticsFlyoutWrapper: FC = (props) => { const { isAdvancedEditorEnabled, isModalVisible } = props.state; if (isModalVisible === false) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx index 11052b171845d..64fe736e67b17 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx @@ -465,7 +465,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta ]} > { + inputRef={(input) => { if (input) { forceInput.current = input; } @@ -475,7 +475,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta defaultMessage: 'Job ID', })} value={jobId} - onChange={e => setFormState({ jobId: e.target.value })} + onChange={(e) => setFormState({ jobId: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.jobIdInputAriaLabel', { @@ -579,7 +579,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta disabled={isJobCreated} placeholder="destination index" value={destinationIndex} - onChange={e => setFormState({ destinationIndex: e.target.value })} + onChange={(e) => setFormState({ destinationIndex: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.destinationIndexInputAriaLabel', { @@ -667,7 +667,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta singleSelection={true} options={dependentVariableOptions} selectedOptions={dependentVariable ? [{ label: dependentVariable }] : []} - onChange={selectedOptions => + onChange={(selectedOptions) => setFormState({ dependentVariable: selectedOptions[0].label || '', }) @@ -691,7 +691,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta showValue value={trainingPercent} // @ts-ignore Property 'value' does not exist on type 'EventTarget' | (EventTarget & HTMLInputElement) - onChange={e => setFormState({ trainingPercent: +e.target.value })} + onChange={(e) => setFormState({ trainingPercent: +e.target.value })} data-test-subj="mlAnalyticsCreateJobFlyoutTrainingPercentSlider" /> @@ -738,7 +738,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta disabled={false} isInvalid={numTopFeatureImportanceValuesValid === false} min={NUM_TOP_FEATURE_IMPORTANCE_VALUES_MIN} - onChange={e => setFormState({ numTopFeatureImportanceValues: +e.target.value })} + onChange={(e) => setFormState({ numTopFeatureImportanceValues: +e.target.value })} step={1} value={numTopFeatureImportanceValues} /> @@ -790,12 +790,12 @@ export const CreateAnalyticsForm: FC = ({ actions, sta isDisabled={isJobCreated} isLoading={loadingFieldOptions} options={excludesOptions} - selectedOptions={excludes.map(field => ({ + selectedOptions={excludes.map((field) => ({ label: field, }))} onCreateOption={onCreateOption} - onChange={selectedOptions => - setFormState({ excludes: selectedOptions.map(option => option.label) }) + onChange={(selectedOptions) => + setFormState({ excludes: selectedOptions.map((option) => option.label) }) } isClearable={true} data-test-subj="mlAnalyticsCreateJobFlyoutExcludesSelect" @@ -816,7 +816,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta } disabled={isJobCreated} value={modelMemoryLimit || ''} - onChange={e => setFormState({ modelMemoryLimit: e.target.value })} + onChange={(e) => setFormState({ modelMemoryLimit: e.target.value })} isInvalid={modelMemoryLimitValidationResult !== null} data-test-subj="mlAnalyticsCreateJobFlyoutModelMemoryInput" /> diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx index 58f3129280c09..46301a6f832e7 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx @@ -27,7 +27,7 @@ export const JobDescriptionInput: FC = ({ description, setFormState }) => value={description} placeholder={helpText} rows={2} - onChange={e => { + onChange={(e) => { const value = e.target.value; setFormState({ description: value }); }} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx index 210f2c2dbedf1..6daa72dd805b1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx @@ -57,13 +57,13 @@ export const JobType: FC = ({ type, setFormState }) => { helpText={type !== undefined ? helpText[type] : ''} > ({ + options={Object.values(ANALYSIS_CONFIG_TYPE).map((jobType) => ({ value: jobType, text: jobType.replace(/_/g, ' '), }))} value={type} hasNoInitialSelection={true} - onChange={e => { + onChange={(e) => { const value = e.target.value as AnalyticsJobType; setFormState({ previousJobType: type, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts index 1cab42d8ee12d..a79a8fcf61ed4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts @@ -144,7 +144,7 @@ export const validateAdvancedEditor = (state: State): State => { sourceIndexNameValid = !sourceIndex.includes(','); } if (Array.isArray(sourceIndex)) { - sourceIndexNameValid = !sourceIndex.some(d => d?.includes(',')); + sourceIndexNameValid = !sourceIndex.some((d) => d?.includes(',')); } } @@ -479,7 +479,7 @@ export function reducer(state: State, action: Action): State { // update state attributes which are derived from other state attributes. if (action.payload.destinationIndex !== undefined) { newFormState.destinationIndexNameExists = state.indexNames.some( - name => newFormState.destinationIndex === name + (name) => newFormState.destinationIndex === name ); newFormState.destinationIndexNameEmpty = newFormState.destinationIndex === ''; newFormState.destinationIndexNameValid = isValidIndexName(newFormState.destinationIndex); @@ -488,7 +488,7 @@ export function reducer(state: State, action: Action): State { } if (action.payload.jobId !== undefined) { - newFormState.jobIdExists = state.jobIds.some(id => newFormState.jobId === id); + newFormState.jobIdExists = state.jobIds.some((id) => newFormState.jobId === id); newFormState.jobIdEmpty = newFormState.jobId === ''; newFormState.jobIdValid = isJobIdValid(newFormState.jobId); newFormState.jobIdInvalidMaxLength = !!maxLengthValidator(JOB_ID_MAX_LENGTH)( @@ -515,7 +515,7 @@ export function reducer(state: State, action: Action): State { case ACTION.SET_INDEX_NAMES: { const newState = { ...state, indexNames: action.indexNames }; newState.form.destinationIndexNameExists = newState.indexNames.some( - name => newState.form.destinationIndex === name + (name) => newState.form.destinationIndex === name ); return newState; } @@ -547,7 +547,7 @@ export function reducer(state: State, action: Action): State { case ACTION.SET_JOB_IDS: { const newState = { ...state, jobIds: action.jobIds }; - newState.form.jobIdExists = newState.jobIds.some(id => newState.form.jobId === id); + newState.form.jobIdExists = newState.jobIds.some((id) => newState.form.jobId === id); return newState; } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts index 8ca985a537b6e..4ff7deab34f26 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts @@ -220,7 +220,7 @@ export const getJobConfigFromFormState = ( // the into an array of indices to be in the correct format for // the data frame analytics API. index: formState.sourceIndex.includes(',') - ? formState.sourceIndex.split(',').map(d => d.trim()) + ? formState.sourceIndex.split(',').map((d) => d.trim()) : formState.sourceIndex, }, dest: { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts index 2478dbf7cf63d..1ec767d014a2e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts @@ -214,7 +214,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } try { - setIndexNames((await ml.getIndices()).map(index => index.name)); + setIndexNames((await ml.getIndices()).map((index) => index.name)); } catch (e) { addRequestMessage({ error: getErrorMessage(e), diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts index df58f225e62de..964e8e4062b38 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts @@ -125,7 +125,7 @@ export const getAnalyticsFactory = ( const tableRows = analyticsConfigs.data_frame_analytics.reduce( (reducedtableRows, config) => { const stats = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) - ? analyticsStats.data_frame_analytics.find(d => config.id === d.id) + ? analyticsStats.data_frame_analytics.find((d) => config.id === d.id) : undefined; // A newly created analytics job might not have corresponding stats yet. diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx index 2bddf0de0499d..8aef8d456e75f 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx @@ -47,7 +47,7 @@ export const AboutPanel: FC = ({ onFilePickerChange }) => { defaultMessage: 'Select or drag and drop a file', } )} - onChange={files => onFilePickerChange(files)} + onChange={(files) => onFilePickerChange(files)} className="file-datavisualizer-file-picker" />
diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js index 253ec0ba4d028..1f0115a7ee9d2 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js @@ -36,13 +36,13 @@ export class EditFlyout extends Component { this.props.closeEditFlyout(); }; - setApplyOverrides = applyOverrides => { + setApplyOverrides = (applyOverrides) => { this.applyOverrides = applyOverrides; }; unsetApplyOverrides = () => { this.applyOverrides = () => {}; }; - setOverridesValid = overridesValid => { + setOverridesValid = (overridesValid) => { this.setState({ overridesValid }); }; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js index 503f26a9e978f..7728e96d6fc64 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js @@ -13,7 +13,7 @@ import { } from './option_lists'; function getOptions(list) { - return list.map(o => ({ label: o })); + return list.map((o) => ({ label: o })); } export function getFormatOptions() { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js index c84e456b206cd..bbbc33052f3c7 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js @@ -130,7 +130,7 @@ class OverridesUI extends Component { } if (originalTimestampFormat !== undefined) { - const optionExists = TIMESTAMP_OPTIONS.some(option => option === originalTimestampFormat); + const optionExists = TIMESTAMP_OPTIONS.some((option) => option === originalTimestampFormat); if (optionExists === false) { // Incoming format does not exist in dropdown. Display custom input with incoming format as default value. const overrides = { ...this.state.overrides }; @@ -177,7 +177,7 @@ class OverridesUI extends Component { } }; - onCustomTimestampFormatChange = e => { + onCustomTimestampFormatChange = (e) => { this.setState({ customTimestampFormat: e.target.value }); // check whether the value is valid and set that to state. const { isValid, errorMessage } = isTimestampFormatValid(e.target.value); @@ -195,7 +195,7 @@ class OverridesUI extends Component { this.setOverride({ delimiter }); }; - onCustomDelimiterChange = e => { + onCustomDelimiterChange = (e) => { this.setState({ customDelimiter: e.target.value }); }; @@ -204,11 +204,11 @@ class OverridesUI extends Component { this.setOverride({ quote }); }; - onHasHeaderRowChange = e => { + onHasHeaderRowChange = (e) => { this.setOverride({ hasHeaderRow: e.target.checked }); }; - onShouldTrimFieldsChange = e => { + onShouldTrimFieldsChange = (e) => { this.setOverride({ shouldTrimFields: e.target.checked }); }; @@ -223,11 +223,11 @@ class OverridesUI extends Component { this.setOverride({ columnNames }); }; - grokPatternChange = e => { + grokPatternChange = (e) => { this.setOverride({ grokPattern: e.target.value }); }; - onLinesToSampleChange = e => { + onLinesToSampleChange = (e) => { const linesToSample = +e.target.value; this.setOverride({ linesToSample }); @@ -493,7 +493,7 @@ class OverridesUI extends Component { this.onColumnNameChange(e, i)} + onChange={(e) => this.onColumnNameChange(e, i)} /> ))} @@ -514,7 +514,7 @@ function selectedOption(opt) { // also sort alphanumerically function getSortedFields(fields) { return fields - .map(f => ({ label: f })) + .map((f) => ({ label: f })) .sort((a, b) => a.label.localeCompare(b.label, undefined, { numeric: true })); } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js index 0257e69053d33..1a2bc20a5192a 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js @@ -10,7 +10,7 @@ import React from 'react'; import { Overrides } from './overrides'; jest.mock('../../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js index 5dfae43f223b1..9e83f72d7a07b 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js @@ -31,7 +31,7 @@ export class FieldsStats extends Component { return (
- {this.state.fields.map(f => ( + {this.state.fields.map((f) => ( @@ -53,7 +53,7 @@ function createFields(results) { if (mappings && fieldStats) { const fieldNames = getFieldNames(results); - return fieldNames.map(name => { + return fieldNames.map((name) => { if (fieldStats[name] !== undefined) { const field = { name }; const f = fieldStats[name]; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx index 6564b9a1f4d83..ee73b20051427 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx @@ -60,8 +60,5 @@ export const FileContents: FC = ({ data, format, numberOfLines }) => { }; function limitByNumberOfLines(data: string, numberOfLines: number) { - return data - .split('\n') - .slice(0, numberOfLines) - .join('\n'); + return data.split('\n').slice(0, numberOfLines).join('\n'); } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js index c73ab4b9e11c7..7cb545cd5a776 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js @@ -67,7 +67,7 @@ export class FileDataVisualizerView extends Component { this.setState({ hasPermissionToImport }); } - onFilePickerChange = files => { + onFilePickerChange = (files) => { this.overrides = {}; this.setState( @@ -147,8 +147,8 @@ export class FileDataVisualizerView extends Component { // if no overrides were used, store all the settings returned from the endpoint this.originalSettings = serverSettings; } else { - Object.keys(serverOverrides).forEach(o => { - const camelCaseO = o.replace(/_\w/g, m => m[1].toUpperCase()); + Object.keys(serverOverrides).forEach((o) => { + const camelCaseO = o.replace(/_\w/g, (m) => m[1].toUpperCase()); this.overrides[camelCaseO] = serverOverrides[o]; }); @@ -156,7 +156,7 @@ export class FileDataVisualizerView extends Component { // e.g. changing the name of the time field which is also the time field // will cause the timestamp_field setting to change. // if any have changed, update the originalSettings value - Object.keys(serverSettings).forEach(o => { + Object.keys(serverSettings).forEach((o) => { const value = serverSettings[o]; if ( this.overrides[o] === undefined && @@ -225,7 +225,7 @@ export class FileDataVisualizerView extends Component { this.setState({ bottomBarVisible: false }); }; - setOverrides = overrides => { + setOverrides = (overrides) => { console.log('setOverrides', overrides); this.setState( { @@ -239,7 +239,7 @@ export class FileDataVisualizerView extends Component { ); }; - changeMode = mode => { + changeMode = (mode) => { this.setState({ mode }); }; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx index 32b51c8b7d4ee..07f2825687515 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx @@ -56,7 +56,7 @@ export const FilebeatConfigFlyout: FC = ({ useEffect(() => { if (security !== undefined) { - security.authc.getCurrentUser().then(user => { + security.authc.getCurrentUser().then((user) => { setUsername(user.username === undefined ? null : user.username); }); } @@ -86,7 +86,7 @@ export const FilebeatConfigFlyout: FC = ({ - {copy => ( + {(copy) => ( { + onConfigModeChange = (configMode) => { this.setState({ configMode, }); }; - onIndexChange = e => { + onIndexChange = (e) => { const name = e.target.value; const { indexNames, indexPattern, indexPatternNames } = this.state; @@ -341,7 +341,7 @@ export class ImportView extends Component { }); }; - onIndexPatternChange = e => { + onIndexPatternChange = (e) => { const name = e.target.value; const { indexPatternNames, index } = this.state; this.setState({ @@ -350,37 +350,37 @@ export class ImportView extends Component { }); }; - onCreateIndexPatternChange = e => { + onCreateIndexPatternChange = (e) => { this.setState({ createIndexPattern: e.target.checked, }); }; - onIndexSettingsStringChange = text => { + onIndexSettingsStringChange = (text) => { this.setState({ indexSettingsString: text, }); }; - onMappingsStringChange = text => { + onMappingsStringChange = (text) => { this.setState({ mappingsString: text, }); }; - onPipelineStringChange = text => { + onPipelineStringChange = (text) => { this.setState({ pipelineString: text, }); }; - setImportProgress = progress => { + setImportProgress = (progress) => { this.setState({ uploadProgress: progress, }); }; - setReadProgress = progress => { + setReadProgress = (progress) => { this.setState({ readProgress: progress, }); @@ -398,7 +398,7 @@ export class ImportView extends Component { async loadIndexNames() { const indices = await ml.getIndices(); - const indexNames = indices.map(i => i.name); + const indexNames = indices.map((i) => i.name); this.setState({ indexNames }); } @@ -656,7 +656,7 @@ function getDefaultState(state, results) { } function isIndexNameValid(name, indexNames) { - if (indexNames.find(i => i === name)) { + if (indexNames.find((i) => i === name)) { return ( i === name)) { + if (indexPatternNames.find((i) => i === name)) { return ( `_${$1.toLowerCase()}`); + const snakeCaseO = o.replace(/([A-Z])/g, ($1) => `_${$1.toLowerCase()}`); formattedOverrides[snakeCaseO] = value; } } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx index e2c156fc66ded..e2fb8ae5547cc 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx @@ -145,7 +145,7 @@ export const NumberContent: FC = ({ config }) => { setDetailsMode(optionId as DETAILS_MODE)} + onChange={(optionId) => setDetailsMode(optionId as DETAILS_MODE)} aria-label={i18n.translate( 'xpack.ml.fieldDataCard.cardNumber.selectMetricDetailsDisplayAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx index cf0e3ec1a9c9b..4189308a3bc99 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx @@ -59,7 +59,7 @@ export const MetricDistributionChart: FC = ({ width, height, chartData, f const headerFormatter: TooltipValueFormatter = (tooltipData: ChartTooltipValue) => { const xValue = tooltipData.value; const chartPoint: MetricDistributionChartData | undefined = chartData.find( - data => data.x === xValue + (data) => data.x === xValue ); return ( @@ -97,9 +97,9 @@ export const MetricDistributionChart: FC = ({ width, height, chartData, f kibanaFieldFormat(d, fieldFormat)} + tickFormat={(d) => kibanaFieldFormat(d, fieldFormat)} /> - d.toFixed(3)} hide={true} /> + d.toFixed(3)} hide={true} /> data.y); + let barHeights = processedData.map((data) => data.y); barHeights = barHeights.sort((a, b) => a - b); let maxBarHeight = 0; @@ -131,12 +131,12 @@ export function buildChartDataFromStats( 2; } - processedData.forEach(data => { + processedData.forEach((data) => { data.y = Math.min(data.y, maxBarHeight); }); // Convert the data to the format used by the chart. - chartData = processedData.map(data => { + chartData = processedData.map((data) => { const { x0, y, dataMin, dataMax, percent } = data; return { x: x0, y, dataMin, dataMax, percent }; }); diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx index 6fd08076e1f46..24081f835a017 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx @@ -31,7 +31,7 @@ export const FieldTypesSelect: FC = ({ }), }, ]; - fieldTypes.forEach(fieldType => { + fieldTypes.forEach((fieldType) => { options.push({ value: fieldType, text: i18n.translate('xpack.ml.datavisualizer.fieldTypesSelect.typeOptionLabel', { @@ -47,7 +47,7 @@ export const FieldTypesSelect: FC = ({ setSelectedFieldType(e.target.value as ML_JOB_FIELD_TYPES | '*')} + onChange={(e) => setSelectedFieldType(e.target.value as ML_JOB_FIELD_TYPES | '*')} aria-label={i18n.translate('xpack.ml.datavisualizer.fieldTypesSelect.selectAriaLabel', { defaultMessage: 'Select field types to display', })} diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx index 16004475eb44f..b93ae9e67ef72 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx @@ -43,7 +43,7 @@ interface Props { totalCount: number; } -const searchSizeOptions = [1000, 5000, 10000, 100000, -1].map(v => { +const searchSizeOptions = [1000, 5000, 10000, 100000, -1].map((v) => { return { value: String(v), inputDisplay: @@ -150,7 +150,7 @@ export const SearchPanel: FC = ({ setSamplerShardSize(+value)} + onChange={(value) => setSamplerShardSize(+value)} aria-label={i18n.translate( 'xpack.ml.datavisualizer.searchPanel.sampleSizeAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index 9ba99ce891538..7d1f456d2334f 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -38,7 +38,7 @@ export class DataLoader { ): Promise { const aggregatableFields: string[] = []; const nonAggregatableFields: string[] = []; - this._indexPattern.fields.forEach(field => { + this._indexPattern.fields.forEach((field) => { const fieldName = field.displayName !== undefined ? field.displayName : field.name; if (this.isDisplayField(fieldName) === true) { if (field.aggregatable === true) { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx index 06d89ab782167..d68c0342ac857 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx @@ -131,7 +131,7 @@ export const Page: FC = () => { // Obtain the list of non metric field types which appear in the index pattern. let indexedFieldTypes: ML_JOB_FIELD_TYPES[] = []; const indexPatternFields: IFieldType[] = currentIndexPattern.fields; - indexPatternFields.forEach(field => { + indexPatternFields.forEach((field) => { if (field.scripted !== true) { const dataVisualizerType: ML_JOB_FIELD_TYPES | undefined = kbnTypeToMLJobType(field); if ( @@ -300,7 +300,7 @@ export const Page: FC = () => { } const configsToLoad = metricConfigs.filter( - config => config.existsInDocs === true && config.loading === true + (config) => config.existsInDocs === true && config.loading === true ); if (configsToLoad.length === 0) { return; @@ -308,7 +308,7 @@ export const Page: FC = () => { // Pass the field name, type and cardinality in the request. // Top values will be obtained on a sample if cardinality > 100000. - const existMetricFields: FieldRequestConfig[] = configsToLoad.map(config => { + const existMetricFields: FieldRequestConfig[] = configsToLoad.map((config) => { const props = { fieldName: config.fieldName, type: config.type, cardinality: 0 }; if (config.stats !== undefined && config.stats.cardinality !== undefined) { props.cardinality = config.stats.cardinality; @@ -347,7 +347,7 @@ export const Page: FC = () => { // Add the metric stats to the existing stats in the corresponding config. const configs: FieldVisConfig[] = []; - metricConfigs.forEach(config => { + metricConfigs.forEach((config) => { const configWithStats = { ...config }; if (config.fieldName !== undefined) { configWithStats.stats = { @@ -383,7 +383,7 @@ export const Page: FC = () => { } const configsToLoad = nonMetricConfigs.filter( - config => config.existsInDocs === true && config.loading === true + (config) => config.existsInDocs === true && config.loading === true ); if (configsToLoad.length === 0) { return; @@ -391,7 +391,7 @@ export const Page: FC = () => { // Pass the field name, type and cardinality in the request. // Top values will be obtained on a sample if cardinality > 100000. - const existNonMetricFields: FieldRequestConfig[] = configsToLoad.map(config => { + const existNonMetricFields: FieldRequestConfig[] = configsToLoad.map((config) => { const props = { fieldName: config.fieldName, type: config.type, cardinality: 0 }; if (config.stats !== undefined && config.stats.cardinality !== undefined) { props.cardinality = config.stats.cardinality; @@ -418,7 +418,7 @@ export const Page: FC = () => { // Add the field stats to the existing stats in the corresponding config. const configs: FieldVisConfig[] = []; - nonMetricConfigs.forEach(config => { + nonMetricConfigs.forEach((config) => { const configWithStats = { ...config }; if (config.fieldName !== undefined) { configWithStats.stats = { @@ -442,7 +442,7 @@ export const Page: FC = () => { const configs: FieldVisConfig[] = []; const aggregatableExistsFields: any[] = overallStats.aggregatableExistsFields || []; - let allMetricFields = indexPatternFields.filter(f => { + let allMetricFields = indexPatternFields.filter((f) => { return ( f.type === KBN_FIELD_TYPES.NUMBER && f.displayName !== undefined && @@ -451,14 +451,14 @@ export const Page: FC = () => { }); if (metricFieldQuery !== undefined) { const metricFieldRegexp = new RegExp(`(${metricFieldQuery})`, 'gi'); - allMetricFields = allMetricFields.filter(f => { + allMetricFields = allMetricFields.filter((f) => { const addField = f.displayName !== undefined && !!f.displayName.match(metricFieldRegexp); return addField; }); } - const metricExistsFields = allMetricFields.filter(f => { - return aggregatableExistsFields.find(existsF => { + const metricExistsFields = allMetricFields.filter((f) => { + return aggregatableExistsFields.find((existsF) => { return existsF.fieldName === f.displayName; }); }); @@ -493,8 +493,8 @@ export const Page: FC = () => { const metricFieldsToShow = showAllMetrics === true ? allMetricFields : metricExistsFields; - metricFieldsToShow.forEach(field => { - const fieldData = aggregatableFields.find(f => { + metricFieldsToShow.forEach((field) => { + const fieldData = aggregatableFields.find((f) => { return f.fieldName === field.displayName; }); @@ -517,7 +517,7 @@ export const Page: FC = () => { function createNonMetricCards() { let allNonMetricFields = []; if (nonMetricShowFieldType === '*') { - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.type !== KBN_FIELD_TYPES.NUMBER && f.displayName !== undefined && @@ -531,7 +531,7 @@ export const Page: FC = () => { ) { const aggregatableCheck = nonMetricShowFieldType === ML_JOB_FIELD_TYPES.KEYWORD ? true : false; - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.displayName !== undefined && dataLoader.isDisplayField(f.displayName) === true && @@ -540,7 +540,7 @@ export const Page: FC = () => { ); }); } else { - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.type === nonMetricShowFieldType && f.displayName !== undefined && @@ -554,7 +554,7 @@ export const Page: FC = () => { if (nonMetricFieldQuery !== undefined) { const nonMetricFieldRegexp = new RegExp(`(${nonMetricFieldQuery})`, 'gi'); allNonMetricFields = allNonMetricFields.filter( - f => f.displayName !== undefined && f.displayName.match(nonMetricFieldRegexp) + (f) => f.displayName !== undefined && f.displayName.match(nonMetricFieldRegexp) ); } @@ -565,9 +565,9 @@ export const Page: FC = () => { const aggregatableExistsFields: any[] = overallStats.aggregatableExistsFields || []; const nonAggregatableExistsFields: any[] = overallStats.nonAggregatableExistsFields || []; - allNonMetricFields.forEach(f => { + allNonMetricFields.forEach((f) => { const checkAggregatableField = aggregatableExistsFields.find( - existsField => existsField.fieldName === f.displayName + (existsField) => existsField.fieldName === f.displayName ); if (checkAggregatableField !== undefined) { @@ -575,7 +575,7 @@ export const Page: FC = () => { nonMetricFieldData.push(checkAggregatableField); } else { const checkNonAggregatableField = nonAggregatableExistsFields.find( - existsField => existsField.fieldName === f.displayName + (existsField) => existsField.fieldName === f.displayName ); if (checkNonAggregatableField !== undefined) { @@ -606,8 +606,8 @@ export const Page: FC = () => { const configs: FieldVisConfig[] = []; - nonMetricFieldsToShow.forEach(field => { - const fieldData = nonMetricFieldData.find(f => f.fieldName === field.displayName); + nonMetricFieldsToShow.forEach((field) => { + const fieldData = nonMetricFieldData.find((f) => f.fieldName === field.displayName); const nonMetricConfig = { ...fieldData, diff --git a/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts b/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts index 994d67bfdb02c..24926960abd17 100644 --- a/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts +++ b/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts @@ -15,18 +15,18 @@ import { createJobs } from '../explorer_utils'; export function jobSelectionActionCreator(selectedJobIds: string[]) { return from(mlFieldFormatService.populateFormats(selectedJobIds)).pipe( - map(resp => { + map((resp) => { if (resp.err) { console.log('Error populating field formats:', resp.err); // eslint-disable-line no-console return null; } - const jobs = createJobs(mlJobService.jobs).map(job => { - job.selected = selectedJobIds.some(id => job.id === id); + const jobs = createJobs(mlJobService.jobs).map((job) => { + job.selected = selectedJobIds.some((id) => job.id === id); return job; }); - const selectedJobs = jobs.filter(job => job.selected); + const selectedJobs = jobs.filter((job) => job.selected); return { type: EXPLORER_ACTION.JOB_SELECTION_CHANGE, diff --git a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts index 37794a250db34..590a69283a819 100644 --- a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts +++ b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts @@ -40,7 +40,7 @@ import { ExplorerState } from '../reducers'; // the original function. const memoizeIsEqual = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); const wrapWithLastRefreshArg = any>(func: T) => { - return function(lastRefresh: number, ...args: Parameters): ReturnType { + return function (lastRefresh: number, ...args: Parameters): ReturnType { return func.apply(null, args); }; }; @@ -265,5 +265,5 @@ const explorerData$ = loadExplorerData$.pipe( export const useExplorerData = (): [Partial | undefined, (d: any) => void] => { const explorerData = useObservable(explorerData$); - return [explorerData, c => loadExplorerData$.next(c)]; + return [explorerData, (c) => loadExplorerData$.next(c)]; }; diff --git a/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx b/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx index 0263ad08b03cf..1c3c42b58b10e 100644 --- a/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx +++ b/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx @@ -35,7 +35,7 @@ export function getKqlQueryValues({ // if ast.type == 'function' then layout of ast.arguments: // [{ arguments: [ { type: 'literal', value: 'AAL' } ] },{ arguments: [ { type: 'literal', value: 'AAL' } ] }] if (ast && Array.isArray(ast.arguments)) { - ast.arguments.forEach(arg => { + ast.arguments.forEach((arg) => { if (arg.arguments !== undefined) { arg.arguments.forEach((nestedArg: { type: string; value: string }) => { if (typeof nestedArg.value === 'string') { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer.js b/x-pack/plugins/ml/public/application/explorer/explorer.js index 9c9c82a212472..5cebb6354c0db 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer.js @@ -84,7 +84,7 @@ import { MlTooltipComponent } from '../components/chart_tooltip'; import { hasMatchingPoints } from './has_matching_points'; function mapSwimlaneOptionsToEuiOptions(options) { - return options.map(option => ({ + return options.map((option) => ({ value: option, text: option, })); @@ -190,12 +190,12 @@ export class Explorer extends React.Component { this.anomaliesTablePreviousArgs = null; } - viewByChangeHandler = e => explorerService.setViewBySwimlaneFieldName(e.target.value); + viewByChangeHandler = (e) => explorerService.setViewBySwimlaneFieldName(e.target.value); isSwimlaneSelectActive = false; onSwimlaneEnterHandler = () => this.setSwimlaneSelectActive(true); onSwimlaneLeaveHandler = () => this.setSwimlaneSelectActive(false); - setSwimlaneSelectActive = active => { + setSwimlaneSelectActive = (active) => { if (this.isSwimlaneSelectActive && !active && this.disableDragSelectOnMouseLeave) { this.dragSelect.stop(); this.isSwimlaneSelectActive = active; @@ -210,7 +210,7 @@ export class Explorer extends React.Component { }; // Listener for click events in the swimlane to load corresponding anomaly data. - swimlaneCellClick = selectedCells => { + swimlaneCellClick = (selectedCells) => { // If selectedCells is an empty object we clear any existing selection, // otherwise we save the new selection in AppState and update the Explorer. if (Object.keys(selectedCells).length === 0) { @@ -276,7 +276,7 @@ export class Explorer extends React.Component { } }; - updateLanguage = language => this.setState({ language }); + updateLanguage = (language) => this.setState({ language }); render() { const { showCharts, severity } = this.props; @@ -416,7 +416,7 @@ export class Explorer extends React.Component { > {showOverallSwimlane && ( - {tooltipService => ( + {(tooltipService) => ( - {tooltipService => ( + {(tooltipService) => (  –  ); - const entityFieldBadges = entityFields.map(entity => ( + const entityFieldBadges = entityFields.map((entity) => ( )); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js index edb4b988277f9..b5e9daad7d1c1 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js @@ -60,7 +60,7 @@ export function buildConfig(record) { jobId: record.job_id, aggregationInterval: config.interval, chartFunction: functionLabel, - entityFields: config.entityFields.map(f => ({ + entityFields: config.entityFields.map((f) => ({ fieldName: f.fieldName, fieldValue: f.fieldValue, })), diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js index 2b577c978eb13..6c7c3e9040216 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js @@ -92,7 +92,7 @@ export class ExplorerChartDistribution extends React.Component { const CHART_Y_ATTRIBUTE = chartType === CHART_TYPE.EVENT_DISTRIBUTION ? 'entity' : 'value'; - let highlight = config.chartData.find(d => d.anomalyScore !== undefined); + let highlight = config.chartData.find((d) => d.anomalyScore !== undefined); highlight = highlight && highlight.entity; const filteredChartData = init(config); @@ -118,7 +118,7 @@ export class ExplorerChartDistribution extends React.Component { const categoryLimit = 30; const scaleCategories = d3 .nest() - .key(d => d.entity) + .key((d) => d.entity) .entries(chartData) .sort((a, b) => { return b.values.length - a.values.length; @@ -130,22 +130,22 @@ export class ExplorerChartDistribution extends React.Component { } return true; }) - .map(d => d.key); + .map((d) => d.key); - chartData = chartData.filter(d => { + chartData = chartData.filter((d) => { return scaleCategories.includes(d.entity); }); if (chartType === CHART_TYPE.POPULATION_DISTRIBUTION) { const focusData = chartData - .filter(d => { + .filter((d) => { return d.entity === highlight; }) - .map(d => d.value); + .map((d) => d.value); const focusExtent = d3.extent(focusData); // now again filter chartData to include only the data points within the domain - chartData = chartData.filter(d => { + chartData = chartData.filter((d) => { return d.value <= focusExtent[1]; }); @@ -184,7 +184,7 @@ export class ExplorerChartDistribution extends React.Component { .data(tempLabelTextData) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { @@ -195,7 +195,7 @@ export class ExplorerChartDistribution extends React.Component { } }) // Don't use an arrow function since we need access to `this`. - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + yAxis.tickPadding(), maxYAxisLabelWidth @@ -225,9 +225,9 @@ export class ExplorerChartDistribution extends React.Component { lineChartValuesLine = d3.svg .line() - .x(d => lineChartXScale(d.date)) - .y(d => lineChartYScale(d[CHART_Y_ATTRIBUTE])) - .defined(d => d.value !== null); + .x((d) => lineChartXScale(d.date)) + .y((d) => lineChartYScale(d[CHART_Y_ATTRIBUTE])) + .defined((d) => d.value !== null); lineChartGroup = svg .append('g') @@ -280,7 +280,7 @@ export class ExplorerChartDistribution extends React.Component { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); // With tooManyBuckets the chart would end up with no x-axis labels // because the ticks are based on the span of the emphasis section, @@ -300,7 +300,7 @@ export class ExplorerChartDistribution extends React.Component { .tickPadding(10); if (fieldFormat !== undefined) { - yAxis.tickFormat(d => fieldFormat.convert(d, 'text')); + yAxis.tickFormat((d) => fieldFormat.convert(d, 'text')); } const axes = lineChartGroup.append('g'); @@ -311,17 +311,14 @@ export class ExplorerChartDistribution extends React.Component { .attr('transform', 'translate(0,' + chartHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); // emphasize the y axis label this rare chart is actually about if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { axes .select('.y') .selectAll('text') - .each(function(d) { + .each(function (d) { d3.select(this).classed('ml-explorer-chart-axis-emphasis', d === highlight); }); } @@ -345,10 +342,10 @@ export class ExplorerChartDistribution extends React.Component { .enter() .append('circle') .classed('values-dots-circle', true) - .classed('values-dots-circle-blur', d => { + .classed('values-dots-circle-blur', (d) => { return d.entity !== highlight; }) - .attr('r', d => (d.entity === highlight ? radius * 1.5 : radius)); + .attr('r', (d) => (d.entity === highlight ? radius * 1.5 : radius)); dots.attr('cx', rareChartValuesLine.x()).attr('cy', rareChartValuesLine.y()); @@ -382,7 +379,7 @@ export class ExplorerChartDistribution extends React.Component { .append('g') .attr('class', 'chart-markers') .selectAll('.metric-value') - .data(data.filter(d => d.value !== null)); + .data(data.filter((d) => d.value !== null)); // Remove dots that are no longer needed i.e. if number of chart points has decreased. dots.exit().remove(); @@ -392,16 +389,16 @@ export class ExplorerChartDistribution extends React.Component { .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); // Update all dots to new positions. dots - .attr('cx', d => lineChartXScale(d.date)) - .attr('cy', d => lineChartYScale(d[CHART_Y_ATTRIBUTE])) - .attr('class', d => { + .attr('cx', (d) => lineChartXScale(d.date)) + .attr('cy', (d) => lineChartYScale(d[CHART_Y_ATTRIBUTE])) + .attr('class', (d) => { let markerClass = 'metric-value'; if (_.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity) { markerClass += ' anomaly-marker '; @@ -414,7 +411,7 @@ export class ExplorerChartDistribution extends React.Component { const scheduledEventMarkers = lineChartGroup .select('.chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -430,8 +427,11 @@ export class ExplorerChartDistribution extends React.Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => lineChartYScale(d[CHART_Y_ATTRIBUTE]) - SCHEDULED_EVENT_MARKER_HEIGHT / 2); + .attr('x', (d) => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr( + 'y', + (d) => lineChartYScale(d[CHART_Y_ATTRIBUTE]) - SCHEDULED_EVENT_MARKER_HEIGHT / 2 + ); } function showLineChartTooltip(marker, circle) { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js index 06fd82204c1e1..53aca826f2dda 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js @@ -143,15 +143,9 @@ describe('ExplorerChart', () => { expect(+selectedInterval.getAttribute('y')).toBe(2); expect(+selectedInterval.getAttribute('height')).toBe(166); - const xAxisTicks = wrapper - .getDOMNode() - .querySelector('.x') - .querySelectorAll('.tick'); + const xAxisTicks = wrapper.getDOMNode().querySelector('.x').querySelectorAll('.tick'); expect([...xAxisTicks]).toHaveLength(0); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(5); const emphasizedAxisLabel = wrapper .getDOMNode() @@ -164,10 +158,7 @@ describe('ExplorerChart', () => { expect(paths[1].getAttribute('class')).toBe('domain'); expect(paths[2]).toBe(undefined); - const dots = wrapper - .getDOMNode() - .querySelector('.values-dots') - .querySelectorAll('circle'); + const dots = wrapper.getDOMNode().querySelector('.values-dots').querySelectorAll('circle'); expect([...dots]).toHaveLength(5); expect(dots[0].getAttribute('r')).toBe('1.5'); @@ -176,7 +167,7 @@ describe('ExplorerChart', () => { .querySelector('.chart-markers') .querySelectorAll('circle'); expect([...chartMarkers]).toHaveLength(5); - expect([...chartMarkers].map(d => +d.getAttribute('r'))).toEqual([7, 7, 7, 7, 7]); + expect([...chartMarkers].map((d) => +d.getAttribute('r'))).toEqual([7, 7, 7, 7, 7]); }); it('Anomaly Explorer Chart with single data point', () => { @@ -192,10 +183,7 @@ describe('ExplorerChart', () => { ]; const wrapper = init(chartData); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(1); }); }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js index 0ee1eac19f64d..01f4626e222aa 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js @@ -77,7 +77,7 @@ export const ExplorerChartInfoTooltip = ({ }, ]; - entityFields.forEach(entityField => { + entityFields.forEach((entityField) => { toolTipData.push({ title: entityField.fieldName, description: entityField.fieldValue, diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js index 531a24493c961..63775c5ca312e 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js @@ -128,7 +128,7 @@ export class ExplorerChartSingleMetric extends React.Component { .data(lineChartYScale.ticks()) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { @@ -136,7 +136,7 @@ export class ExplorerChartSingleMetric extends React.Component { } }) // Don't use an arrow function since we need access to `this`. - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + yAxis.tickPadding(), maxYAxisLabelWidth @@ -158,9 +158,9 @@ export class ExplorerChartSingleMetric extends React.Component { lineChartValuesLine = d3.svg .line() - .x(d => lineChartXScale(d.date)) - .y(d => lineChartYScale(d.value)) - .defined(d => d.value !== null); + .x((d) => lineChartXScale(d.date)) + .y((d) => lineChartYScale(d.value)) + .defined((d) => d.value !== null); lineChartGroup = svg .append('g') @@ -212,7 +212,7 @@ export class ExplorerChartSingleMetric extends React.Component { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); // With tooManyBuckets the chart would end up with no x-axis labels // because the ticks are based on the span of the emphasis section, @@ -232,7 +232,7 @@ export class ExplorerChartSingleMetric extends React.Component { .tickPadding(10); if (fieldFormat !== undefined) { - yAxis.tickFormat(d => fieldFormat.convert(d, 'text')); + yAxis.tickFormat((d) => fieldFormat.convert(d, 'text')); } const axes = lineChartGroup.append('g'); @@ -243,10 +243,7 @@ export class ExplorerChartSingleMetric extends React.Component { .attr('transform', 'translate(0,' + chartHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); if (tooManyBuckets === false) { removeLabelOverlap(gAxis, tickValuesStart, interval, vizWidth); @@ -290,7 +287,7 @@ export class ExplorerChartSingleMetric extends React.Component { .selectAll('.metric-value') .data( data.filter( - d => + (d) => (d.value !== null || typeof d.anomalyScore === 'number') && !showMultiBucketAnomalyMarker(d) ) @@ -304,18 +301,19 @@ export class ExplorerChartSingleMetric extends React.Component { .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); - const isAnomalyVisible = d => _.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity; + const isAnomalyVisible = (d) => + _.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity; // Update all dots to new positions. dots - .attr('cx', d => lineChartXScale(d.date)) - .attr('cy', d => lineChartYScale(d.value)) - .attr('class', d => { + .attr('cx', (d) => lineChartXScale(d.date)) + .attr('cy', (d) => lineChartYScale(d.value)) + .attr('class', (d) => { let markerClass = 'metric-value'; if (isAnomalyVisible(d)) { markerClass += ` anomaly-marker ${getSeverityWithLow(d.anomalyScore).id}`; @@ -327,7 +325,7 @@ export class ExplorerChartSingleMetric extends React.Component { const multiBucketMarkers = lineChartGroup .select('.chart-markers') .selectAll('.multi-bucket') - .data(data.filter(d => isAnomalyVisible(d) && showMultiBucketAnomalyMarker(d) === true)); + .data(data.filter((d) => isAnomalyVisible(d) && showMultiBucketAnomalyMarker(d) === true)); // Remove multi-bucket markers that are no longer needed multiBucketMarkers.exit().remove(); @@ -336,20 +334,17 @@ export class ExplorerChartSingleMetric extends React.Component { multiBucketMarkers .enter() .append('path') + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') + 'transform', + (d) => `translate(${lineChartXScale(d.date)}, ${lineChartYScale(d.value)})` ) .attr( - 'transform', - d => `translate(${lineChartXScale(d.date)}, ${lineChartYScale(d.value)})` + 'class', + (d) => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}` ) - .attr('class', d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); @@ -358,7 +353,7 @@ export class ExplorerChartSingleMetric extends React.Component { const scheduledEventMarkers = lineChartGroup .select('.chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -374,8 +369,8 @@ export class ExplorerChartSingleMetric extends React.Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => lineChartYScale(d.value) - SCHEDULED_EVENT_SYMBOL_HEIGHT / 2); + .attr('x', (d) => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr('y', (d) => lineChartYScale(d.value) - SCHEDULED_EVENT_SYMBOL_HEIGHT / 2); } function showLineChartTooltip(marker, circle) { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js index 54f541ceb7c3d..99f5c3eff6984 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js @@ -143,15 +143,9 @@ describe('ExplorerChart', () => { expect(+selectedInterval.getAttribute('y')).toBe(2); expect(+selectedInterval.getAttribute('height')).toBe(166); - const xAxisTicks = wrapper - .getDOMNode() - .querySelector('.x') - .querySelectorAll('.tick'); + const xAxisTicks = wrapper.getDOMNode().querySelector('.x').querySelectorAll('.tick'); expect([...xAxisTicks]).toHaveLength(0); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(10); const paths = wrapper.getDOMNode().querySelectorAll('path'); @@ -162,10 +156,7 @@ describe('ExplorerChart', () => { 'MNaN,159.33024504444444ZMNaN,9.166257955555556LNaN,169.60736875555557' ); - const dots = wrapper - .getDOMNode() - .querySelector('.values-dots') - .querySelectorAll('circle'); + const dots = wrapper.getDOMNode().querySelector('.values-dots').querySelectorAll('circle'); expect([...dots]).toHaveLength(1); expect(dots[0].getAttribute('r')).toBe('1.5'); @@ -174,7 +165,7 @@ describe('ExplorerChart', () => { .querySelector('.chart-markers') .querySelectorAll('circle'); expect([...chartMarkers]).toHaveLength(4); - expect([...chartMarkers].map(d => +d.getAttribute('r'))).toEqual([7, 7, 7, 7]); + expect([...chartMarkers].map((d) => +d.getAttribute('r'))).toEqual([7, 7, 7, 7]); }); it('Anomaly Explorer Chart with single data point', () => { @@ -191,10 +182,7 @@ describe('ExplorerChart', () => { const wrapper = init(chartData); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(13); }); }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js index 5b95931d31ab6..9988298c25c51 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js @@ -45,7 +45,7 @@ const textViewButton = i18n.translate( // from charts metadata for React's key attribute function getChartId(series) { const { jobId, detectorLabel, entityFields } = series; - const entities = entityFields.map(ef => `${ef.fieldName}/${ef.fieldValue}`).join(','); + const entities = entityFields.map((ef) => `${ef.fieldName}/${ef.fieldValue}`).join(','); const id = `${jobId}_${detectorLabel}_${entities}`; return id; } @@ -58,7 +58,7 @@ function ExplorerChartContainer({ series, severity, tooManyBuckets, wrapLabel }) let DetectorLabel = {detectorLabel}; if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { - const byField = series.entityFields.find(d => d.fieldType === 'by'); + const byField = series.entityFields.find((d) => d.fieldType === 'by'); if (typeof byField !== 'undefined') { DetectorLabel = ( @@ -121,7 +121,7 @@ function ExplorerChartContainer({ series, severity, tooManyBuckets, wrapLabel }) ) { return ( - {tooltipService => ( + {(tooltipService) => ( - {tooltipService => ( + {(tooltipService) => ( isLabelLengthAboveThreshold(series)); + const wrapLabel = seriesToPlot.some((series) => isLabelLengthAboveThreshold(series)); return ( {seriesToPlot.length > 0 && - seriesToPlot.map(series => ( + seriesToPlot.map((series) => ( { + const filteredRecords = anomalyRecords.filter((record) => { return Number(record.record_score) >= severity; }); const allSeriesRecords = processRecordsForDisplay(filteredRecords); @@ -88,7 +88,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, data.tooManyBuckets = tooManyBuckets; // initialize the charts with loading indicators - data.seriesToPlot = seriesConfigs.map(config => ({ + data.seriesToPlot = seriesConfigs.map((config) => ({ ...config, loading: true, chartData: null, @@ -168,15 +168,15 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, return mlResultsService .getModelPlotOutput(jobId, detectorIndex, criteriaFields, range.min, range.max, interval) .toPromise() - .then(resp => { + .then((resp) => { // Return data in format required by the explorer charts. const results = resp.results; - Object.keys(results).forEach(time => { + Object.keys(results).forEach((time) => { obj.results[time] = results[time].actual; }); resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -225,11 +225,11 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // Define splitField and filterField based on chartType if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { - splitField = config.entityFields.find(f => f.fieldType === 'by'); - filterField = config.entityFields.find(f => f.fieldType === 'partition'); + splitField = config.entityFields.find((f) => f.fieldType === 'by'); + filterField = config.entityFields.find((f) => f.fieldType === 'partition'); } else if (chartType === CHART_TYPE.POPULATION_DISTRIBUTION) { - splitField = config.entityFields.find(f => f.fieldType === 'over'); - filterField = config.entityFields.find(f => f.fieldType === 'partition'); + splitField = config.entityFields.find((f) => f.fieldType === 'over'); + filterField = config.entityFields.find((f) => f.fieldType === 'partition'); } const datafeedQuery = _.get(config, 'datafeedConfig.query', null); @@ -251,7 +251,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // only after that trigger data processing and page render. // TODO - if query returns no results e.g. source data has been deleted, // display a message saying 'No data between earliest/latest'. - const seriesPromises = seriesConfigs.map(seriesConfig => + const seriesPromises = seriesConfigs.map((seriesConfig) => Promise.all([ getMetricData(seriesConfig, chartRange), getRecordsForCriteria(seriesConfig, chartRange), @@ -280,7 +280,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, if (metricData !== undefined) { if (eventDistribution.length > 0 && records.length > 0) { const filterField = records[0].by_field_value || records[0].over_field_value; - chartData = eventDistribution.filter(d => d.entity !== filterField); + chartData = eventDistribution.filter((d) => d.entity !== filterField); _.map(metricData, (value, time) => { // The filtering for rare/event_distribution charts needs to be handled // differently because of how the source data is structured. @@ -310,7 +310,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // Iterate through the anomaly records, adding anomalyScore properties // to the chartData entries for anomalous buckets. const chartDataForPointSearch = getChartDataForPointSearch(chartData, records[0], chartType); - _.each(records, record => { + _.each(records, (record) => { // Look for a chart point with the same time as the record. // If none found, insert a point for anomalies due to a gap in the data. const recordTime = record[ML_TIME_FIELD_NAME]; @@ -365,7 +365,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, chartType === CHART_TYPE.EVENT_DISTRIBUTION || chartType === CHART_TYPE.POPULATION_DISTRIBUTION ) { - return chartData.filter(d => { + return chartData.filter((d) => { return d.entity === (record && (record.by_field_value || record.over_field_value)); }); } @@ -374,17 +374,17 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, } function findChartPointForTime(chartData, time) { - return chartData.find(point => point.date === time); + return chartData.find((point) => point.date === time); } Promise.all(seriesPromises) - .then(response => { + .then((response) => { // calculate an overall min/max for all series const processedData = response.map(processChartData); const allDataPoints = _.reduce( processedData, (datapoints, series) => { - _.each(series, d => datapoints.push(d)); + _.each(series, (d) => datapoints.push(d)); return datapoints; }, [] @@ -403,7 +403,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, })); explorerService.setCharts({ ...data }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -416,7 +416,7 @@ function processRecordsForDisplay(anomalyRecords) { // Aggregate by job, detector, and analysis fields (partition, by, over). const aggregatedData = {}; - _.each(anomalyRecords, record => { + _.each(anomalyRecords, (record) => { // Check if we can plot a chart for this record, depending on whether the source data // is chartable, and if model plot is enabled for the job. const job = mlJobService.getJob(record.job_id); @@ -521,20 +521,20 @@ function processRecordsForDisplay(anomalyRecords) { console.log('explorer charts aggregatedData is:', aggregatedData); let recordsForSeries = []; // Convert to an array of the records with the highest record_score per unique series. - _.each(aggregatedData, detectorsForJob => { - _.each(detectorsForJob, groupsForDetector => { + _.each(aggregatedData, (detectorsForJob) => { + _.each(detectorsForJob, (groupsForDetector) => { if (groupsForDetector.maxScoreRecord !== undefined) { // Detector with no partition / by field. recordsForSeries.push(groupsForDetector.maxScoreRecord); } else { - _.each(groupsForDetector, valuesForGroup => { - _.each(valuesForGroup, dataForGroupValue => { + _.each(groupsForDetector, (valuesForGroup) => { + _.each(valuesForGroup, (dataForGroupValue) => { if (dataForGroupValue.maxScoreRecord !== undefined) { recordsForSeries.push(dataForGroupValue.maxScoreRecord); } else { // Second level of aggregation for partition and by/over. - _.each(dataForGroupValue, splitsForGroup => { - _.each(splitsForGroup, dataForSplitValue => { + _.each(dataForGroupValue, (splitsForGroup) => { + _.each(splitsForGroup, (dataForSplitValue) => { recordsForSeries.push(dataForSplitValue.maxScoreRecord); }); }); @@ -585,7 +585,7 @@ function calculateChartRange( let minMs = recordsToPlot[0][timeFieldName]; let maxMs = recordsToPlot[0][timeFieldName]; - _.each(recordsToPlot, record => { + _.each(recordsToPlot, (record) => { const diffMs = maxMs - minMs; if (diffMs < maxTimeSpan) { const recordTime = record[timeFieldName]; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js index 35261257ce625..6a9fd19180a4e 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js @@ -108,7 +108,7 @@ describe('explorerChartsContainerService', () => { explorerService.setCharts.mockClear(); }); - test('call anomalyChangeListener with empty series config', done => { + test('call anomalyChangeListener with empty series config', (done) => { anomalyDataChange([], 1486656000000, 1486670399999); setImmediate(() => { @@ -121,7 +121,7 @@ describe('explorerChartsContainerService', () => { }); }); - test('call anomalyChangeListener with actual series config', done => { + test('call anomalyChangeListener with actual series config', (done) => { anomalyDataChange(mockAnomalyChartRecords, 1486656000000, 1486670399999); setImmediate(() => { @@ -132,8 +132,8 @@ describe('explorerChartsContainerService', () => { }); }); - test('filtering should skip values of null', done => { - const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords).map(d => { + test('filtering should skip values of null', (done) => { + const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords).map((d) => { d.job_id = 'mock-job-id-distribution'; return d; }); @@ -150,13 +150,13 @@ describe('explorerChartsContainerService', () => { // it should remove the datapoint with `null` and keep the one with `0`. const chartData = explorerService.setCharts.mock.calls[1][0].seriesToPlot[0].chartData; expect(chartData).toHaveLength(114); - expect(chartData.filter(d => d.value === 0)).toHaveLength(1); - expect(chartData.filter(d => d.value === null)).toHaveLength(0); + expect(chartData.filter((d) => d.value === 0)).toHaveLength(1); + expect(chartData.filter((d) => d.value === null)).toHaveLength(0); done(); }); }); - test('field value with trailing dot should not throw an error', done => { + test('field value with trailing dot should not throw an error', (done) => { const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords); mockAnomalyChartRecordsClone[1].partition_field_value = 'AAL.'; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx index e8ea54d28f5a0..18b5de1d51f9c 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx @@ -118,7 +118,7 @@ export class ExplorerSwimlane extends React.Component { // immediately clear the selection, otherwise trigger // a reload with the updated selected cells. if (selectedData.bucketScore === 0) { - elements.map(e => d3.select(e).classed('ds-selected', false)); + elements.map((e) => d3.select(e).classed('ds-selected', false)); this.selectCell([], selectedData); previousSelectedData = null; } else { @@ -199,7 +199,7 @@ export class ExplorerSwimlane extends React.Component { highlightOverall(times: number[]) { const overallSwimlane = d3.select('.ml-swimlane-overall'); - times.forEach(time => { + times.forEach((time) => { const overallCell = overallSwimlane .selectAll(`div[data-time="${time}"]`) .selectAll('.sl-cell-inner,.sl-cell-inner-dragselect'); @@ -229,7 +229,7 @@ export class ExplorerSwimlane extends React.Component { .classed('sl-cell-inner-selected', true); const rootParent = d3.select(this.rootNode.current!.parentNode!); - rootParent.selectAll('.lane-label').classed('lane-label-masked', function(this: HTMLElement) { + rootParent.selectAll('.lane-label').classed('lane-label-masked', function (this: HTMLElement) { return laneLabels.indexOf(d3.select(this).text()) === -1; }); @@ -379,7 +379,7 @@ export class ExplorerSwimlane extends React.Component { function cellMouseOverFactory(time: number, i: number) { // Don't use an arrow function here because we need access to `this`, // which is where d3 supplies a reference to the corresponding DOM element. - return function(this: HTMLElement, lane: string) { + return function (this: HTMLElement, lane: string) { const bucketScore = getBucketScore(lane, time); if (bucketScore !== 0) { lane = lane === '' ? EMPTY_FIELD_VALUE_LABEL : lane; @@ -393,10 +393,7 @@ export class ExplorerSwimlane extends React.Component { }; const d3Lanes = swimlanes.selectAll('.lane').data(lanes); - const d3LanesEnter = d3Lanes - .enter() - .append('div') - .classed('lane', true); + const d3LanesEnter = d3Lanes.enter().append('div').classed('lane', true); const that = this; @@ -420,10 +417,10 @@ export class ExplorerSwimlane extends React.Component { swimlaneCellClick({}); } }) - .each(function(this: HTMLElement) { + .each(function (this: HTMLElement) { if (swimlaneData.fieldName !== undefined) { d3.select(this) - .on('mouseover', value => { + .on('mouseover', (value) => { that.props.tooltipService.show( [ { skipHeader: true } as ChartTooltipValue, @@ -447,7 +444,7 @@ export class ExplorerSwimlane extends React.Component { }) .attr( 'aria-label', - value => `${mlEscape(swimlaneData.fieldName!)}: ${mlEscape(value)}` + (value) => `${mlEscape(swimlaneData.fieldName!)}: ${mlEscape(value)}` ); } }); @@ -456,7 +453,7 @@ export class ExplorerSwimlane extends React.Component { function getBucketScore(lane: string, time: number): number { let bucketScore = 0; - const point = points.find(p => { + const point = points.find((p) => { return p.value > 0 && p.laneLabel === lane && p.time === time; }); if (typeof point !== 'undefined') { @@ -483,7 +480,7 @@ export class ExplorerSwimlane extends React.Component { // of this iteration to the event. .on('mouseover', cellMouseOverFactory(time, i)) .on('mouseleave', cellMouseleave) - .each(function(this: NodeWithData, laneLabel: string) { + .each(function (this: NodeWithData, laneLabel: string) { this.__clickData__ = { bucketScore: getBucketScore(laneLabel, time), laneLabel, @@ -493,13 +490,13 @@ export class ExplorerSwimlane extends React.Component { }); // calls itself with each() to get access to lane (= d3 data) - cell.append('div').each(function(this: HTMLElement, lane: string) { + cell.append('div').each(function (this: HTMLElement, lane: string) { const el = d3.select(this); let color = 'none'; let bucketScore = 0; - const point = points.find(p => { + const point = points.find((p) => { return p.value > 0 && p.laneLabel === lane && p.time === time; }); @@ -525,25 +522,19 @@ export class ExplorerSwimlane extends React.Component { // height of .time-tick-labels const svgHeight = 25; - const svg = laneTimes - .append('svg') - .attr('width', chartWidth) - .attr('height', svgHeight); + const svg = laneTimes.append('svg').attr('width', chartWidth).attr('height', svgHeight); const xAxis = d3.svg .axis() .scale(xAxisScale) .ticks(numTicksForDateFormat(chartWidth, xAxisTickFormat)) - .tickFormat(tick => moment(tick).format(xAxisTickFormat)); + .tickFormat((tick) => moment(tick).format(xAxisTickFormat)); - const gAxis = svg - .append('g') - .attr('class', 'x axis') - .call(xAxis); + const gAxis = svg.append('g').attr('class', 'x axis').call(xAxis); // remove overlapping labels let overlapCheck = 0; - gAxis.selectAll('g.tick').each(function(this: HTMLElement) { + gAxis.selectAll('g.tick').each(function (this: HTMLElement) { const tick = d3.select(this); const xTransform = d3.transform(tick.attr('transform')).translate[0]; const tickWidth = (tick.select('text').node() as SVGGraphicsElement).getBBox().width; @@ -595,7 +586,7 @@ export class ExplorerSwimlane extends React.Component { const selectedTimes = _.get(selectionState, 'times', []); const selectedTimeExtent = d3.extent(selectedTimes); - selectedLanes.forEach(selectedLane => { + selectedLanes.forEach((selectedLane) => { if ( lanes.indexOf(selectedLane) > -1 && selectedTimeExtent[0] >= startTime && @@ -607,7 +598,7 @@ export class ExplorerSwimlane extends React.Component { `div[data-lane-label="${mlEscape(selectedLane)}"]` ); - laneCells.each(function(this: HTMLElement) { + laneCells.each(function (this: HTMLElement) { const cell = d3.select(this); const cellTime = parseInt(cell.attr('data-time'), 10); if (cellTime >= selectedTimeExtent[0] && cellTime <= selectedTimeExtent[1]) { @@ -621,7 +612,7 @@ export class ExplorerSwimlane extends React.Component { return Math.max(maxBucketScore, +d3.select(cell).attr('data-bucket-score') || 0); }, 0); - const selectedCellTimes = cellsToSelect.map(e => { + const selectedCellTimes = cellsToSelect.map((e) => { return (d3.select(e).node() as NodeWithData).__clickData__.time; }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js index aaf9ff491ce32..f35a000b7f9e1 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js @@ -41,7 +41,7 @@ import { getSwimlaneContainerWidth } from './legacy_utils'; // create new job objects based on standard job config objects // new job objects just contain job id, bucket span in seconds and a selected flag. export function createJobs(jobs) { - return jobs.map(job => { + return jobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, selected: false, bucketSpanSeconds: bucketSpan.asSeconds() }; }); @@ -78,7 +78,7 @@ export async function loadFilteredTopInfluencers( // Add the specified influencer(s) to ensure they are used in the filter // even if their influencer score for the selected time range is zero. - influencers.forEach(influencer => { + influencers.forEach((influencer) => { const fieldName = influencer.fieldName; if (recordInfluencersByName[influencer.fieldName] === undefined) { recordInfluencersByName[influencer.fieldName] = []; @@ -87,9 +87,9 @@ export async function loadFilteredTopInfluencers( }); // Add the influencers from the top scoring anomalies. - records.forEach(record => { + records.forEach((record) => { const influencersByName = record.influencers || []; - influencersByName.forEach(influencer => { + influencersByName.forEach((influencer) => { const fieldName = influencer.influencer_field_name; const fieldValues = influencer.influencer_field_values; if (recordInfluencersByName[fieldName] === undefined) { @@ -100,15 +100,15 @@ export async function loadFilteredTopInfluencers( }); const uniqValuesByName = {}; - Object.keys(recordInfluencersByName).forEach(fieldName => { + Object.keys(recordInfluencersByName).forEach((fieldName) => { const fieldValues = recordInfluencersByName[fieldName]; uniqValuesByName[fieldName] = uniq(fieldValues); }); const filterInfluencers = []; - Object.keys(uniqValuesByName).forEach(fieldName => { + Object.keys(uniqValuesByName).forEach((fieldName) => { // Find record influencers with the same field name as the clicked on cell(s). - const matchingFieldName = influencers.find(influencer => { + const matchingFieldName = influencers.find((influencer) => { return influencer.fieldName === fieldName; }); @@ -117,7 +117,7 @@ export async function loadFilteredTopInfluencers( filterInfluencers.push(...influencers); } else { // For other field names, add values from all records. - uniqValuesByName[fieldName].forEach(fieldValue => { + uniqValuesByName[fieldName].forEach((fieldValue) => { filterInfluencers.push({ fieldName, fieldValue }); }); } @@ -135,7 +135,7 @@ export async function loadFilteredTopInfluencers( export function getInfluencers(selectedJobs = []) { const influencers = []; - selectedJobs.forEach(selectedJob => { + selectedJobs.forEach((selectedJob) => { const job = mlJobService.getJob(selectedJob.id); if (job !== undefined && job.analysis_config && job.analysis_config.influencers) { influencers.push(...job.analysis_config.influencers); @@ -212,7 +212,7 @@ export function getSelectionInfluencers(selectedCells, fieldName) { selectedCells.viewByFieldName !== undefined && selectedCells.viewByFieldName !== VIEW_BY_JOB_LABEL ) { - return selectedCells.lanes.map(laneLabel => ({ fieldName, fieldValue: laneLabel })); + return selectedCells.lanes.map((laneLabel) => ({ fieldName, fieldValue: laneLabel })); } return []; @@ -228,7 +228,7 @@ export function getSelectionJobIds(selectedCells, selectedJobs) { return selectedCells.lanes; } - return selectedJobs.map(d => d.id); + return selectedJobs.map((d) => d.id); } export function getSwimlaneBucketInterval(selectedJobs, swimlaneContainerWidth) { @@ -275,15 +275,15 @@ export function loadViewByTopFieldValuesForSelectedTime( swimlaneLimit, noInfluencersConfigured ) { - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Find the top field values for the selected time, and then load the 'view by' // swimlane over the full time range for those specific field values. - return new Promise(resolve => { + return new Promise((resolve) => { if (viewBySwimlaneFieldName !== VIEW_BY_JOB_LABEL) { mlResultsService .getTopInfluencers(selectedJobIds, earliestMs, latestMs, swimlaneLimit) - .then(resp => { + .then((resp) => { if (resp.influencers[viewBySwimlaneFieldName] === undefined) { resolve([]); } @@ -291,7 +291,7 @@ export function loadViewByTopFieldValuesForSelectedTime( const topFieldValues = []; const topInfluencers = resp.influencers[viewBySwimlaneFieldName]; if (Array.isArray(topInfluencers)) { - topInfluencers.forEach(influencerData => { + topInfluencers.forEach((influencerData) => { if (influencerData.maxAnomalyScore > 0) { topFieldValues.push(influencerData.influencerFieldValue); } @@ -311,7 +311,7 @@ export function loadViewByTopFieldValuesForSelectedTime( ).asSeconds() + 's', swimlaneLimit ) - .then(resp => { + .then((resp) => { const topFieldValues = Object.keys(resp.results); resolve(topFieldValues); }); @@ -328,19 +328,19 @@ export function getViewBySwimlaneOptions({ selectedCells, selectedJobs, }) { - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Unique influencers for the selected job(s). const viewByOptions = chain( mlJobService.jobs.reduce((reducedViewByOptions, job) => { - if (selectedJobIds.some(jobId => jobId === job.job_id)) { + if (selectedJobIds.some((jobId) => jobId === job.job_id)) { return reducedViewByOptions.concat(job.analysis_config.influencers || []); } return reducedViewByOptions; }, []) ) .uniq() - .sortBy(fieldName => fieldName.toLowerCase()) + .sortBy((fieldName) => fieldName.toLowerCase()) .value(); viewByOptions.push(VIEW_BY_JOB_LABEL); @@ -360,12 +360,12 @@ export function getViewBySwimlaneOptions({ } else if (mlJobService.jobs.length > 0 && selectedJobIds.length > 0) { // For a single job, default to the first partition, over, // by or influencer field of the first selected job. - const firstSelectedJob = mlJobService.jobs.find(job => { + const firstSelectedJob = mlJobService.jobs.find((job) => { return job.job_id === selectedJobIds[0]; }); const firstJobInfluencers = firstSelectedJob.analysis_config.influencers || []; - firstSelectedJob.analysis_config.detectors.forEach(detector => { + firstSelectedJob.analysis_config.detectors.forEach((detector) => { if ( detector.partition_field_name !== undefined && firstJobInfluencers.indexOf(detector.partition_field_name) !== -1 @@ -416,7 +416,7 @@ export function getViewBySwimlaneOptions({ Array.isArray(viewBySwimlaneOptions) && Array.isArray(filteredFields) ) { - const filteredOptions = viewBySwimlaneOptions.filter(option => { + const filteredOptions = viewBySwimlaneOptions.filter((option) => { return ( filteredFields.includes(option) || option === VIEW_BY_JOB_LABEL || @@ -538,10 +538,10 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, const jobIds = selectedCells !== undefined && selectedCells.viewByFieldName === VIEW_BY_JOB_LABEL ? selectedCells.lanes - : selectedJobs.map(d => d.id); + : selectedJobs.map((d) => d.id); const timeRange = getSelectionTimeRange(selectedCells, interval, bounds); - return new Promise(resolve => { + return new Promise((resolve) => { ml.annotations .getAnnotations({ jobIds, @@ -550,13 +550,13 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, }) .toPromise() - .then(resp => { + .then((resp) => { if (resp.error !== undefined || resp.annotations === undefined) { return resolve([]); } const annotationsData = []; - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { const jobAnnotations = resp.annotations[jobId]; if (jobAnnotations !== undefined) { annotationsData.push(...jobAnnotations); @@ -574,7 +574,7 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, }) ); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of annotations for jobs list:', resp); // Silently fail and just return an empty array for annotations to not break the UI. return resolve([]); @@ -613,10 +613,10 @@ export async function loadAnomaliesTableData( influencersFilterQuery ) .toPromise() - .then(resp => { + .then((resp) => { const anomalies = resp.anomalies; const detectorsByJob = mlJobService.detectorsByJob; - anomalies.forEach(anomaly => { + anomalies.forEach((anomaly) => { // Add a detector property to each anomaly. // Default to functionDescription if no description available. // TODO - when job_service is moved server_side, move this to server endpoint. @@ -662,7 +662,7 @@ export async function loadAnomaliesTableData( jobIds, }); }) - .catch(resp => { + .catch((resp) => { console.log('Explorer - error loading data for anomalies table:', resp); reject(); }); @@ -680,7 +680,7 @@ export async function loadDataForCharts( selectedCells, influencersFilterQuery ) { - return new Promise(resolve => { + return new Promise((resolve) => { // Just skip doing the request when this function // is called without the minimum required data. if ( @@ -705,7 +705,7 @@ export async function loadDataForCharts( 500, influencersFilterQuery ) - .then(resp => { + .then((resp) => { // Ignore this response if it's returned by an out of date promise if (newRequestCount < requestCount) { resolve([]); @@ -725,7 +725,7 @@ export async function loadDataForCharts( } export function loadOverallData(selectedJobs, interval, bounds) { - return new Promise(resolve => { + return new Promise((resolve) => { // Loads the overall data components i.e. the overall swimlane and influencers list. if (selectedJobs === null) { resolve({ @@ -738,7 +738,7 @@ export function loadOverallData(selectedJobs, interval, bounds) { // Ensure the search bounds align to the bucketing interval used in the swimlane so // that the first and last buckets are complete. const searchBounds = getBoundsRoundedToInterval(bounds, interval, false); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Load the overall bucket scores by time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -757,7 +757,7 @@ export function loadOverallData(selectedJobs, interval, bounds) { overallBucketsBounds.max.valueOf(), interval.asSeconds() + 's' ) - .then(resp => { + .then((resp) => { const overallSwimlaneData = processOverallResults( resp.results, searchBounds, @@ -782,8 +782,8 @@ export function loadViewBySwimlane( influencersFilterQuery, noInfluencersConfigured ) { - return new Promise(resolve => { - const finish = resp => { + return new Promise((resolve) => { + const finish = (resp) => { if (resp !== undefined) { const viewBySwimlaneData = processViewByResults( resp.results, @@ -819,7 +819,7 @@ export function loadViewBySwimlane( getSwimlaneBucketInterval(selectedJobs, getSwimlaneContainerWidth(noInfluencersConfigured)), false ); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // load scores by influencer/jobId value and time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -866,7 +866,7 @@ export async function loadTopInfluencers( noInfluencersConfigured, influencersFilterQuery ) { - return new Promise(resolve => { + return new Promise((resolve) => { if (noInfluencersConfigured !== true) { mlResultsService .getTopInfluencers( @@ -877,7 +877,7 @@ export async function loadTopInfluencers( influencers, influencersFilterQuery ) - .then(resp => { + .then((resp) => { // TODO - sort the influencers keys so that the partition field(s) are first. console.log('Explorer top influencers data set:', resp.influencers); resolve(resp.influencers); diff --git a/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts b/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts index 397615d68f189..1af399d9a70b5 100644 --- a/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts +++ b/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts @@ -17,13 +17,13 @@ export const hasMatchingPoints = ({ swimlaneData, }: HasMatchingPointsParams): boolean => { // If filtered fields includes a wildcard search maskAll only if there are no points matching the pattern - const wildCardField = filteredFields.find(field => /\@kuery-wildcard\@$/.test(field)); + const wildCardField = filteredFields.find((field) => /\@kuery-wildcard\@$/.test(field)); const substring = wildCardField !== undefined ? wildCardField.replace(/\@kuery-wildcard\@$/, '') : null; return ( substring !== null && - swimlaneData.points.some(point => { + swimlaneData.points.some((point) => { return point.laneLabel.includes(substring); }) ); diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts index 9b6c7e4fb99bc..98e630d0028f2 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts @@ -13,7 +13,7 @@ import { getInfluencers, ExplorerJob } from '../../explorer_utils'; export function getIndexPattern(selectedJobs: ExplorerJob[]) { return { title: ML_RESULTS_INDEX_PATTERN, - fields: getInfluencers(selectedJobs).map(influencer => ({ + fields: getInfluencers(selectedJobs).map((influencer) => ({ name: influencer, type: 'string', aggregatable: true, diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts index 0d84179c572d2..819f6ca1cac92 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts @@ -23,7 +23,7 @@ export function setInfluencerFilterSettings( const { selectedCells, viewBySwimlaneOptions } = state; let selectedViewByFieldName = state.viewBySwimlaneFieldName; - const filteredViewBySwimlaneOptions = viewBySwimlaneOptions.filter(d => + const filteredViewBySwimlaneOptions = viewBySwimlaneOptions.filter((d) => filteredFields.includes(d) ); diff --git a/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx b/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx index 03e3273b80832..7f7a8fc5a70bd 100644 --- a/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx +++ b/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx @@ -15,7 +15,7 @@ import { EuiSelect } from '@elastic/eui'; const limitOptions = [5, 10, 25, 50]; -const euiOptions = limitOptions.map(limit => ({ +const euiOptions = limitOptions.map((limit) => ({ value: limit, text: `${limit}`, })); diff --git a/x-pack/plugins/ml/public/application/formatters/format_value.ts b/x-pack/plugins/ml/public/application/formatters/format_value.ts index abafe65615156..1a696d6e01dde 100644 --- a/x-pack/plugins/ml/public/application/formatters/format_value.ts +++ b/x-pack/plugins/ml/public/application/formatters/format_value.ts @@ -39,7 +39,7 @@ export function formatValue( // Currently only multi-value response is for lat_long detectors. // Return with array style formatting, with items formatted as numbers, rather than // the default String format which is set for geo_point and geo_shape fields. - const values = value.map(val => formatSingleValue(val, mlFunction, undefined, record)); + const values = value.map((val) => formatSingleValue(val, mlFunction, undefined, record)); return `[${values}]`; } } else { @@ -73,20 +73,14 @@ function formatSingleValue( record !== undefined && record.timestamp !== undefined ? new Date(record.timestamp) : new Date(); - const utcMoment = moment - .utc(d) - .startOf('week') - .add(value, 's'); + const utcMoment = moment.utc(d).startOf('week').add(value, 's'); return moment(utcMoment.valueOf()).format('ddd HH:mm'); } else if (mlFunction === 'time_of_day') { const d = record !== undefined && record.timestamp !== undefined ? new Date(record.timestamp) : new Date(); - const utcMoment = moment - .utc(d) - .startOf('day') - .add(value, 's'); + const utcMoment = moment.utc(d).startOf('day').add(value, 's'); return moment(utcMoment.valueOf()).format('HH:mm'); } else { if (fieldFormat !== undefined) { diff --git a/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts b/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts index 5b378934ed5e8..d5f357106b735 100644 --- a/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts +++ b/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts @@ -21,7 +21,7 @@ describe('ML - numberAsOrdinal formatter', () => { { number: 100, asOrdinal: '100th' }, ]; test('returns the expected numeral format', () => { - tests.forEach(test => { + tests.forEach((test) => { expect(numberAsOrdinal(test.number)).toBe(test.asOrdinal); }); }); diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx index c4c32c1f4c5f2..4f6e520298efb 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx @@ -114,7 +114,7 @@ export const CustomUrlEditor: FC = ({ }; const onQueryEntitiesChange = (selectedOptions: EuiComboBoxOptionOption[]) => { - const selectedFieldNames = selectedOptions.map(option => option.label); + const selectedFieldNames = selectedOptions.map((option) => option.label); const kibanaSettings = customUrl.kibanaSettings; setEditCustomUrl({ @@ -159,22 +159,22 @@ export const CustomUrlEditor: FC = ({ const { label, type, timeRange, kibanaSettings, otherUrlSettings } = customUrl; - const dashboardOptions = dashboards.map(dashboard => { + const dashboardOptions = dashboards.map((dashboard) => { return { value: dashboard.id, text: dashboard.title }; }); - const indexPatternOptions = indexPatterns.map(indexPattern => { + const indexPatternOptions = indexPatterns.map((indexPattern) => { return { value: indexPattern.id, text: indexPattern.title }; }); - const entityOptions = queryEntityFieldNames.map(fieldName => ({ label: fieldName })); + const entityOptions = queryEntityFieldNames.map((fieldName) => ({ label: fieldName })); let selectedEntityOptions: EuiComboBoxOptionOption[] = []; if (kibanaSettings !== undefined && kibanaSettings.queryFieldNames !== undefined) { const queryFieldNames: string[] = kibanaSettings.queryFieldNames; - selectedEntityOptions = queryFieldNames.map(fieldName => ({ label: fieldName })); + selectedEntityOptions = queryFieldNames.map((fieldName) => ({ label: fieldName })); } - const timeRangeOptions = Object.values(TIME_RANGE_TYPE).map(timeRangeType => ({ + const timeRangeOptions = Object.values(TIME_RANGE_TYPE).map((timeRangeType) => ({ value: timeRangeType, text: timeRangeType, })); diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx index 1b18afaf2569f..7e228757dfd90 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx @@ -102,10 +102,10 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust const onTestButtonClick = (index: number) => { if (index < customUrls.length) { getTestUrl(job, customUrls[index]) - .then(testUrl => { + .then((testUrl) => { openCustomUrlWindow(testUrl, customUrls[index]); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error obtaining URL for test:', resp); @@ -163,7 +163,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust onLabelChange(e, index)} + onChange={(e) => onLabelChange(e, index)} data-test-subj={`mlJobEditCustomUrlLabelInput_${index}`} /> @@ -184,7 +184,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust }} fullWidth={true} value={customUrl.url_value} - onChange={e => onUrlValueChange(e, index)} + onChange={(e) => onUrlValueChange(e, index)} onBlur={() => { setExpandedUrlIndex(null); }} @@ -216,7 +216,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust value={(customUrl as KibanaUrlConfig).time_range || ''} isInvalid={isInvalidTimeRange} placeholder={TIME_RANGE_TYPE.AUTO} - onChange={e => onTimeRangeChange(e, index)} + onChange={(e) => onTimeRangeChange(e, index)} /> diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js index 18873b3b6b6d3..0b33efa3f9ff1 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js @@ -47,7 +47,7 @@ export function getNewCustomUrlDefaults(job, dashboards, indexPatterns) { datafeedConfig.indices.length > 0 ) { const datafeedIndex = datafeedConfig.indices[0]; - let defaultIndexPattern = indexPatterns.find(indexPattern => { + let defaultIndexPattern = indexPatterns.find((indexPattern) => { return indexPattern.title === datafeedIndex; }); @@ -87,7 +87,7 @@ export function getQueryEntityFieldNames(job) { detectors.forEach((detector, detectorIndex) => { const partitioningFields = getPartitioningFieldNames(job, detectorIndex); - partitioningFields.forEach(fieldName => { + partitioningFields.forEach((fieldName) => { if (entityFieldNames.indexOf(fieldName) === -1) { entityFieldNames.push(fieldName); } @@ -139,7 +139,7 @@ function buildDashboardUrlFromSettings(settings) { const savedObjectsClient = getSavedObjectsClient(); savedObjectsClient .get('dashboard', dashboardId) - .then(response => { + .then((response) => { // Use the filters from the saved dashboard if there are any. let filters = []; @@ -176,7 +176,7 @@ function buildDashboardUrlFromSettings(settings) { // template to inject the time parameters. useHash: false, }) - .then(urlValue => { + .then((urlValue) => { const urlToAdd = { url_name: settings.label, url_value: decodeURIComponent(`dashboards${url.parse(urlValue).hash}`), @@ -190,7 +190,7 @@ function buildDashboardUrlFromSettings(settings) { resolve(urlToAdd); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -300,7 +300,7 @@ export function getTestUrl(job, customUrl) { rest_total_hits_as_int: true, body, }) - .then(resp => { + .then((resp) => { if (resp.hits.total > 0) { const record = resp.hits.hits[0]._source; testUrl = replaceTokensInUrlValue(customUrl, bucketSpanSecs, record, 'timestamp'); @@ -308,7 +308,7 @@ export function getTestUrl(job, customUrl) { } else { // No anomalies yet for this job, so do a preview of the search // configured in the job datafeed to obtain sample docs. - mlJobService.searchPreview(job).then(response => { + mlJobService.searchPreview(job).then((response) => { let testDoc; const docTimeFieldName = job.data_description.time_field; @@ -348,7 +348,7 @@ export function getTestUrl(job, customUrl) { }); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js index 0d88aa29d70e9..d05278c19b5a5 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js @@ -81,9 +81,9 @@ export class CreateWatchFlyoutUI extends Component { }); }; - showFlyout = jobId => { + showFlyout = (jobId) => { loadFullJob(jobId) - .then(job => { + .then((job) => { const bucketSpan = job.analysis_config.bucket_span; mlCreateWatchService.config.includeInfluencers = job.analysis_config.influencers.length > 0; @@ -94,7 +94,7 @@ export class CreateWatchFlyoutUI extends Component { isFlyoutVisible: true, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -103,11 +103,11 @@ export class CreateWatchFlyoutUI extends Component { const { toasts } = this.props.kibana.services.notifications; mlCreateWatchService .createNewWatch(this.state.jobId) - .then(resp => { + .then((resp) => { toasts.addSuccess(getSuccessToast(resp.id, resp.url)); this.closeFlyout(true); }) - .catch(error => { + .catch((error) => { toasts.addDanger( i18n.translate( 'xpack.ml.jobsList.createWatchFlyout.watchNotSavedErrorNotificationMessage', diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js index 307fa79f5dea2..67de83e90695d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js @@ -80,7 +80,7 @@ class CreateWatchService { this.config.threshold = { display, val }; } - createNewWatch = function(jobId) { + createNewWatch = function (jobId) { return new Promise((resolve, reject) => { this.status.watch = this.STATUS.SAVING; if (jobId !== undefined) { @@ -173,7 +173,7 @@ class CreateWatchService { url: this.config.watcherEditURL, }); }) - .catch(resp => { + .catch((resp) => { this.status.watch = this.STATUS.SAVE_FAILED; reject(resp); }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js index 0595ce5caf931..97520626783fa 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js @@ -66,7 +66,7 @@ export class CreateWatch extends Component { } // load elasticsearch settings to see if email has been configured - ml.getNotificationSettings().then(resp => { + ml.getNotificationSettings().then((resp) => { if (has(resp, 'defaults.xpack.notification.email')) { this.setState({ emailEnabled: true }); } @@ -82,27 +82,27 @@ export class CreateWatch extends Component { }); } - onThresholdChange = threshold => { + onThresholdChange = (threshold) => { this.setState({ threshold }, () => { this.config.threshold = threshold; }); }; - onIntervalChange = e => { + onIntervalChange = (e) => { const interval = e.target.value; this.setState({ interval }, () => { this.config.interval = interval; }); }; - onIncludeEmailChanged = e => { + onIncludeEmailChanged = (e) => { const includeEmail = e.target.checked; this.setState({ includeEmail }, () => { this.config.includeEmail = includeEmail; }); }; - onEmailChange = e => { + onEmailChange = (e) => { const email = e.target.value; this.setState({ email }, () => { this.config.email = email; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx index 727830a58bb41..ff930832bde3e 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx @@ -68,7 +68,7 @@ export const SEVERITY_OPTIONS: TableSeverity[] = [ function optionValueToThreshold(value: number) { // Get corresponding threshold object with required display and val properties from the specified value. - let threshold = SEVERITY_OPTIONS.find(opt => opt.val === value); + let threshold = SEVERITY_OPTIONS.find((opt) => opt.val === value); // Default to warning if supplied value doesn't map to one of the options. if (threshold === undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js index 3e129a174c9e0..1e3ec6241311b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js @@ -56,7 +56,7 @@ export class DeleteJobModal extends Component { this.setState({ isModalVisible: false }); }; - showModal = jobs => { + showModal = (jobs) => { this.setState({ jobs, isModalVisible: true, @@ -74,7 +74,7 @@ export class DeleteJobModal extends Component { }, DELETING_JOBS_REFRESH_INTERVAL_MS); }; - setEL = el => { + setEL = (el) => { if (el) { this.el = el; } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 9066e41fb8f23..b463322ea55db 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -108,17 +108,17 @@ export class EditJobFlyoutUI extends Component { ); } - showFlyout = jobLite => { + showFlyout = (jobLite) => { const hasDatafeed = jobLite.hasDatafeed; loadFullJob(jobLite.id) - .then(job => { + .then((job) => { this.extractJob(job, hasDatafeed); this.setState({ job, isFlyoutVisible: true, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -147,7 +147,7 @@ export class EditJobFlyoutUI extends Component { jobGroups: job.groups !== undefined ? job.groups : [], jobModelMemoryLimit: mml, jobDetectors: detectors, - jobDetectorDescriptions: detectors.map(d => d.detector_description), + jobDetectorDescriptions: detectors.map((d) => d.detector_description), jobBucketSpan: bucketSpan, jobCustomUrls: customUrls, datafeedQuery: hasDatafeed ? JSON.stringify(datafeedConfig.query, null, 2) : '', @@ -171,7 +171,7 @@ export class EditJobFlyoutUI extends Component { }); } - setJobDetails = jobDetails => { + setJobDetails = (jobDetails) => { let { jobModelMemoryLimitValidationError, jobGroupsValidationError } = this.state; if (jobDetails.jobModelMemoryLimit !== undefined) { @@ -180,7 +180,7 @@ export class EditJobFlyoutUI extends Component { } if (jobDetails.jobGroups !== undefined) { - if (jobDetails.jobGroups.some(j => this.props.allJobIds.includes(j))) { + if (jobDetails.jobGroups.some((j) => this.props.allJobIds.includes(j))) { jobGroupsValidationError = i18n.translate( 'xpack.ml.jobsList.editJobFlyout.groupsAndJobsHasSameIdErrorMessage', { @@ -204,19 +204,19 @@ export class EditJobFlyoutUI extends Component { }); }; - setDetectorDescriptions = jobDetectorDescriptions => { + setDetectorDescriptions = (jobDetectorDescriptions) => { this.setState({ ...jobDetectorDescriptions, }); }; - setDatafeed = datafeed => { + setDatafeed = (datafeed) => { this.setState({ ...datafeed, }); }; - setCustomUrls = jobCustomUrls => { + setCustomUrls = (jobCustomUrls) => { const isValidJobCustomUrls = isValidCustomUrls(jobCustomUrls); this.setState({ jobCustomUrls, @@ -251,7 +251,7 @@ export class EditJobFlyoutUI extends Component { this.refreshJobs(); this.closeFlyout(true); }) - .catch(error => { + .catch((error) => { console.error(error); toasts.addDanger( i18n.translate('xpack.ml.jobsList.editJobFlyout.changesNotSavedNotificationMessage', { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js index a49a2af896be2..fcd2c09f72767 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js @@ -32,7 +32,7 @@ export function saveJob(job, newJobData, finish) { .then(() => { resolve(); }) - .catch(error => { + .catch((error) => { reject(error); }); }; @@ -41,14 +41,14 @@ export function saveJob(job, newJobData, finish) { if (Object.keys(jobData).length) { mlJobService .updateJob(job.job_id, jobData) - .then(resp => { + .then((resp) => { if (resp.success) { saveDatafeedWrapper(); } else { reject(resp); } }) - .catch(error => { + .catch((error) => { reject(error); }); } else { @@ -61,7 +61,7 @@ function saveDatafeed(datafeedData, job) { return new Promise((resolve, reject) => { if (Object.keys(datafeedData).length) { const datafeedId = job.datafeed_config.datafeed_id; - mlJobService.updateDatafeed(datafeedId, datafeedData).then(resp => { + mlJobService.updateDatafeed(datafeedId, datafeedData).then((resp) => { if (resp.success) { resolve(); } else { @@ -84,10 +84,10 @@ export function loadSavedDashboards(maxNumber) { fields: ['title'], perPage: maxNumber, }) - .then(resp => { + .then((resp) => { const savedObjects = resp.savedObjects; if (savedObjects !== undefined) { - const dashboards = savedObjects.map(savedObj => { + const dashboards = savedObjects.map((savedObj) => { return { id: savedObj.id, title: savedObj.attributes.title }; }); @@ -98,7 +98,7 @@ export function loadSavedDashboards(maxNumber) { resolve(dashboards); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -116,10 +116,10 @@ export function loadIndexPatterns(maxNumber) { fields: ['title'], perPage: maxNumber, }) - .then(resp => { + .then((resp) => { const savedObjects = resp.savedObjects; if (savedObjects !== undefined) { - const indexPatterns = savedObjects.map(savedObj => { + const indexPatterns = savedObjects.map((savedObj) => { return { id: savedObj.id, title: savedObj.attributes.title }; }); @@ -130,7 +130,7 @@ export function loadIndexPatterns(maxNumber) { resolve(indexPatterns); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -183,7 +183,7 @@ function extractDetectorDescriptions(job, newJobData) { })); const originalDetectors = job.analysis_config.detectors; - originalDetectors.forEach(d => { + originalDetectors.forEach((d) => { if (descriptions[d.detector_index].description !== d.detector_description) { detectors.push(descriptions[d.detector_index]); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx index 6cb9dde056c5c..7af27fc22e34c 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx @@ -84,10 +84,10 @@ class CustomUrlsUI extends Component { componentDidMount() { const { toasts } = this.props.kibana.services.notifications; loadSavedDashboards(MAX_NUMBER_DASHBOARDS) - .then(dashboards => { + .then((dashboards) => { this.setState({ dashboards }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error loading list of dashboards:', resp); toasts.addDanger( @@ -101,10 +101,10 @@ class CustomUrlsUI extends Component { }); loadIndexPatterns(MAX_NUMBER_INDEX_PATTERNS) - .then(indexPatterns => { + .then((indexPatterns) => { this.setState({ indexPatterns }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error loading list of dashboards:', resp); toasts.addDanger( @@ -120,7 +120,7 @@ class CustomUrlsUI extends Component { editNewCustomUrl = () => { // Opens the editor for configuring a new custom URL. - this.setState(prevState => { + this.setState((prevState) => { const { dashboards, indexPatterns } = prevState; return { @@ -138,7 +138,7 @@ class CustomUrlsUI extends Component { addNewCustomUrl = () => { buildCustomUrlFromSettings(this.state.editorSettings as CustomUrlSettings) - .then(customUrl => { + .then((customUrl) => { const customUrls = [...this.state.customUrls, customUrl]; this.props.setCustomUrls(customUrls); this.setState({ editorOpen: false }); @@ -163,12 +163,12 @@ class CustomUrlsUI extends Component { const { toasts } = this.props.kibana.services.notifications; const job = this.props.job; buildCustomUrlFromSettings(this.state.editorSettings as CustomUrlSettings) - .then(customUrl => { + .then((customUrl) => { getTestUrl(job, customUrl) - .then(testUrl => { + .then((testUrl) => { openCustomUrlWindow(testUrl, customUrl); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error obtaining URL for test:', resp); toasts.addWarning( @@ -181,7 +181,7 @@ class CustomUrlsUI extends Component { ); }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error building custom URL from settings:', resp); toasts.addWarning( diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js index 3d81b767021a0..a038f761d47a0 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js @@ -61,19 +61,19 @@ export class Datafeed extends Component { }; } - onQueryChange = query => { + onQueryChange = (query) => { this.setDatafeed({ datafeedQuery: query }); }; - onQueryDelayChange = e => { + onQueryDelayChange = (e) => { this.setDatafeed({ datafeedQueryDelay: e.target.value }); }; - onFrequencyChange = e => { + onFrequencyChange = (e) => { this.setDatafeed({ datafeedFrequency: e.target.value }); }; - onScrollSizeChange = e => { + onScrollSizeChange = (e) => { this.setDatafeed({ datafeedScrollSize: +e.target.value }); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js index 0296004f736a2..e9ba65f14138b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js @@ -16,7 +16,7 @@ export class Detectors extends Component { constructor(props) { super(props); - this.detectors = mlJobService.getJobGroups().map(g => ({ label: g.id })); + this.detectors = mlJobService.getJobGroups().map((g) => ({ label: g.id })); this.state = { detectors: [], @@ -47,7 +47,7 @@ export class Detectors extends Component { {detectorDescriptions.map((d, i) => ( - this.onDescriptionChange(e, i)} /> + this.onDescriptionChange(e, i)} /> ))} diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js index 672fd8cefaaba..974afafc08b6b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js @@ -33,18 +33,18 @@ export class JobDetails extends Component { // load groups to populate the select options ml.jobs .groups() - .then(resp => { - const groups = resp.map(g => ({ label: g.id })); + .then((resp) => { + const groups = resp.map((g) => ({ label: g.id })); this.setState({ groups }); }) - .catch(error => { + .catch((error) => { console.error('Could not load groups', error); }); } static getDerivedStateFromProps(props) { const selectedGroups = - props.jobGroups !== undefined ? props.jobGroups.map(g => ({ label: g })) : []; + props.jobGroups !== undefined ? props.jobGroups.map((g) => ({ label: g })) : []; return { description: props.jobDescription, @@ -55,16 +55,16 @@ export class JobDetails extends Component { }; } - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setJobDetails({ jobDescription: e.target.value }); }; - onMmlChange = e => { + onMmlChange = (e) => { this.setJobDetails({ jobModelMemoryLimit: e.target.value }); }; - onGroupsChange = selectedGroups => { - this.setJobDetails({ jobGroups: selectedGroups.map(g => g.label) }); + onGroupsChange = (selectedGroups) => { + this.setJobDetails({ jobGroups: selectedGroups.map((g) => g.label) }); }; onCreateGroup = (input, flattenedOptions) => { @@ -82,7 +82,7 @@ export class JobDetails extends Component { // Create the option if it doesn't exist. if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { groups.push(newGroup); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js index bb4bed93f922e..254c546df65bc 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js @@ -33,9 +33,9 @@ export function actionsMenuContent( defaultMessage: 'Start datafeed', }), icon: 'play', - enabled: item => item.deleting !== true && canStartStopDatafeed, - available: item => isStartable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canStartStopDatafeed, + available: (item) => isStartable([item]), + onClick: (item) => { showStartDatafeedModal([item]); closeMenu(); }, @@ -49,9 +49,9 @@ export function actionsMenuContent( defaultMessage: 'Stop datafeed', }), icon: 'stop', - enabled: item => item.deleting !== true && canStartStopDatafeed, - available: item => isStoppable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canStartStopDatafeed, + available: (item) => isStoppable([item]), + onClick: (item) => { stopDatafeeds([item], refreshJobs); closeMenu(true); }, @@ -65,9 +65,9 @@ export function actionsMenuContent( defaultMessage: 'Close job', }), icon: 'cross', - enabled: item => item.deleting !== true && canCloseJob, - available: item => isClosable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canCloseJob, + available: (item) => isClosable([item]), + onClick: (item) => { closeJobs([item], refreshJobs); closeMenu(true); }, @@ -81,19 +81,19 @@ export function actionsMenuContent( defaultMessage: 'Clone job', }), icon: 'copy', - enabled: item => { + enabled: (item) => { // We only allow cloning of a job if the user has the right permissions and can still access // the indexPattern the job was created for. An indexPattern could either have been deleted // since the the job was created or the current user doesn't have the required permissions to // access the indexPattern. const indexPatternNames = getIndexPatternNames(); - const jobIndicesAvailable = item.datafeedIndices.every(dfiName => { - return indexPatternNames.some(ipName => ipName === dfiName); + const jobIndicesAvailable = item.datafeedIndices.every((dfiName) => { + return indexPatternNames.some((ipName) => ipName === dfiName); }); return item.deleting !== true && canCreateJob && jobIndicesAvailable; }, - onClick: item => { + onClick: (item) => { cloneJob(item.id); closeMenu(true); }, @@ -107,8 +107,8 @@ export function actionsMenuContent( defaultMessage: 'Edit job', }), icon: 'pencil', - enabled: item => item.deleting !== true && canUpdateJob && canUpdateDatafeed, - onClick: item => { + enabled: (item) => item.deleting !== true && canUpdateJob && canUpdateDatafeed, + onClick: (item) => { showEditJobFlyout(item); closeMenu(); }, @@ -124,7 +124,7 @@ export function actionsMenuContent( icon: 'trash', color: 'danger', enabled: () => canDeleteJob, - onClick: item => { + onClick: (item) => { showDeleteJobModal([item]); closeMenu(); }, diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js index 9406f1b3456cf..ff314c237f5d7 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js @@ -62,10 +62,10 @@ export class DatafeedPreviewPane extends Component { this.setState({ canPreviewDatafeed }); updateDatafeedPreview(this.props.job, canPreviewDatafeed) - .then(previewJson => { + .then((previewJson) => { this.setState({ previewJson, loading: false }); }) - .catch(error => { + .catch((error) => { console.log('Datafeed preview could not be loaded', error); this.setState({ loading: false }); }); @@ -89,7 +89,7 @@ function updateDatafeedPreview(job, canPreviewDatafeed) { if (canPreviewDatafeed) { mlJobService .getDatafeedPreview(job.datafeed_config.datafeed_id) - .then(resp => { + .then((resp) => { if (Array.isArray(resp)) { resolve(JSON.stringify(resp.slice(0, ML_DATA_PREVIEW_COUNT), null, 2)); } else { @@ -97,7 +97,7 @@ function updateDatafeedPreview(job, canPreviewDatafeed) { console.log('Datafeed preview could not be loaded', resp); } }) - .catch(error => { + .catch((error) => { reject(error); }); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js index fa36a0626d632..50e5aeeb29dd9 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js @@ -34,7 +34,7 @@ export function extractJobDetails(job) { }; if (job.custom_settings && job.custom_settings.custom_urls) { customUrl.items.push( - ...job.custom_settings.custom_urls.map(cu => [cu.url_name, cu.url_value, cu.time_range]) + ...job.custom_settings.custom_urls.map((cu) => [cu.url_name, cu.url_value, cu.time_range]) ); } @@ -59,13 +59,13 @@ export function extractJobDetails(job) { items: [], }; if (job.calendars) { - calendars.items = job.calendars.map(c => [ + calendars.items = job.calendars.map((c) => [ '', {c}, ]); // remove the calendars list from the general section // so not to show it twice. - const i = general.items.findIndex(item => item[0] === 'calendars'); + const i = general.items.findIndex((item) => item[0] === 'calendars'); if (i >= 0) { general.items.splice(i, 1); } @@ -81,7 +81,7 @@ export function extractJobDetails(job) { }; if (job.analysis_config && job.analysis_config.detectors) { detectors.items.push( - ...job.analysis_config.detectors.map(d => { + ...job.analysis_config.detectors.map((d) => { const stringifiedDtr = detectorToString(d); return [ stringifiedDtr, @@ -97,7 +97,7 @@ export function extractJobDetails(job) { defaultMessage: 'Influencers', }), position: 'left', - items: job.analysis_config.influencers.map(i => ['', i]), + items: job.analysis_config.influencers.map((i) => ['', i]), }; const analysisConfig = { @@ -141,7 +141,7 @@ export function extractJobDetails(job) { if (job.datafeed_config && job.datafeed_config.timing_stats) { // remove the timing_stats list from the datafeed section // so not to show it twice. - const i = datafeed.items.findIndex(item => item[0] === 'timing_stats'); + const i = datafeed.items.findIndex((item) => item[0] === 'timing_stats'); if (i >= 0) { datafeed.items.splice(i, 1); } @@ -183,7 +183,7 @@ export function extractJobDetails(job) { items: job.datafeed_config && job.datafeed_config.timing_stats ? filterObjects(job.datafeed_config.timing_stats) - .filter(o => o[0] !== 'total_search_time_ms') // remove total_search_time_ms as average_search_time_per_bucket_ms is better + .filter((o) => o[0] !== 'total_search_time_ms') // remove total_search_time_ms as average_search_time_per_bucket_ms is better .map(formatValues) : [], }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js index 41dfdb0dcfeed..817715dbf6413 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js @@ -56,13 +56,13 @@ export class ForecastsTable extends Component { dataCounts.earliest_record_timestamp, MAX_FORECASTS ) - .then(resp => { + .then((resp) => { this.setState({ isLoading: false, forecasts: resp.forecasts, }); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of forecasts for jobs list:', resp); this.setState({ isLoading: false, @@ -201,7 +201,7 @@ export class ForecastsTable extends Component { defaultMessage: 'Created', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, scope: 'row', @@ -212,7 +212,7 @@ export class ForecastsTable extends Component { defaultMessage: 'From', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -222,7 +222,7 @@ export class ForecastsTable extends Component { defaultMessage: 'To', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -238,7 +238,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.memorySizeLabel', { defaultMessage: 'Memory size', }), - render: bytes => formatNumber(bytes, '0b'), + render: (bytes) => formatNumber(bytes, '0b'), sortable: true, }, { @@ -246,7 +246,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.processingTimeLabel', { defaultMessage: 'Processing time', }), - render: ms => + render: (ms) => i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.msTimeUnitLabel', { defaultMessage: '{ms} ms', values: { @@ -260,7 +260,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.expiresLabel', { defaultMessage: 'Expires', }), - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -270,7 +270,7 @@ export class ForecastsTable extends Component { defaultMessage: 'Messages', }), sortable: false, - render: messages => { + render: (messages) => { return (
{messages.map((message, index) => { @@ -286,7 +286,7 @@ export class ForecastsTable extends Component { defaultMessage: 'View', }), width: '60px', - render: forecast => { + render: (forecast) => { const viewForecastAriaLabel = i18n.translate( 'xpack.ml.jobsList.jobDetails.forecastsTable.viewAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js index 246a476517ace..9194f7537cf3d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js @@ -84,9 +84,9 @@ export function formatValues([key, value]) { export function filterObjects(obj, allowArrays, allowObjects) { return Object.keys(obj) .filter( - k => allowObjects || typeof obj[k] !== 'object' || (allowArrays && Array.isArray(obj[k])) + (k) => allowObjects || typeof obj[k] !== 'object' || (allowArrays && Array.isArray(obj[k])) ) - .map(k => { + .map((k) => { let item = obj[k]; if (Array.isArray(item)) { item = item.join(', '); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js index e7df2c089dca2..606210dd87593 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js @@ -79,14 +79,14 @@ export class JobDetailsPane extends Component {
{sections - .filter(s => s.position === 'left') + .filter((s) => s.position === 'left') .map((s, i) => (
))}
{sections - .filter(s => s.position === 'right') + .filter((s) => s.position === 'right') .map((s, i) => (
))} diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js index a91df3cce01f2..b274a8d572adb 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js @@ -18,8 +18,8 @@ import { FormattedMessage } from '@kbn/i18n/react'; function loadGroups() { return ml.jobs .groups() - .then(groups => { - return groups.map(g => ({ + .then((groups) => { + return groups.map((g) => ({ value: g.id, view: (
@@ -36,7 +36,7 @@ function loadGroups() { ), })); }) - .catch(error => { + .catch((error) => { console.log(error); return []; }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js index 0cccca722557d..dbaa1ff59a487 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js @@ -14,7 +14,7 @@ export function JobDescription({ job }) {
{job.description}   - {job.groups.map(group => ( + {job.groups.map((group) => ( ))}
diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js index 9874ac56577d3..0afaca3ec12e1 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js @@ -61,7 +61,7 @@ export class JobsList extends Component { }); }; - toggleRow = item => { + toggleRow = (item) => { this.props.toggleRow(item.id); }; @@ -76,7 +76,7 @@ export class JobsList extends Component { getPageOfJobs(index, size, sortField, sortDirection) { let list = this.state.jobsSummaryList; - list = sortBy(this.state.jobsSummaryList, item => item[sortField]); + list = sortBy(this.state.jobsSummaryList, (item) => item[sortField]); list = sortDirection === 'asc' ? list : list.reverse(); const listLength = list.length; @@ -101,7 +101,7 @@ export class JobsList extends Component { render() { const { loading, isManagementTable } = this.props; const selectionControls = { - selectable: job => job.deleting !== true, + selectable: (job) => job.deleting !== true, selectableMessage: (selectable, rowItem) => selectable === false ? i18n.translate('xpack.ml.jobsList.cannotSelectRowForJobMessage', { @@ -134,7 +134,7 @@ export class JobsList extends Component {

), - render: item => ( + render: (item) => ( this.toggleRow(item)} isDisabled={item.deleting === true} @@ -166,7 +166,7 @@ export class JobsList extends Component { truncateText: false, width: '20%', scope: 'row', - render: isManagementTable ? id => this.getJobIdLink(id) : undefined, + render: isManagementTable ? (id) => this.getJobIdLink(id) : undefined, }, { field: 'auditMessage', @@ -180,7 +180,7 @@ export class JobsList extends Component {

), - render: item => , + render: (item) => , }, { name: i18n.translate('xpack.ml.jobsList.descriptionLabel', { @@ -202,7 +202,7 @@ export class JobsList extends Component { sortable: true, truncateText: false, dataType: 'number', - render: count => toLocaleString(count), + render: (count) => toLocaleString(count), width: '10%', }, { @@ -239,7 +239,7 @@ export class JobsList extends Component { name: i18n.translate('xpack.ml.jobsList.actionsLabel', { defaultMessage: 'Actions', }), - render: item => , + render: (item) => , }, ]; @@ -344,7 +344,7 @@ export class JobsList extends Component { isExpandable={true} sorting={sorting} hasActions={true} - rowProps={item => ({ + rowProps={(item) => ({ 'data-test-subj': `mlJobListRow row-${item.id}`, })} /> diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js index 6999f4c591eac..276ff5468b1d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js @@ -94,7 +94,7 @@ export class JobsListView extends Component { } } - toggleRow = jobId => { + toggleRow = (jobId) => { if (this.state.itemIdToExpandedRowMap[jobId]) { const itemIdToExpandedRowMap = { ...this.state.itemIdToExpandedRowMap }; delete itemIdToExpandedRowMap[jobId]; @@ -125,7 +125,7 @@ export class JobsListView extends Component { this.setState({ itemIdToExpandedRowMap }, () => { loadFullJob(jobId) - .then(job => { + .then((job) => { const fullJobsList = { ...this.state.fullJobsList }; fullJobsList[jobId] = job; this.setState({ fullJobsList }, () => { @@ -147,7 +147,7 @@ export class JobsListView extends Component { this.setState({ itemIdToExpandedRowMap }); }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }); @@ -157,32 +157,32 @@ export class JobsListView extends Component { addUpdateFunction = (id, f) => { this.updateFunctions[id] = f; }; - removeUpdateFunction = id => { + removeUpdateFunction = (id) => { delete this.updateFunctions[id]; }; - setShowEditJobFlyoutFunction = func => { + setShowEditJobFlyoutFunction = (func) => { this.showEditJobFlyout = func; }; unsetShowEditJobFlyoutFunction = () => { this.showEditJobFlyout = () => {}; }; - setShowDeleteJobModalFunction = func => { + setShowDeleteJobModalFunction = (func) => { this.showDeleteJobModal = func; }; unsetShowDeleteJobModalFunction = () => { this.showDeleteJobModal = () => {}; }; - setShowStartDatafeedModalFunction = func => { + setShowStartDatafeedModalFunction = (func) => { this.showStartDatafeedModal = func; }; unsetShowStartDatafeedModalFunction = () => { this.showStartDatafeedModal = () => {}; }; - setShowCreateWatchFlyoutFunction = func => { + setShowCreateWatchFlyoutFunction = (func) => { this.showCreateWatchFlyout = func; }; unsetShowCreateWatchFlyoutFunction = () => { @@ -192,24 +192,24 @@ export class JobsListView extends Component { return this.showCreateWatchFlyout; }; - selectJobChange = selectedJobs => { + selectJobChange = (selectedJobs) => { this.setState({ selectedJobs }); }; refreshSelectedJobs() { - const selectedJobsIds = this.state.selectedJobs.map(j => j.id); - const filteredJobIds = this.state.filteredJobsSummaryList.map(j => j.id); + const selectedJobsIds = this.state.selectedJobs.map((j) => j.id); + const filteredJobIds = this.state.filteredJobsSummaryList.map((j) => j.id); // refresh the jobs stored as selected // only select those which are also in the filtered list const selectedJobs = this.state.jobsSummaryList - .filter(j => selectedJobsIds.find(id => id === j.id)) - .filter(j => filteredJobIds.find(id => id === j.id)); + .filter((j) => selectedJobsIds.find((id) => id === j.id)) + .filter((j) => filteredJobIds.find((id) => id === j.id)); this.setState({ selectedJobs }); } - setFilters = filterClauses => { + setFilters = (filterClauses) => { const filteredJobsSummaryList = filterJobs(this.state.jobsSummaryList, filterClauses); this.setState({ filteredJobsSummaryList, filterClauses }, () => { this.refreshSelectedJobs(); @@ -235,7 +235,7 @@ export class JobsListView extends Component { try { const jobs = await ml.jobs.jobsSummary(expandedJobsIds); const fullJobsList = {}; - const jobsSummaryList = jobs.map(job => { + const jobsSummaryList = jobs.map((job) => { if (job.fullJob !== undefined) { fullJobsList[job.id] = job.fullJob; delete job.fullJob; @@ -251,18 +251,18 @@ export class JobsListView extends Component { } ); - Object.keys(this.updateFunctions).forEach(j => { + Object.keys(this.updateFunctions).forEach((j) => { this.updateFunctions[j].setState({ job: fullJobsList[j] }); }); - jobs.forEach(job => { + jobs.forEach((job) => { if (job.deleting && this.state.itemIdToExpandedRowMap[job.id]) { this.toggleRow(job.id); } }); this.isDoneRefreshing(); - if (jobsSummaryList.some(j => j.deleting === true)) { + if (jobsSummaryList.some((j) => j.deleting === true)) { // if there are some jobs in a deleting state, start polling for // deleting jobs so we can update the jobs list once the // deleting tasks are over @@ -351,7 +351,7 @@ export class JobsListView extends Component { renderJobsListComponents() { const { isRefreshing, loading, jobsSummaryList } = this.state; - const jobIds = jobsSummaryList.map(j => j.id); + const jobIds = jobsSummaryList.map((j) => j.id); return ( diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js index 3c791ff658978..63c29e9df328f 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js @@ -65,7 +65,7 @@ function createJobStats(jobsSummaryList) { const mlNodes = {}; let failedJobs = 0; - jobsSummaryList.forEach(job => { + jobsSummaryList.forEach((job) => { if (job.jobState === JOB_STATE.OPENED) { jobStats.open.value++; } else if (job.jobState === JOB_STATE.CLOSED) { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js index 2e530a66cd83d..a011f21fddfef 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js @@ -29,7 +29,7 @@ class MultiJobActionsMenuUI extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isOpen: !prevState.isOpen, })); }; @@ -41,7 +41,7 @@ class MultiJobActionsMenuUI extends Component { }; render() { - const anyJobsDeleting = this.props.jobs.some(j => j.deleting); + const anyJobsDeleting = this.props.jobs.some((j) => j.deleting); const button = ( { + selectGroup = (group) => { this.props.selectGroup(group); }; @@ -91,11 +91,11 @@ export class GroupList extends Component { {groups.map((g, index) => (
this.handleKeyDown(event, g, index)} + onKeyDown={(event) => this.handleKeyDown(event, g, index)} key={g.id} className="group-item" onClick={() => this.selectGroup(g)} - ref={ref => this.setRef(ref, index)} + ref={(ref) => this.setRef(ref, index)} > diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js index e7b6e3a771a85..7792893305326 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js @@ -30,10 +30,10 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; function createSelectedGroups(jobs, groups) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); const groupCounts = {}; - jobs.forEach(j => { - j.groups.forEach(g => { + jobs.forEach((j) => { + j.groups.forEach((g) => { if (groupCounts[g] === undefined) { groupCounts[g] = 0; } @@ -42,7 +42,7 @@ function createSelectedGroups(jobs, groups) { }); const selectedGroups = groups.reduce((p, c) => { - if (c.jobIds.some(j => jobIds.includes(j))) { + if (c.jobIds.some((j) => jobIds.includes(j))) { p[c.id] = { partial: groupCounts[c.id] !== jobIds.length, }; @@ -89,7 +89,7 @@ export class GroupSelector extends Component { } else { ml.jobs .groups() - .then(groups => { + .then((groups) => { const selectedGroups = createSelectedGroups(this.props.jobs, groups); this.setState({ @@ -99,7 +99,7 @@ export class GroupSelector extends Component { groups, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); } @@ -112,7 +112,7 @@ export class GroupSelector extends Component { }); }; - selectGroup = group => { + selectGroup = (group) => { const newSelectedGroups = cloneDeep(this.state.selectedGroups); if (newSelectedGroups[group.id] === undefined) { @@ -134,7 +134,7 @@ export class GroupSelector extends Component { applyChanges = () => { const { selectedGroups } = this.state; const { jobs } = this.props; - const newJobs = jobs.map(j => ({ + const newJobs = jobs.map((j) => ({ id: j.id, oldGroups: j.groups, newGroups: [], @@ -143,7 +143,7 @@ export class GroupSelector extends Component { for (const gId in selectedGroups) { if (selectedGroups.hasOwnProperty(gId)) { const group = selectedGroups[gId]; - newJobs.forEach(j => { + newJobs.forEach((j) => { if (group.partial === false || (group.partial === true && j.oldGroups.includes(gId))) { j.newGroups.push(gId); } @@ -151,10 +151,10 @@ export class GroupSelector extends Component { } } - const tempJobs = newJobs.map(j => ({ job_id: j.id, groups: j.newGroups })); + const tempJobs = newJobs.map((j) => ({ job_id: j.id, groups: j.newGroups })); ml.jobs .updateGroups(tempJobs) - .then(resp => { + .then((resp) => { let success = true; for (const jobId in resp) { // check success of each job update @@ -174,13 +174,13 @@ export class GroupSelector extends Component { console.error(resp); } }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); console.error(error); }); }; - addNewGroup = id => { + addNewGroup = (id) => { const newGroup = { id, calendarIds: [], @@ -188,7 +188,7 @@ export class GroupSelector extends Component { }; const groups = this.state.groups; - if (groups.some(g => g.id === newGroup.id) === false) { + if (groups.some((g) => g.id === newGroup.id) === false) { groups.push(newGroup); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js index f92f9c2fa4a3d..6a97d32f8cf0c 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js @@ -35,7 +35,7 @@ export class NewGroupInput extends Component { }; } - changeTempNewGroup = e => { + changeTempNewGroup = (e) => { const tempNewGroupName = e.target.value; let groupsValidationError = ''; @@ -59,7 +59,7 @@ export class NewGroupInput extends Component { }); }; - newGroupKeyPress = e => { + newGroupKeyPress = (e) => { if ( e.keyCode === keyCodes.ENTER && this.state.groupsValidationError === '' && diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js index 3ea25fb2f44eb..9ce15fb881bd8 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js @@ -62,15 +62,15 @@ export class StartDatafeedModal extends Component { } } - setStartTime = time => { + setStartTime = (time) => { this.setState({ startTime: time }); }; - setEndTime = time => { + setEndTime = (time) => { this.setState({ endTime: time }); }; - setCreateWatch = e => { + setCreateWatch = (e) => { this.setState({ createWatch: e.target.checked }); }; @@ -78,7 +78,7 @@ export class StartDatafeedModal extends Component { this.setState({ isModalVisible: false }); }; - setTimeRangeValid = timeRangeValid => { + setTimeRangeValid = (timeRangeValid) => { this.setState({ timeRangeValid }); }; @@ -130,7 +130,7 @@ export class StartDatafeedModal extends Component { now, timeRangeValid, } = this.state; - const startableJobs = jobs !== undefined ? jobs.filter(j => j.hasDatafeed) : []; + const startableJobs = jobs !== undefined ? jobs.filter((j) => j.hasDatafeed) : []; // disable start button if the start and end times are the same const startDisabled = timeRangeValid === false || (startTime !== undefined && startTime === endTime); @@ -222,6 +222,6 @@ StartDatafeedModal.propTypes = { }; function getLowestLatestTime(jobs) { - const times = jobs.map(j => j.latestTimestampSortValue); + const times = jobs.map((j) => j.latestTimestampSortValue); return moment(Math.min(...times)); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js index d30ec83acdede..55c87bbc90b10 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js @@ -28,7 +28,7 @@ export class TimeRangeSelector extends Component { this.now = this.props.now; } - setStartTab = tab => { + setStartTab = (tab) => { this.setState({ startTab: tab }); switch (tab) { case 0: @@ -42,7 +42,7 @@ export class TimeRangeSelector extends Component { } }; - setEndTab = tab => { + setEndTab = (tab) => { this.setState({ endTab: tab }); switch (tab) { case 0: @@ -56,11 +56,11 @@ export class TimeRangeSelector extends Component { } }; - setStartTime = time => { + setStartTime = (time) => { this.props.setStartTime(time); }; - setEndTime = time => { + setEndTime = (time) => { this.props.setEndTime(time); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js index 4f77004b91f99..0a3728c7351b5 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js @@ -20,44 +20,44 @@ export function loadFullJob(jobId) { return new Promise((resolve, reject) => { ml.jobs .jobs(jobId) - .then(jobs => { + .then((jobs) => { if (jobs.length) { resolve(jobs[0]); } else { throw new Error(`Could not find job ${jobId}`); } }) - .catch(error => { + .catch((error) => { reject(error); }); }); } export function isStartable(jobs) { - return jobs.some(j => j.datafeedState === DATAFEED_STATE.STOPPED); + return jobs.some((j) => j.datafeedState === DATAFEED_STATE.STOPPED); } export function isStoppable(jobs) { return jobs.some( - j => j.datafeedState === DATAFEED_STATE.STARTED || j.datafeedState === DATAFEED_STATE.STARTING + (j) => j.datafeedState === DATAFEED_STATE.STARTED || j.datafeedState === DATAFEED_STATE.STARTING ); } export function isClosable(jobs) { return jobs.some( - j => j.datafeedState === DATAFEED_STATE.STOPPED && j.jobState !== JOB_STATE.CLOSED + (j) => j.datafeedState === DATAFEED_STATE.STOPPED && j.jobState !== JOB_STATE.CLOSED ); } export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { - const datafeedIds = jobs.filter(j => j.hasDatafeed).map(j => j.datafeedId); + const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId); mlJobService .forceStartDatafeeds(datafeedIds, start, end) - .then(resp => { + .then((resp) => { showResults(resp, DATAFEED_STATE.STARTED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -71,14 +71,14 @@ export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { } export function stopDatafeeds(jobs, finish = () => {}) { - const datafeedIds = jobs.filter(j => j.hasDatafeed).map(j => j.datafeedId); + const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId); mlJobService .stopDatafeeds(datafeedIds) - .then(resp => { + .then((resp) => { showResults(resp, DATAFEED_STATE.STOPPED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -156,7 +156,7 @@ function showResults(resp, action) { ); if (failures.length > 0) { - failures.forEach(f => { + failures.forEach((f) => { mlMessageBarService.notify.error(f.result.error); toastNotifications.addDanger( i18n.translate('xpack.ml.jobsList.actionFailedNotificationMessage', { @@ -228,14 +228,14 @@ export async function cloneJob(jobId) { } export function closeJobs(jobs, finish = () => {}) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); mlJobService .closeJobs(jobIds) - .then(resp => { + .then((resp) => { showResults(resp, JOB_STATE.CLOSED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -249,14 +249,14 @@ export function closeJobs(jobs, finish = () => {}) { } export function deleteJobs(jobs, finish = () => {}) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); mlJobService .deleteJobs(jobIds) - .then(resp => { + .then((resp) => { showResults(resp, JOB_STATE.DELETED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -284,7 +284,7 @@ export function filterJobs(jobs, clauses) { return p; }, {}); - clauses.forEach(c => { + clauses.forEach((c) => { // the search term could be negated with a minus, e.g. -bananas const bool = c.match === 'must'; let js = []; @@ -295,14 +295,14 @@ export function filterJobs(jobs, clauses) { // if the term has been negated, AND the matches if (bool === true) { js = jobs.filter( - job => + (job) => stringMatch(job.id, c.value) === bool || stringMatch(job.description, c.value) === bool || stringMatch(job.memory_status, c.value) === bool ); } else { js = jobs.filter( - job => + (job) => stringMatch(job.id, c.value) === bool && stringMatch(job.description, c.value) === bool && stringMatch(job.memory_status, c.value) === bool @@ -312,18 +312,18 @@ export function filterJobs(jobs, clauses) { // filter other clauses, i.e. the toggle group buttons if (Array.isArray(c.value)) { // the groups value is an array of group ids - js = jobs.filter(job => jobProperty(job, c.field).some(g => c.value.indexOf(g) >= 0)); + js = jobs.filter((job) => jobProperty(job, c.field).some((g) => c.value.indexOf(g) >= 0)); } else { - js = jobs.filter(job => jobProperty(job, c.field) === c.value); + js = jobs.filter((job) => jobProperty(job, c.field) === c.value); } } - js.forEach(j => matches[j.id].count++); + js.forEach((j) => matches[j.id].count++); }); // loop through the matches and return only those jobs which have match all the clauses const filteredJobs = []; - each(matches, m => { + each(matches, (m) => { if (m.count >= clauses.length) { filteredJobs.push(m.job); } @@ -369,7 +369,7 @@ function jobProperty(job, prop) { function getUrlVars(url) { const vars = {}; - url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(_, key, value) { + url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (_, key, value) { vars[key] = value; }); return vars; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx index 103db5707eed5..d738c8aa3d615 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx @@ -18,7 +18,7 @@ interface JobsPageProps { lastRefresh?: number; } -export const JobsPage: FC = props => { +export const JobsPage: FC = (props) => { return (
diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx index 131e313e7c9e5..06317375d8bc6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx @@ -20,18 +20,18 @@ export interface JobGroupsInputProps { export const JobGroupsInput: FC = memo( ({ existingGroups, selectedGroups, onChange, validation }) => { - const options = existingGroups.map(g => ({ + const options = existingGroups.map((g) => ({ label: g, color: tabColor(g), })); - const selectedOptions = selectedGroups.map(g => ({ + const selectedOptions = selectedGroups.map((g) => ({ label: g, color: tabColor(g), })); function onChangeCallback(optionsIn: EuiComboBoxOptionOption[]) { - onChange(optionsIn.map(g => g.label)); + onChange(optionsIn.map((g) => g.label)); } function onCreateGroup(input: string, flattenedOptions: EuiComboBoxOptionOption[]) { @@ -48,7 +48,7 @@ export const JobGroupsInput: FC = memo( if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { options.push(newGroup); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index 9fa0eb901c61f..ad7197cc2478f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -193,7 +193,7 @@ export class AdvancedJobCreator extends JobCreator { const detectors = getRichDetectors(job, datafeed, this.additionalFields, true); // keep track of the custom rules for each detector - const customRules = this._detectors.map(d => d.custom_rules); + const customRules = this._detectors.map((d) => d.custom_rules); this.removeAllDetectors(); this._richDetectors.length = 0; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index ca982304bd4f3..89a0c45828737 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -617,7 +617,7 @@ export class JobCreator { } if (this._job_config.analysis_config.influencers !== undefined) { - this._job_config.analysis_config.influencers.forEach(i => this.addInfluencer(i)); + this._job_config.analysis_config.influencers.forEach((i) => this.addInfluencer(i)); } if ( @@ -630,7 +630,7 @@ export class JobCreator { this._scriptFields = []; if (this._datafeed_config.script_fields !== undefined) { - this._scriptFields = Object.keys(this._datafeed_config.script_fields).map(f => ({ + this._scriptFields = Object.keys(this._datafeed_config.script_fields).map((f) => ({ id: f, name: f, type: ES_FIELD_TYPES.KEYWORD, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts index 10d306c37d114..95141f31cdea6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts @@ -49,7 +49,7 @@ export class MultiMetricJobCreator extends JobCreator { } public removeSplitField() { - this._detectors.forEach(d => { + this._detectors.forEach((d) => { delete d.partition_field_name; }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts index 276f16c9e76b7..de6cc855e4963 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts @@ -78,7 +78,7 @@ export class PopulationJobCreator extends JobCreator { // remove over field from all detectors public removeSplitField() { - this._detectors.forEach(d => { + this._detectors.forEach((d) => { delete d.over_field_name; }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts index 6d061c2df9ad9..92e65e580fc01 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts @@ -35,7 +35,7 @@ const getFieldByIdFactory = (additionalFields: Field[]) => (id: string) => { if (id === MLCATEGORY) { field = mlCategory; } else if (additionalFields.length) { - field = additionalFields.find(f => f.id === id) || null; + field = additionalFields.find((f) => f.id === id) || null; } } return field; @@ -52,7 +52,7 @@ export function getRichDetectors( const getFieldById = getFieldByIdFactory(additionalFields); - return detectors.map(d => { + return detectors.map((d) => { let field = null; let byField = null; let overField = null; @@ -86,13 +86,13 @@ export function getRichDetectors( export function createFieldOptions(fields: Field[], additionalFields: Field[]) { return [ ...fields - .filter(f => f.id !== EVENT_RATE_FIELD_ID) - .map(f => ({ + .filter((f) => f.id !== EVENT_RATE_FIELD_ID) + .map((f) => ({ label: f.name, })), ...additionalFields - .filter(f => fields.some(f2 => f2.id === f.id) === false) - .map(f => ({ + .filter((f) => fields.some((f2) => f2.id === f.id) === false) + .map((f) => ({ label: f.id, })), ].sort((a, b) => a.label.localeCompare(b.label)); @@ -150,7 +150,7 @@ function getDetectors(job: Job, datafeed: Datafeed) { } else { // all other detectors. detectors = processFieldlessAggs(detectors); - detectors = detectors.map(d => { + detectors = detectors.map((d) => { switch (d.function) { // if sparse data functions were used, replace them with their non-sparse versions // the sparse data flag has already been determined and set, so this information is not being lost. @@ -182,7 +182,7 @@ function getDetectors(job: Job, datafeed: Datafeed) { // if a fieldless function is used, add EVENT_RATE_FIELD_ID as its field function processFieldlessAggs(detectors: Detector[]) { - return detectors.map(d => { + return detectors.map((d) => { switch (d.function) { case ML_JOB_AGGREGATION.COUNT: case ML_JOB_AGGREGATION.HIGH_COUNT: @@ -287,7 +287,7 @@ export function advancedStartDatafeed(jobCreator: JobCreatorType) { } export function aggFieldPairsCanBeCharted(afs: AggFieldPair[]) { - return afs.some(a => a.agg.dslName === null) === false; + return afs.some((a) => a.agg.dslName === null) === false; } export function getJobCreatorTitle(jobCreator: JobCreatorType) { @@ -324,7 +324,7 @@ export function collectAggs(o: any, aggFields: Field[]) { for (const i in o) { if (o[i] !== null && typeof o[i] === 'object') { if (i === 'aggregations' || i === 'aggs') { - Object.keys(o[i]).forEach(k => { + Object.keys(o[i]).forEach((k) => { if (k !== 'aggregations' && k !== 'aggs') { aggFields.push({ id: k, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts index eb563e8b36107..0011c88d2b524 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts @@ -45,7 +45,7 @@ export const modelMemoryEstimatorProvider = ( get updates$(): Observable { return combineLatest([ jobCreator.wizardInitialized$.pipe( - skipWhile(wizardInitialized => wizardInitialized === false) + skipWhile((wizardInitialized) => wizardInitialized === false) ), modelMemoryCheck$, ]).pipe( @@ -58,10 +58,10 @@ export const modelMemoryEstimatorProvider = ( distinctUntilChanged(isEqual), // don't call the endpoint with invalid payload filter(() => jobValidator.isModelMemoryEstimationPayloadValid), - switchMap(payload => { + switchMap((payload) => { return ml.calculateModelMemoryLimit$(payload).pipe( pluck('modelMemoryLimit'), - catchError(error => { + catchError((error) => { // eslint-disable-next-line no-console console.error('Model memory limit could not be calculated', error.body); error$.next(error.body); @@ -115,7 +115,7 @@ export const useModelMemoryEstimator = ( ); subscription.add( - modelMemoryEstimator.error$.subscribe(error => { + modelMemoryEstimator.error$.subscribe((error) => { notifications.toasts.addWarning({ title: i18n.translate('xpack.ml.newJob.wizard.estimateModelMemoryError', { defaultMessage: 'Model memory limit could not be calculated', diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts index 2571fe70f4a83..9afc6e5bfca93 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts @@ -81,7 +81,7 @@ export class JobRunner { // link the _subscribers list from the JobCreator // to the progress BehaviorSubject. const subscriptions = - pollProgress === true ? this._subscribers.map(s => this._progress$.subscribe(s)) : []; + pollProgress === true ? this._subscribers.map((s) => this._progress$.subscribe(s)) : []; await this.openJob(); const { started } = await mlJobService.startDatafeed( @@ -118,7 +118,7 @@ export class JobRunner { // than the end date supplied to the datafeed this._progress$.next(100); // unsubscribe everyone - subscriptions.forEach(s => s.unsubscribe()); + subscriptions.forEach((s) => s.unsubscribe()); } }; // wait for the first check to run and then return success. diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts index a942603d7f9d4..242a643ddd3ce 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts @@ -103,7 +103,7 @@ export class JobValidator { this._asyncValidators$ = [cardinalityValidator(this._jobCreatorSubject$)]; this._asyncValidatorsResult$ = combineLatest(this._asyncValidators$).pipe( - map(res => { + map((res) => { return res.reduce((acc, curr) => { return { ...acc, @@ -124,7 +124,7 @@ export class JobValidator { ...asyncValidatorsResult, }; }), - tap(latestValidationResult => { + tap((latestValidationResult) => { this.latestValidationResult = latestValidationResult; }) ); @@ -168,7 +168,7 @@ export class JobValidator { private _resetBasicValidations() { this._validationSummary.basic = true; - Object.values(this._basicValidations).forEach(v => { + Object.values(this._basicValidations).forEach((v) => { v.valid = true; delete v.message; }); @@ -214,7 +214,7 @@ export class JobValidator { } private _isOverallBasicValid() { - return Object.values(this._basicValidations).some(v => v.valid === false) === false; + return Object.values(this._basicValidations).some((v) => v.valid === false) === false; } public get validationSummary(): ValidationSummary { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts index 2ab58714830e3..d5cc1cf535a78 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts @@ -189,16 +189,16 @@ export function checkForExistingJobAndGroupIds( } // check that groups that have been newly added in this job do not already exist as job ids - const newGroups = groupIds.filter(g => !existingJobsAndGroups.groupIds.includes(g)); - if (existingJobsAndGroups.jobIds.some(g => newGroups.includes(g))) { + const newGroups = groupIds.filter((g) => !existingJobsAndGroups.groupIds.includes(g)); + if (existingJobsAndGroups.jobIds.some((g) => newGroups.includes(g))) { messages.push({ id: 'job_group_id_already_exists' }); } return { messages, valid: messages.length === 0, - contains: (id: string) => messages.some(m => id === m.id), - find: (id: string) => messages.find(m => id === m.id), + contains: (id: string) => messages.some((m) => id === m.id), + find: (id: string) => messages.find((m) => id === m.id), }; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts index ea7ba21699f60..eabf5588579c5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts @@ -41,10 +41,10 @@ export function cardinalityValidator( ): Observable { return jobCreator$.pipe( // Perform a cardinality check only with enabled model plot. - filter(jobCreator => { + filter((jobCreator) => { return jobCreator?.modelPlot; }), - map(jobCreator => { + map((jobCreator) => { return { jobCreator, analysisConfigString: JSON.stringify(jobCreator.jobConfig.analysis_config), @@ -60,7 +60,7 @@ export function cardinalityValidator( datafeed_config: jobCreator.datafeedConfig, } as CombinedJob); }), - map(validationResults => { + map((validationResults) => { for (const validationResult of validationResults) { if (isCardinalityModelPlotHigh(validationResult)) { return { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts index 5048f44586a38..110b031cd1dc0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts @@ -236,7 +236,7 @@ export class ResultsLoader { const anomalies: Record = {}; Object.entries(resp.results).forEach(([dtrIdx, results]) => { anomalies[+dtrIdx] = results.map( - r => ({ ...r, severity: getSeverityType(r.value as number) } as Anomaly) + (r) => ({ ...r, severity: getSeverityType(r.value as number) } as Anomaly) ); }); return anomalies; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx index 1596177daaf03..ab2098ca27135 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx @@ -48,7 +48,7 @@ function splitAnomalySeverities(anomalies: Anomaly[]) { unknown: [], low: [], }; - anomalies.forEach(a => { + anomalies.forEach((a) => { if (a.value !== 0) { severities[a.severity].push({ dataValue: a.time }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx index 54fb19d868cdc..3909a7a31fb2f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx @@ -44,7 +44,7 @@ export const ModelMemoryLimitInput: FC = () => { setModelMemoryLimit(e.target.value)} + onChange={(e) => setModelMemoryLimit(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputModelMemoryLimit" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx index 6328366626894..7a75a17a870c9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx @@ -50,7 +50,7 @@ export const FrequencyInput: FC = () => { setFrequency(e.target.value)} + onChange={(e) => setFrequency(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputFrequency" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx index 0e6dd81fb91a9..22573fb215cea 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx @@ -36,7 +36,7 @@ export const QueryDelayInput: FC = () => { setQueryDelay(e.target.value)} + onChange={(e) => setQueryDelay(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputQueryDelay" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx index ea03d16fcccca..508811731ae3e 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx @@ -41,7 +41,7 @@ export const ScrollSizeInput: FC = () => { min={0} placeholder={scrollSizeDefault} value={scrollSizeString === '' ? scrollSizeString : +scrollSizeString} - onChange={e => setScrollSize(e.target.value)} + onChange={(e) => setScrollSize(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputScrollSize" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx index 597fe42543301..60b034b516939 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx @@ -37,10 +37,10 @@ export const CalendarsSelection: FC = () => { async function loadCalendars() { setIsLoading(true); const calendars = (await ml.calendars()).filter( - c => c.job_ids.includes(GLOBAL_CALENDAR) === false + (c) => c.job_ids.includes(GLOBAL_CALENDAR) === false ); - setOptions(calendars.map(c => ({ label: c.calendar_id, value: c }))); - setSelectedOptions(selectedCalendars.map(c => ({ label: c.calendar_id, value: c }))); + setOptions(calendars.map((c) => ({ label: c.calendar_id, value: c }))); + setSelectedOptions(selectedCalendars.map((c) => ({ label: c.calendar_id, value: c }))); setIsLoading(false); } @@ -58,9 +58,9 @@ export const CalendarsSelection: FC = () => { options, selectedOptions, isLoading, - onChange: optionsIn => { + onChange: (optionsIn) => { setSelectedOptions(optionsIn); - setSelectedCalendars(optionsIn.map(o => o.value!)); + setSelectedCalendars(optionsIn.map((o) => o.value!)); }, }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx index a034bdcc2900f..b63f3004efdc5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx @@ -29,7 +29,7 @@ export const ModelPlotSwitch: FC = () => { // and a rare detector is being used. const isRareCategoryJob = isCategorizationJobCreator(jobCreator) && - jobCreator.aggregations.some(agg => aggs.includes(agg.id)); + jobCreator.aggregations.some((agg) => aggs.includes(agg.id)); setEnabled(isRareCategoryJob === false); }, [jobCreatorUpdated]); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx index 841ccfdce0958..a693127e07f48 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx @@ -35,7 +35,7 @@ export const GroupsInput: FC = () => { })); function onChange(optionsIn: EuiComboBoxOptionOption[]) { - setSelectedGroups(optionsIn.map(g => g.label)); + setSelectedGroups(optionsIn.map((g) => g.label)); } function onCreateGroup(input: string, flattenedOptions: EuiComboBoxOptionOption[]) { @@ -52,13 +52,13 @@ export const GroupsInput: FC = () => { if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { options.push(newGroup); } - setSelectedGroups([...selectedOptions, newGroup].map(g => g.label)); + setSelectedGroups([...selectedOptions, newGroup].map((g) => g.label)); } useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx index 1c027b6c81ff9..bfddae0e79ea1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx @@ -22,7 +22,7 @@ export const JobDescriptionInput: FC = () => { setJobDescription(e.target.value)} + onChange={(e) => setJobDescription(e.target.value)} data-test-subj="mlJobWizardInputJobDescription" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx index c77024a4d329f..43468d83844ed 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx @@ -33,7 +33,7 @@ export const JobIdInput: FC = () => { setJobId(e.target.value)} + onChange={(e) => setJobId(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputJobId" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index 9e784a20c4f5f..7d71583977204 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -91,7 +91,7 @@ export const AdvancedDetectorModal: FC = ({ // list of aggregation combobox options. const aggOptions: EuiComboBoxOptionOption[] = aggs - .filter(agg => filterAggs(agg, usingScriptFields)) + .filter((agg) => filterAggs(agg, usingScriptFields)) .map(createAggOption); // fields available for the selected agg @@ -110,7 +110,7 @@ export const AdvancedDetectorModal: FC = ({ ...createMlcategoryFieldOption(jobCreator.categorizationFieldName), ].sort(comboBoxOptionsSort); - const eventRateField = fields.find(f => f.id === EVENT_RATE_FIELD_ID); + const eventRateField = fields.find((f) => f.id === EVENT_RATE_FIELD_ID); const onOptionChange = (func: (p: EuiComboBoxOptionOption) => any) => ( selectedOptions: EuiComboBoxOptionOption[] @@ -119,15 +119,15 @@ export const AdvancedDetectorModal: FC = ({ }; function getAgg(title: string) { - return aggs.find(a => a.id === title) || null; + return aggs.find((a) => a.id === title) || null; } function getField(title: string) { if (title === mlCategory.id) { return mlCategory; } return ( - fields.find(f => f.id === title) || - jobCreator.additionalFields.find(f => f.id === title) || + fields.find((f) => f.id === title) || + jobCreator.additionalFields.find((f) => f.id === title) || null ); } @@ -301,7 +301,7 @@ export const AdvancedDetectorModal: FC = ({ fullWidth={true} placeholder={descriptionPlaceholder} value={descriptionOption} - onChange={e => setDescriptionOption(e.target.value)} + onChange={(e) => setDescriptionOption(e.target.value)} data-test-subj="mlAdvancedDetectorDescriptionInput" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx index e4eccb5f01423..7f108da217035 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx @@ -42,20 +42,20 @@ export const AggSelect: FC = ({ fields, changeHandler, selectedOptions, r // so they can be removed from the dropdown list const removeLabels = removeOptions.map(createLabel); - const options: EuiComboBoxOptionOption[] = fields.map(f => { + const options: EuiComboBoxOptionOption[] = fields.map((f) => { const aggOption: DropDownOption = { label: f.name, options: [] }; if (typeof f.aggs !== 'undefined') { aggOption.options = f.aggs - .filter(a => a.dslName !== null) // don't include aggs which have no ES equivalent + .filter((a) => a.dslName !== null) // don't include aggs which have no ES equivalent .map( - a => + (a) => ({ label: `${a.title}(${f.name})`, agg: a, field: f, } as DropDownLabel) ) - .filter(o => removeLabels.includes(o.label) === false); + .filter((o) => removeLabels.includes(o.label) === false); } return aggOption; }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx index 35c1cfa9ce65d..740a8614ee205 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx @@ -23,7 +23,7 @@ export const BucketSpanInput: FC = ({ bucketSpan, setBucketSpan, isInvali defaultMessage: 'Bucket span', })} value={bucketSpan} - onChange={e => setBucketSpan(e.target.value)} + onChange={(e) => setBucketSpan(e.target.value)} isInvalid={isInvalid} data-test-subj="mlJobWizardInputBucketSpan" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx index 72ebbb0b438a2..2be0f67f3944f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx @@ -35,7 +35,7 @@ export const BucketSpanEstimator: FC = ({ setEstimating }) => { function checkIsUsingMlCategory() { return ( isAdvancedJobCreator(jobCreator) && - jobCreator.detectors.some(d => { + jobCreator.detectors.some((d) => { if ( d.partition_field_name === MLCATEGORY || d.over_field_name === MLCATEGORY || diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index 5064ba9df9bee..0ec3b609b604f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -29,12 +29,12 @@ export function useEstimateBucketSpan() { const [status, setStatus] = useState(ESTIMATE_STATUS.NOT_RUNNING); const data: BucketSpanEstimatorData = { - aggTypes: jobCreator.aggregations.map(a => a.dslName), + aggTypes: jobCreator.aggregations.map((a) => a.dslName), duration: { start: jobCreator.start, end: jobCreator.end, }, - fields: jobCreator.fields.map(f => (f.id === EVENT_RATE_FIELD_ID ? null : f.id)), + fields: jobCreator.fields.map((f) => (f.id === EVENT_RATE_FIELD_ID ? null : f.id)), index: mlContext.currentIndexPattern.title, query: mlContext.combinedQuery, splitField: undefined, @@ -47,7 +47,7 @@ export function useEstimateBucketSpan() { ) { data.splitField = jobCreator.splitField.id; } else if (isAdvancedJobCreator(jobCreator)) { - jobCreator.richDetectors.some(d => { + jobCreator.richDetectors.some((d) => { if (d.partitionField !== null) { data.splitField = d.partitionField.id; return true; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx index f139a8013725a..0ca8320eec859 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx @@ -123,7 +123,7 @@ const AllValidationChecks: FC<{ validationChecks: FieldExampleCheck[] }> = ({ validationChecks, }) => { const list: EuiListGroupItemProps[] = Object.keys(VALIDATION_CHECK_DESCRIPTION).map((k, i) => { - const failedCheck = validationChecks.find(vc => vc.id === i); + const failedCheck = validationChecks.find((vc) => vc.id === i); if ( failedCheck !== undefined && failedCheck?.valid !== CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx index 227c93dc2d86b..07ae18ae2f810 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx @@ -27,7 +27,7 @@ export const TopCategories: FC = () => { async function loadTopCats() { const results = await ml.jobs.topCategories(jobCreator.jobId, NUMBER_OF_CATEGORY_EXAMPLES); setTableRow( - results.categories.map(c => ({ + results.categories.map((c) => ({ count: c.count, example: c.category.examples?.length ? c.category.examples[0] : '', })) diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx index c55bdeef4dde8..f80827da03a19 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx @@ -24,7 +24,7 @@ export const Influencers: FC = () => { useEffect(() => { jobCreator.removeAllInfluencers(); - influencers.forEach(i => jobCreator.addInfluencer(i)); + influencers.forEach((i) => jobCreator.addInfluencer(i)); jobCreatorUpdate(); }, [influencers.join()]); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx index 25c924ee0b42f..f3e2e22c871e6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx @@ -27,10 +27,10 @@ export const InfluencersSelect: FC = ({ fields, changeHandler, selectedIn ...createMlcategoryFieldOption(jobCreator.categorizationFieldName), ]; - const selection: EuiComboBoxOptionOption[] = selectedInfluencers.map(i => ({ label: i })); + const selection: EuiComboBoxOptionOption[] = selectedInfluencers.map((i) => ({ label: i })); function onChange(selectedOptions: EuiComboBoxOptionOption[]) { - changeHandler(selectedOptions.map(o => o.label)); + changeHandler(selectedOptions.map((o) => o.label)); } return ( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx index cbd7c0ab72ffc..684cb5b4e0dda 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx @@ -76,7 +76,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { // watch for changes in detector list length useEffect(() => { jobCreator.removeAllDetectors(); - aggFieldPairList.forEach(pair => { + aggFieldPairList.forEach((pair) => { jobCreator.addDetector(pair.agg, pair.field); }); jobCreatorUpdate(); @@ -108,7 +108,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { chartLoader .loadFieldExampleValues(splitField) .then(setFieldValues) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); }); } else { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx index 70a3d1c7d616c..e5f5ba48900d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx @@ -49,7 +49,7 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { const [splitField, setSplitField] = useState(jobCreator.splitField); const [fieldValuesPerDetector, setFieldValuesPerDetector] = useState({}); const [byFieldsUpdated, setByFieldsUpdated] = useReducer<(s: number, action: any) => number>( - s => s + 1, + (s) => s + 1, 0 ); const [pageReady, setPageReady] = useState(false); @@ -203,7 +203,7 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { function allDataReady() { let ready = aggFieldPairList.length > 0; - aggFieldPairList.forEach(af => { + aggFieldPairList.forEach((af) => { if (af.by !== undefined && af.by.field !== null) { // if a by field is set, it's only ready when the value is loaded ready = ready && af.by.value !== null; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx index 4474a2d6b5413..06f7092e8ac06 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx @@ -125,7 +125,7 @@ export const PopulationDetectorsSummary: FC = () => { function allDataReady() { let ready = aggFieldPairList.length > 0; - aggFieldPairList.forEach(af => { + aggFieldPairList.forEach((af) => { if (af.by !== undefined && af.by.field !== null) { // if a by field is set, it's only ready when the value is loaded ready = ready && af.by.value !== null; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx index 2884bce4d89ad..faa505fae22a1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx @@ -24,7 +24,7 @@ export const SparseDataSwitch: FC = () => { useEffect(() => { const aggs = [ES_AGGREGATION.COUNT, ES_AGGREGATION.SUM]; const isCountOrSum = jobCreator.aggregations.some( - agg => agg.dslName !== null && aggs.includes(agg.dslName) + (agg) => agg.dslName !== null && aggs.includes(agg.dslName) ); setEnabled(isCountOrSum); if (isCountOrSum === false && sparseData === true) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx index 118923aa203e1..184a851a8d078 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx @@ -48,7 +48,7 @@ export const SplitCards: FC = memo( if (animate === true) { setTimeout(() => { - panels.forEach(p => (p.panel.style.marginBottom = `${p.marginBottom}px`)); + panels.forEach((p) => (p.panel.style.marginBottom = `${p.marginBottom}px`)); }, 100); } @@ -68,7 +68,7 @@ export const SplitCards: FC = memo( ...(animate ? { transition: 'margin 0.5s' } : {}), }; return ( -
storePanels(ref, marginBottom)} style={style}> +
storePanels(ref, marginBottom)} style={style}> { const sf = jobCreator.splitField; if (sf !== null) { - setFields(allCategoryFields.filter(f => f.name !== sf.name)); + setFields(allCategoryFields.filter((f) => f.name !== sf.name)); } else { setFields(allCategoryFields); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx index 816614fb2a772..af9644f4770d3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx @@ -32,7 +32,7 @@ export const SplitFieldSelect: FC = ({ placeholder, }) => { const options: EuiComboBoxOptionOption[] = fields.map( - f => + (f) => ({ label: f.name, field: f, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx index bfb34b977ec97..2e1a187daa736 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx @@ -43,14 +43,14 @@ export const Wizard: FC = ({ firstWizardStep = WIZARD_STEPS.TIME_RANGE, }) => { const [jobCreatorUpdated, setJobCreatorUpdate] = useReducer<(s: number, action: any) => number>( - s => s + 1, + (s) => s + 1, 0 ); const jobCreatorUpdate = () => setJobCreatorUpdate(jobCreatorUpdated); const [jobValidatorUpdated, setJobValidatorUpdate] = useReducer< (s: number, action: any) => number - >(s => s + 1, 0); + >((s) => s + 1, 0); const jobCreatorContext: JobCreatorContextValue = { jobCreatorUpdated, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx index 0dd222a1726ef..433327497fe05 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx @@ -51,8 +51,8 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, const handleValidation = () => { const jobGroupsValidationResult = formState.jobGroups - .map(group => groupValidator(group)) - .filter(result => result !== null); + .map((group) => groupValidator(group)) + .filter((result) => result !== null); setValidationResult({ jobGroups: jobGroupsValidationResult, @@ -92,7 +92,7 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, { + onChange={(value) => { setFormState({ jobGroups: value, }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index 2a15a42ba04f8..8dab25bf492f4 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -85,7 +85,7 @@ export const JobItem: FC = memo( - {jobGroups.map(group => ( + {jobGroups.map((group) => ( {group} diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx index bae9c592b94c4..63dec536ea487 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx @@ -195,7 +195,7 @@ export const JobSettingsForm: FC = ({ <> { + setTimeRange={(value) => { setFormState({ timeRange: value, }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx index 50c35ec426acb..da1bbbc7ae67c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx @@ -113,7 +113,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { setSaveState(SAVE_STATE.NOT_SAVED); // mix existing groups from the server with the groups used across all jobs in the module. - const moduleGroups = [...response.jobs.map(j => j.config.groups || [])].flat(); + const moduleGroups = [...response.jobs.map((j) => j.config.groups || [])].flat(); setExistingGroups([...new Set([...existingGroups, ...moduleGroups])]); } catch (e) { // eslint-disable-next-line no-console @@ -176,7 +176,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { const { datafeeds: datafeedsResponse, jobs: jobsResponse, kibana: kibanaResponse } = response; setJobs( - jobs.map(job => { + jobs.map((job) => { return { ...job, datafeedResult: datafeedsResponse.find(({ id }) => id.endsWith(job.id)), @@ -297,7 +297,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { {isFormVisible && ( { + onChange={(formValues) => { setJobPrefix(formValues.jobPrefix); }} saveState={saveState} diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts index 9c60b84b16bdf..e3b0fd4cefe0c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts @@ -66,8 +66,8 @@ export const checkForSavedObjects = async (objects: KibanaObjects): Promise { - const find = savedObjects.find(savedObject => savedObject.attributes.title === obj.title); + acc[type] = objects[type].map((obj) => { + const find = savedObjects.find((savedObject) => savedObject.attributes.title === obj.title); return { ...obj, exists: !!find, diff --git a/x-pack/plugins/ml/public/application/management/index.ts b/x-pack/plugins/ml/public/application/management/index.ts index f15cdb12afb21..480e2fe488980 100644 --- a/x-pack/plugins/ml/public/application/management/index.ts +++ b/x-pack/plugins/ml/public/application/management/index.ts @@ -28,7 +28,7 @@ export function initManagementSection( core: CoreSetup ) { const licensing = pluginsSetup.licensing.license$.pipe(take(1)); - licensing.subscribe(license => { + licensing.subscribe((license) => { const management = pluginsSetup.management; if ( management !== undefined && diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx index dac39b1a2071d..03b66f5c369c1 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx @@ -43,7 +43,7 @@ const createJobLink = '#/jobs/new_job/step/index_or_search'; function getDefaultAnomalyScores(groups: Group[]): MaxScoresByGroup { const anomalyScores: MaxScoresByGroup = {}; - groups.forEach(group => { + groups.forEach((group) => { anomalyScores[group.id] = { maxScore: 0 }; }); @@ -96,7 +96,7 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { try { const promises = groupsList - .filter(group => group.jobIds.length > 0) + .filter((group) => group.jobIds.length > 0) .map((group, i) => { scores[group.id].index = i; const latestTimestamp = group.latest_timestamp; @@ -108,7 +108,7 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { const results = await Promise.all(promises); const tempGroups = { ...groupsObject }; // Check results for each group's promise index and update state - Object.keys(scores).forEach(groupId => { + Object.keys(scores).forEach((groupId) => { const resultsIndex = scores[groupId] && scores[groupId].index; // maxScore will be null if it was not loaded correctly const { maxScore } = resultsIndex !== undefined && results[resultsIndex]; diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts index b030a1ef45ab0..5372862219a89 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts @@ -156,7 +156,7 @@ export function getStatsBarData(jobsList: any) { } export function getJobsFromGroup(group: Group, jobs: any) { - return group.jobIds.map(jobId => jobs[jobId]).filter(id => id !== undefined); + return group.jobIds.map((jobId) => jobs[jobId]).filter((id) => id !== undefined); } export function getJobsWithTimerange(jobsList: any) { diff --git a/x-pack/plugins/ml/public/application/routing/router.tsx b/x-pack/plugins/ml/public/application/routing/router.tsx index f4d6fec5e6ee3..281493c4e31b7 100644 --- a/x-pack/plugins/ml/public/application/routing/router.tsx +++ b/x-pack/plugins/ml/public/application/routing/router.tsx @@ -54,7 +54,7 @@ export const MlRouter: FC<{ pageDeps: PageDependencies }> = ({ pageDeps }) => { key={name} path={route.path} exact - render={props => { + render={(props) => { window.setTimeout(() => { setBreadcrumbs(route.breadcrumbs); }); diff --git a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx index a41a6c83615d3..fdf29406893ad 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx @@ -230,7 +230,7 @@ export const TimeSeriesExplorerUrlStateManager: FC { + .then((resp) => { if (autoZoomDuration === undefined) { return; } @@ -248,7 +248,7 @@ export const TimeSeriesExplorerUrlStateManager: FC { + .catch((resp) => { // eslint-disable-next-line no-console console.error( 'Time series explorer - error loading time range of forecast from elasticsearch:', diff --git a/x-pack/plugins/ml/public/application/routing/use_refresh.ts b/x-pack/plugins/ml/public/application/routing/use_refresh.ts index f9f3bb66f14f3..f0b93c876526b 100644 --- a/x-pack/plugins/ml/public/application/routing/use_refresh.ts +++ b/x-pack/plugins/ml/public/application/routing/use_refresh.ts @@ -22,7 +22,7 @@ export interface Refresh { const refresh$: Observable = merge( mlTimefilterRefresh$, mlTimefilterTimeChange$, - annotationsRefresh$.pipe(map(d => ({ lastRefresh: d }))) + annotationsRefresh$.pipe(map((d) => ({ lastRefresh: d }))) ); export const useRefresh = () => { diff --git a/x-pack/plugins/ml/public/application/routing/use_resolver.ts b/x-pack/plugins/ml/public/application/routing/use_resolver.ts index 8e94f8d77fbb2..4967e3a684a6b 100644 --- a/x-pack/plugins/ml/public/application/routing/use_resolver.ts +++ b/x-pack/plugins/ml/public/application/routing/use_resolver.ts @@ -38,7 +38,7 @@ export const useResolver = ( useEffect(() => { (async () => { try { - const res = await Promise.all(funcs.map(r => r())); + const res = await Promise.all(funcs.map((r) => r())); res.forEach((r, i) => (tempResults[funcNames[i]] = r)); setResults(tempResults); } catch (error) { diff --git a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts index 26fcc25492612..6381f1f8eae89 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts @@ -24,7 +24,7 @@ export class AnomalyDetectorService { .http$<{ count: number; jobs: Job[] }>({ path: `${this.apiBasePath}/${jobId}`, }) - .pipe(map(response => response.jobs[0])); + .pipe(map((response) => response.jobs[0])); } /** @@ -36,7 +36,7 @@ export class AnomalyDetectorService { .http$<{ count: number; jobs: Job[] }>({ path: `${this.apiBasePath}/${jobIds.join(',')}`, }) - .pipe(map(response => response.jobs)); + .pipe(map((response) => response.jobs)); } /** diff --git a/x-pack/plugins/ml/public/application/services/explorer_service.ts b/x-pack/plugins/ml/public/application/services/explorer_service.ts index 8914fd17d1226..efcec8cf2b954 100644 --- a/x-pack/plugins/ml/public/application/services/explorer_service.ts +++ b/x-pack/plugins/ml/public/application/services/explorer_service.ts @@ -96,7 +96,7 @@ export class ExplorerService { // Ensure the search bounds align to the bucketing interval used in the swimlane so // that the first and last buckets are complete. const searchBounds = getBoundsRoundedToInterval(bounds, interval, false); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Load the overall bucket scores by time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -152,7 +152,7 @@ export class ExplorerService { false ); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // load scores by influencer/jobId value and time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets // which wouldn't be the case if e.g. '1M' was used. diff --git a/x-pack/plugins/ml/public/application/services/field_format_service.ts b/x-pack/plugins/ml/public/application/services/field_format_service.ts index 343dc2ea564ba..1a5d22e7320a5 100644 --- a/x-pack/plugins/ml/public/application/services/field_format_service.ts +++ b/x-pack/plugins/ml/public/application/services/field_format_service.ts @@ -30,7 +30,7 @@ class FieldFormatService { // pattern with a title attribute which matches the index configured in the datafeed. // If a Kibana index pattern has not been created // for this index, then no custom field formatting will occur. - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { const jobObj = mlJobService.getJob(jobId); const datafeedIndices = jobObj.datafeed_config.indices; const id = getIndexPatternIdFromName(datafeedIndices.length ? datafeedIndices[0] : ''); @@ -39,17 +39,17 @@ class FieldFormatService { } }); - const promises = jobIds.map(jobId => Promise.all([this.getFormatsForJob(jobId)])); + const promises = jobIds.map((jobId) => Promise.all([this.getFormatsForJob(jobId)])); Promise.all(promises) - .then(fmtsByJobByDetector => { + .then((fmtsByJobByDetector) => { fmtsByJobByDetector.forEach((formatsByDetector, i) => { this.formatsByJob[jobIds[i]] = formatsByDetector[0]; }); resolve(this.formatsByJob); }) - .catch(err => { + .catch((err) => { reject({ formats: {}, err }); }); }); @@ -94,10 +94,10 @@ class FieldFormatService { if (indexPatternId !== undefined) { // Load the full index pattern configuration to obtain the formats of each field. getIndexPatternById(indexPatternId) - .then(indexPatternData => { + .then((indexPatternData) => { // Store the FieldFormat for each job by detector_index. const fieldList = indexPatternData.fields; - detectors.forEach(dtr => { + detectors.forEach((dtr) => { const esAgg = mlFunctionToESAggregation(dtr.function); // distinct_count detectors should fall back to the default // formatter as the values are just counts. @@ -111,7 +111,7 @@ class FieldFormatService { resolve(formatsByDetector); }) - .catch(err => { + .catch((err) => { reject(err); }); } else { diff --git a/x-pack/plugins/ml/public/application/services/forecast_service.js b/x-pack/plugins/ml/public/application/services/forecast_service.js index 5c51839b012bd..c3d593c3347df 100644 --- a/x-pack/plugins/ml/public/application/services/forecast_service.js +++ b/x-pack/plugins/ml/public/application/services/forecast_service.js @@ -61,14 +61,14 @@ function getForecastsSummary(job, query, earliestMs, maxResults) { sort: [{ forecast_create_timestamp: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - obj.forecasts = resp.hits.hits.map(hit => hit._source); + obj.forecasts = resp.hits.hits.map((hit) => hit._source); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -129,7 +129,7 @@ function getForecastDateRange(job, forecastId) { }, }, }) - .then(resp => { + .then((resp) => { obj.earliest = _.get(resp, 'aggregations.earliest.value', null); obj.latest = _.get(resp, 'aggregations.latest.value', null); if (obj.earliest === null || obj.latest === null) { @@ -138,7 +138,7 @@ function getForecastDateRange(job, forecastId) { resolve(obj); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -223,7 +223,7 @@ function getForecastData( ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { filterCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -282,9 +282,9 @@ function getForecastData( }, }) .pipe( - map(resp => { + map((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, dataForTime => { + _.each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { prediction: _.get(dataForTime, ['prediction', 'value']), @@ -306,10 +306,10 @@ function runForecast(jobId, duration) { jobId, duration, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { reject(err); }); }); @@ -355,13 +355,13 @@ function getForecastRequestStats(job, forecastId) { }, }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { obj.stats = _.first(resp.hits.hits)._source; } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/services/http_service.ts b/x-pack/plugins/ml/public/application/services/http_service.ts index ff60c67b3c9e6..34dc89dd5f89b 100644 --- a/x-pack/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/plugins/ml/public/application/services/http_service.ts @@ -56,7 +56,7 @@ export function http$(options: HttpFetchOptionsWithPath): Observable { * Creates an Observable from Kibana's HttpHandler. */ export function fromHttpHandler(input: string, init?: RequestInit): Observable { - return new Observable(subscriber => { + return new Observable((subscriber) => { const controller = new AbortController(); const signal = controller.signal; @@ -82,12 +82,12 @@ export function fromHttpHandler(input: string, init?: RequestInit): Observabl getHttp() .fetch(input, perSubscriberInit) - .then(response => { + .then((response) => { abortable = false; subscriber.next(response); subscriber.complete(); }) - .catch(err => { + .catch((err) => { abortable = false; if (!unsubscribed) { subscriber.error(err); @@ -139,7 +139,7 @@ export class HttpService { * Creates an Observable from Kibana's HttpHandler. */ private fromHttpHandler(input: string, init?: RequestInit): Observable { - return new Observable(subscriber => { + return new Observable((subscriber) => { const controller = new AbortController(); const signal = controller.signal; @@ -165,12 +165,12 @@ export class HttpService { this.httpStart .fetch(input, perSubscriberInit) - .then(response => { + .then((response) => { abortable = false; subscriber.next(response); subscriber.complete(); }) - .catch(err => { + .catch((err) => { abortable = false; if (!unsubscribed) { subscriber.error(err); diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index fb75476c48fa3..8d59270b36dae 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -114,12 +114,12 @@ class JobService { datafeedIds = {}; ml.getJobs() - .then(resp => { + .then((resp) => { jobs = resp.jobs; // load jobs stats ml.getJobStats() - .then(statsResp => { + .then((statsResp) => { // merge jobs stats into jobs for (let i = 0; i < jobs.length; i++) { const job = jobs[i]; @@ -143,7 +143,7 @@ class JobService { } } } - this.loadDatafeeds().then(datafeedsResp => { + this.loadDatafeeds().then((datafeedsResp) => { for (let i = 0; i < jobs.length; i++) { for (let j = 0; j < datafeedsResp.datafeeds.length; j++) { if (jobs[i].job_id === datafeedsResp.datafeeds[j].job_id) { @@ -159,11 +159,11 @@ class JobService { resolve({ jobs: this.jobs }); }); }) - .catch(err => { + .catch((err) => { error(err); }); }) - .catch(err => { + .catch((err) => { error(err); }); @@ -182,10 +182,10 @@ class JobService { loadJobsWrapper = () => { return this.loadJobs() - .then(function(resp) { + .then(function (resp) { return resp; }) - .catch(function(error) { + .catch(function (error) { console.log('Error loading jobs in route resolve.', error); // Always resolve to ensure tab still works. Promise.resolve([]); @@ -195,13 +195,13 @@ class JobService { refreshJob(jobId) { return new Promise((resolve, reject) => { ml.getJobs({ jobId }) - .then(resp => { + .then((resp) => { if (resp.jobs && resp.jobs.length) { const newJob = resp.jobs[0]; // load jobs stats ml.getJobStats({ jobId }) - .then(statsResp => { + .then((statsResp) => { // merge jobs stats into jobs for (let j = 0; j < statsResp.jobs.length; j++) { if (newJob.job_id === statsResp.jobs[j].job_id) { @@ -230,7 +230,7 @@ class JobService { const datafeedId = this.getDatafeedId(jobId); - this.loadDatafeeds(datafeedId).then(datafeedsResp => { + this.loadDatafeeds(datafeedId).then((datafeedsResp) => { for (let i = 0; i < jobs.length; i++) { for (let j = 0; j < datafeedsResp.datafeeds.length; j++) { if (jobs[i].job_id === datafeedsResp.datafeeds[j].job_id) { @@ -245,12 +245,12 @@ class JobService { resolve({ jobs: this.jobs }); }); }) - .catch(err => { + .catch((err) => { error(err); }); } }) - .catch(err => { + .catch((err) => { error(err); }); @@ -272,7 +272,7 @@ class JobService { const sId = datafeedId !== undefined ? { datafeed_id: datafeedId } : undefined; ml.getDatafeeds(sId) - .then(resp => { + .then((resp) => { // console.log('loadDatafeeds query response:', resp); // make deep copy of datafeeds @@ -280,7 +280,7 @@ class JobService { // load datafeeds stats ml.getDatafeedStats() - .then(statsResp => { + .then((statsResp) => { // merge datafeeds stats into datafeeds for (let i = 0; i < datafeeds.length; i++) { const datafeed = datafeeds[i]; @@ -292,11 +292,11 @@ class JobService { } resolve({ datafeeds }); }) - .catch(err => { + .catch((err) => { error(err); }); }) - .catch(err => { + .catch((err) => { error(err); }); @@ -318,7 +318,7 @@ class JobService { const datafeedId = this.getDatafeedId(jobId); ml.getDatafeedStats({ datafeedId }) - .then(resp => { + .then((resp) => { // console.log('updateSingleJobCounts controller query response:', resp); const datafeeds = resp.datafeeds; let state = 'UNKNOWN'; @@ -327,7 +327,7 @@ class JobService { } resolve(state); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -342,10 +342,7 @@ class JobService { } // return the promise chain - return ml - .addJob({ jobId: job.job_id, job }) - .then(func) - .catch(func); + return ml.addJob({ jobId: job.job_id, job }).then(func).catch(func); } cloneJob(job) { @@ -374,7 +371,7 @@ class JobService { delete tempJob.analysis_config.use_per_partition_normalization; - _.each(tempJob.analysis_config.detectors, d => { + _.each(tempJob.analysis_config.detectors, (d) => { delete d.detector_index; }); @@ -414,11 +411,11 @@ class JobService { // return the promise chain return ml .updateJob({ jobId, job }) - .then(resp => { + .then((resp) => { console.log('update job', resp); return { success: true }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotUpdateJobErrorMessage', { defaultMessage: 'Could not update job: {jobId}', @@ -434,10 +431,10 @@ class JobService { // return the promise chain return ml .validateJob(obj) - .then(messages => { + .then((messages) => { return { success: true, messages }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.jobValidationErrorMessage', { defaultMessage: 'Job Validation Error: {errorMessage}', @@ -459,7 +456,7 @@ class JobService { // find a job based on the id getJob(jobId) { - const job = _.find(jobs, j => { + const job = _.find(jobs, (j) => { return j.job_id === jobId; }); @@ -491,7 +488,7 @@ class JobService { timeFieldName: job.data_description.time_field, query, }) - .then(timeRange => { + .then((timeRange) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); const earliestMs = timeRange.start.epoch; const latestMs = +timeRange.start.epoch + 10 * bucketSpan.asMilliseconds(); @@ -540,7 +537,7 @@ class JobService { // get fields from detectors if (job.analysis_config.detectors) { - _.each(job.analysis_config.detectors, dtr => { + _.each(job.analysis_config.detectors, (dtr) => { if (dtr.by_field_name) { fields[dtr.by_field_name] = {}; } @@ -558,7 +555,7 @@ class JobService { // get fields from influencers if (job.analysis_config.influencers) { - _.each(job.analysis_config.influencers, inf => { + _.each(job.analysis_config.influencers, (inf) => { fields[inf] = {}; }); } @@ -592,14 +589,14 @@ class JobService { }; ml.esSearch(data) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } @@ -627,11 +624,11 @@ class JobService { updateDatafeed(datafeedId, datafeedConfig) { return ml .updateDatafeed({ datafeedId, datafeedConfig }) - .then(resp => { + .then((resp) => { console.log('update datafeed', resp); return { success: true }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage', { defaultMessage: 'Could not update datafeed: {datafeedId}', @@ -658,10 +655,10 @@ class JobService { start, end, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { console.log('jobService error starting datafeed:', err); msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotStartDatafeedErrorMessage', { @@ -682,10 +679,10 @@ class JobService { ml.stopDatafeed({ datafeedId, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { console.log('jobService error stopping datafeed:', err); const couldNotStopDatafeedErrorMessage = i18n.translate( 'xpack.ml.jobService.couldNotStopDatafeedErrorMessage', @@ -731,10 +728,10 @@ class JobService { return new Promise((resolve, reject) => { if (detector) { ml.validateDetector({ detector }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } else { @@ -759,9 +756,9 @@ class JobService { getJobGroups() { const groups = []; const tempGroups = {}; - this.jobs.forEach(job => { + this.jobs.forEach((job) => { if (Array.isArray(job.groups)) { - job.groups.forEach(group => { + job.groups.forEach((group) => { if (tempGroups[group] === undefined) { tempGroups[group] = [job]; } else { @@ -829,7 +826,7 @@ function processBasicJobInfo(localJobService, jobsList) { // use cloned copy of jobs list so not to alter the original const jobsListCopy = _.cloneDeep(jobsList); - _.each(jobsListCopy, jobObj => { + _.each(jobsListCopy, (jobObj) => { const analysisConfig = jobObj.analysis_config; const bucketSpan = parseInterval(analysisConfig.bucket_span); @@ -850,7 +847,7 @@ function processBasicJobInfo(localJobService, jobsList) { if (_.has(jobObj, 'custom_settings.custom_urls')) { job.customUrls = []; - _.each(jobObj.custom_settings.custom_urls, url => { + _.each(jobObj.custom_settings.custom_urls, (url) => { if (_.has(url, 'url_name') && _.has(url, 'url_value') && isWebUrl(url.url_value)) { // Only make web URLs (i.e. http or https) available in dashboard drilldowns. job.customUrls.push(url); @@ -887,7 +884,7 @@ function createJobStats(jobsList, jobStats) { const mlNodes = {}; let failedJobs = 0; - _.each(jobsList, job => { + _.each(jobsList, (job) => { if (job.state === 'opened') { jobStats.open.value++; } else if (job.state === 'closed') { @@ -925,10 +922,10 @@ function createResultsUrlForJobs(jobsList, resultsPage) { from = jobsList[0].earliestTimestampMs; to = jobsList[0].latestResultsTimestampMs; // Will be max(latest source data, latest bucket results) } else { - const jobsWithData = jobsList.filter(j => j.earliestTimestampMs !== undefined); + const jobsWithData = jobsList.filter((j) => j.earliestTimestampMs !== undefined); if (jobsWithData.length > 0) { - from = Math.min(...jobsWithData.map(j => j.earliestTimestampMs)); - to = Math.max(...jobsWithData.map(j => j.latestResultsTimestampMs)); + from = Math.min(...jobsWithData.map((j) => j.earliestTimestampMs)); + to = Math.max(...jobsWithData.map((j) => j.latestResultsTimestampMs)); } } @@ -937,12 +934,12 @@ function createResultsUrlForJobs(jobsList, resultsPage) { const fromString = moment(from).format(timeFormat); // Defaults to 'now' if 'from' is undefined const toString = moment(to).format(timeFormat); // Defaults to 'now' if 'to' is undefined - const jobIds = jobsList.map(j => j.id); + const jobIds = jobsList.map((j) => j.id); return createResultsUrl(jobIds, fromString, toString, resultsPage); } function createResultsUrl(jobIds, start, end, resultsPage) { - const idString = jobIds.map(j => `'${j}'`).join(','); + const idString = jobIds.map((j) => `'${j}'`).join(','); const from = moment(start).toISOString(); const to = moment(end).toISOString(); let path = ''; diff --git a/x-pack/plugins/ml/public/application/services/mapping_service.js b/x-pack/plugins/ml/public/application/services/mapping_service.js index 36363cfa3d713..52aa5ed7413cb 100644 --- a/x-pack/plugins/ml/public/application/services/mapping_service.js +++ b/x-pack/plugins/ml/public/application/services/mapping_service.js @@ -14,10 +14,10 @@ export function getFieldTypeFromMapping(index, fieldName) { return new Promise((resolve, reject) => { if (index !== '') { ml.getFieldCaps({ index, fields: [fieldName] }) - .then(resp => { + .then((resp) => { let fieldType = ''; - _.each(resp.fields, field => { - _.each(field, type => { + _.each(resp.fields, (field) => { + _.each(field, (type) => { if (fieldType === '') { fieldType = type.type; } @@ -25,7 +25,7 @@ export function getFieldTypeFromMapping(index, fieldName) { }); resolve(fieldType); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { diff --git a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts index 2b6fb50538020..bd91995b6efc3 100644 --- a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts +++ b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts @@ -27,7 +27,7 @@ describe('ml_server_info initial state', () => { }); describe('ml_server_info', () => { - beforeEach(async done => { + beforeEach(async (done) => { await loadMlServerInfo(); done(); }); @@ -40,7 +40,7 @@ describe('ml_server_info', () => { }); describe('defaults', () => { - it('can get defaults', async done => { + it('can get defaults', async (done) => { const defaults = getNewJobDefaults(); expect(defaults.anomaly_detectors.model_memory_limit).toBe('128mb'); @@ -52,7 +52,7 @@ describe('ml_server_info', () => { }); describe('limits', () => { - it('can get limits', async done => { + it('can get limits', async (done) => { const limits = getNewJobLimits(); expect(limits.max_model_memory_limit).toBe('128mb'); diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts index 792d5222bc6cb..81f05065b5139 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts @@ -26,14 +26,14 @@ const indexPattern = ({ describe('new_job_capabilities_service', () => { describe('cloudwatch newJobCaps()', () => { - it('can construct job caps objects from endpoint json', async done => { + it('can construct job caps objects from endpoint json', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern); const { fields, aggs } = await newJobCapsService.newJobCaps; - const networkOutField = fields.find(f => f.id === 'NetworkOut') || { aggs: [] }; - const regionField = fields.find(f => f.id === 'region') || { aggs: [] }; - const meanAgg = aggs.find(a => a.id === 'mean') || { fields: [] }; - const distinctCountAgg = aggs.find(a => a.id === 'distinct_count') || { fields: [] }; + const networkOutField = fields.find((f) => f.id === 'NetworkOut') || { aggs: [] }; + const regionField = fields.find((f) => f.id === 'region') || { aggs: [] }; + const meanAgg = aggs.find((a) => a.id === 'mean') || { fields: [] }; + const distinctCountAgg = aggs.find((a) => a.id === 'distinct_count') || { fields: [] }; expect(fields).toHaveLength(12); expect(aggs).toHaveLength(35); @@ -46,7 +46,7 @@ describe('new_job_capabilities_service', () => { done(); }); - it('job caps including text fields', async done => { + it('job caps including text fields', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern, true, false); const { fields, aggs } = await newJobCapsService.newJobCaps; @@ -56,7 +56,7 @@ describe('new_job_capabilities_service', () => { done(); }); - it('job caps excluding event rate', async done => { + it('job caps excluding event rate', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern, false, true); const { fields, aggs } = await newJobCapsService.newJobCaps; diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts index f5f1bd3d4c541..bc65ebe7a5fac 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts @@ -85,7 +85,7 @@ class NewJobCapsService { } public get categoryFields(): Field[] { - return this._fields.filter(f => categoryFieldTypes.includes(f.type)); + return this._fields.filter((f) => categoryFieldTypes.includes(f.type)); } public async initializeFromIndexPattern( @@ -108,9 +108,9 @@ class NewJobCapsService { allFields ); const catFields = fieldsPreferringText.filter( - f => f.type === ES_FIELD_TYPES.KEYWORD || f.type === ES_FIELD_TYPES.TEXT + (f) => f.type === ES_FIELD_TYPES.KEYWORD || f.type === ES_FIELD_TYPES.TEXT ); - const dateFields = fieldsPreferringText.filter(f => f.type === ES_FIELD_TYPES.DATE); + const dateFields = fieldsPreferringText.filter((f) => f.type === ES_FIELD_TYPES.DATE); const fields = this._removeTextFields ? fieldsPreferringKeyword : allFields; // set the main fields list to contain fields which have been filtered to prefer @@ -127,12 +127,12 @@ class NewJobCapsService { } public getFieldById(id: string): Field | null { - const field = this._fields.find(f => f.id === id); + const field = this._fields.find((f) => f.id === id); return field === undefined ? null : field; } public getAggById(id: string): Aggregation | null { - const agg = this._aggs.find(f => f.id === id); + const agg = this._aggs.find((f) => f.id === id); return agg === undefined ? null : agg; } } @@ -190,8 +190,8 @@ function createObjects(resp: any, indexPatternTitle: string) { // the aggIds and fieldIds lists are no longer needed as we've created // lists of real fields and aggs - fields.forEach(f => delete f.aggIds); - aggs.forEach(a => delete a.fieldIds); + fields.forEach((f) => delete f.aggIds); + aggs.forEach((a) => delete a.fieldIds); return { fields, @@ -219,7 +219,7 @@ function addEventRateField(aggs: Aggregation[], fields: Field[]) { aggs: [], }; - aggs.forEach(a => { + aggs.forEach((a) => { if (eventRateField.aggs !== undefined && a.fields === undefined) { // if the agg's field list is undefined, it is a fieldless aggregation and // so can only be used with the event rate field. @@ -232,17 +232,17 @@ function addEventRateField(aggs: Aggregation[], fields: Field[]) { // create two lists, one removing text fields if there are keyword equivalents and vice versa function processTextAndKeywordFields(fields: Field[]) { - const keywordIds = fields.filter(f => f.type === ES_FIELD_TYPES.KEYWORD).map(f => f.id); - const textIds = fields.filter(f => f.type === ES_FIELD_TYPES.TEXT).map(f => f.id); + const keywordIds = fields.filter((f) => f.type === ES_FIELD_TYPES.KEYWORD).map((f) => f.id); + const textIds = fields.filter((f) => f.type === ES_FIELD_TYPES.TEXT).map((f) => f.id); const fieldsPreferringKeyword = fields.filter( - f => + (f) => f.type !== ES_FIELD_TYPES.TEXT || (f.type === ES_FIELD_TYPES.TEXT && keywordIds.includes(`${f.id}.keyword`) === false) ); const fieldsPreferringText = fields.filter( - f => + (f) => f.type !== ES_FIELD_TYPES.KEYWORD || (f.type === ES_FIELD_TYPES.KEYWORD && textIds.includes(f.id.replace(/\.keyword$/, '')) === false) diff --git a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts index 8f701a9ebe057..a21d0caaedd33 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts @@ -74,7 +74,7 @@ export function getMetricData( ...(query ? [query] : []), ]; - entityFields.forEach(entity => { + entityFields.forEach((entity) => { if (entity.fieldValue.length !== 0) { mustCriteria.push({ term: { @@ -227,7 +227,7 @@ export function getModelPlotOutput( ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -305,7 +305,7 @@ export function getModelPlotOutput( }, }) .pipe( - map(resp => { + map((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); _.each(aggregationsByTime, (dataForTime: any) => { const time = dataForTime.key; @@ -385,7 +385,7 @@ export function getRecordsForCriteria( } // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { boolCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -420,7 +420,7 @@ export function getRecordsForCriteria( }, }) .pipe( - map(resp => { + map((resp) => { if (resp.hits.total !== 0) { _.each(resp.hits.hits, (hit: any) => { obj.records.push(hit._source); @@ -533,7 +533,7 @@ export function getScheduledEventsByBucket( }, }) .pipe( - map(resp => { + map((resp) => { const dataByJobId = _.get(resp, ['aggregations', 'jobs', 'buckets'], []); _.each(dataByJobId, (dataForJob: any) => { const jobId: string = dataForJob.key; diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.js b/x-pack/plugins/ml/public/application/services/results_service/results_service.js index b7aa5edc88638..4fccc4d789370 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.js +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.js @@ -116,15 +116,15 @@ export function getScoresByBucket(jobIds, earliestMs, latestMs, interval, maxRes }, }, }) - .then(resp => { + .then((resp) => { const dataByJobId = _.get(resp, ['aggregations', 'jobId', 'buckets'], []); - _.each(dataByJobId, dataForJob => { + _.each(dataByJobId, (dataForJob) => { const jobId = dataForJob.key; const resultsForTime = {}; const dataByTime = _.get(dataForJob, ['byTime', 'buckets'], []); - _.each(dataByTime, dataForTime => { + _.each(dataByTime, (dataForTime) => { const value = _.get(dataForTime, ['anomalyScore', 'value']); if (value !== undefined) { const time = dataForTime.key; @@ -136,7 +136,7 @@ export function getScoresByBucket(jobIds, earliestMs, latestMs, interval, maxRes resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -205,7 +205,7 @@ export function getTopInfluencers( if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { bool: { must: [ @@ -282,18 +282,18 @@ export function getTopInfluencers( }, }, }) - .then(resp => { + .then((resp) => { const fieldNameBuckets = _.get( resp, ['aggregations', 'influencerFieldNames', 'buckets'], [] ); - _.each(fieldNameBuckets, nameBucket => { + _.each(fieldNameBuckets, (nameBucket) => { const fieldName = nameBucket.key; const fieldValues = []; const fieldValueBuckets = _.get(nameBucket, ['influencerFieldValues', 'buckets'], []); - _.each(fieldValueBuckets, valueBucket => { + _.each(fieldValueBuckets, (valueBucket) => { const fieldValueResult = { influencerFieldValue: valueBucket.key, maxAnomalyScore: valueBucket.maxAnomalyScore.value, @@ -307,7 +307,7 @@ export function getTopInfluencers( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -407,9 +407,9 @@ export function getTopInfluencerValues( }, }, }) - .then(resp => { + .then((resp) => { const buckets = _.get(resp, ['aggregations', 'influencerFieldValues', 'buckets'], []); - _.each(buckets, bucket => { + _.each(buckets, (bucket) => { const result = { influencerFieldValue: bucket.key, maxAnomalyScore: bucket.maxAnomalyScore.value, @@ -420,7 +420,7 @@ export function getTopInfluencerValues( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -440,9 +440,9 @@ export function getOverallBucketScores(jobIds, topN, earliestMs, latestMs, inter start: earliestMs, end: latestMs, }) - .then(resp => { + .then((resp) => { const dataByTime = _.get(resp, ['overall_buckets'], []); - _.each(dataByTime, dataForTime => { + _.each(dataByTime, (dataForTime) => { const value = _.get(dataForTime, ['overall_score']); if (value !== undefined) { obj.results[dataForTime.timestamp] = value; @@ -451,7 +451,7 @@ export function getOverallBucketScores(jobIds, topN, earliestMs, latestMs, inter resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -594,18 +594,18 @@ export function getInfluencerValueMaxScoreByTime( }, }, }) - .then(resp => { + .then((resp) => { const fieldValueBuckets = _.get( resp, ['aggregations', 'influencerFieldValues', 'buckets'], [] ); - _.each(fieldValueBuckets, valueBucket => { + _.each(fieldValueBuckets, (valueBucket) => { const fieldValue = valueBucket.key; const fieldValues = {}; const timeBuckets = _.get(valueBucket, ['byTime', 'buckets'], []); - _.each(timeBuckets, timeBucket => { + _.each(timeBuckets, (timeBucket) => { const time = timeBucket.key; const score = timeBucket.maxAnomalyScore.value; fieldValues[time] = score; @@ -616,7 +616,7 @@ export function getInfluencerValueMaxScoreByTime( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -710,15 +710,15 @@ export function getRecordInfluencers(jobIds, threshold, earliestMs, latestMs, ma sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -788,7 +788,7 @@ export function getRecordsForInfluencer( if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { nested: { path: 'influencers', @@ -841,15 +841,15 @@ export function getRecordsForInfluencer( sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -966,15 +966,15 @@ export function getRecordsForDetector( sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1045,9 +1045,9 @@ export function getEventRateData(index, query, timeFieldName, earliestMs, latest }, }, }) - .then(resp => { + .then((resp) => { const dataByTimeBucket = _.get(resp, ['aggregations', 'eventRate', 'buckets'], []); - _.each(dataByTimeBucket, dataForTime => { + _.each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; obj.results[time] = dataForTime.doc_count; }); @@ -1055,7 +1055,7 @@ export function getEventRateData(index, query, timeFieldName, earliestMs, latest resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1192,7 +1192,7 @@ export function getEventDistributionData( body, rest_total_hits_as_int: true, }) - .then(resp => { + .then((resp) => { // Because of the sampling, results of metricFunctions which use sum or count // can be significantly skewed. Taking into account totalHits we calculate a // a factor to normalize results for these metricFunctions. @@ -1208,7 +1208,7 @@ export function getEventDistributionData( const data = dataByTime.reduce((d, dataForTime) => { const date = +dataForTime.key; const entities = _.get(dataForTime, ['entities', 'buckets'], []); - entities.forEach(entity => { + entities.forEach((entity) => { let value = metricFunction === 'count' ? entity.doc_count : entity.metric.value; if ( @@ -1229,7 +1229,7 @@ export function getEventDistributionData( }, []); resolve(data); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1260,7 +1260,7 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates { term: { job_id: jobId } }, ]; - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -1307,9 +1307,9 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates }, }, }) - .then(resp => { + .then((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, dataForTime => { + _.each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { score: _.get(dataForTime, ['recordScore', 'value']), @@ -1318,7 +1318,7 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js index bd3c8779c9d43..dbff27dceff4d 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js @@ -70,7 +70,7 @@ export const EventsTable = ({ defaultMessage: 'Start', }), sortable: true, - render: timeMs => { + render: (timeMs) => { const time = moment(timeMs); return time.format(TIME_FORMAT); }, @@ -81,7 +81,7 @@ export const EventsTable = ({ defaultMessage: 'End', }), sortable: true, - render: timeMs => { + render: (timeMs) => { const time = moment(timeMs); return time.format(TIME_FORMAT); }, @@ -89,7 +89,7 @@ export const EventsTable = ({ { field: '', name: '', - render: event => ( + render: (event) => ( { + handleImport = async (loadedFile) => { const incomingFile = loadedFile[0]; const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.importModal.couldNotParseICSFileErrorMessage', @@ -82,14 +82,14 @@ export class ImportModal extends Component { } }; - onEventDelete = eventId => { - this.setState(prevState => ({ - allImportedEvents: prevState.allImportedEvents.filter(event => event.event_id !== eventId), - selectedEvents: prevState.selectedEvents.filter(event => event.event_id !== eventId), + onEventDelete = (eventId) => { + this.setState((prevState) => ({ + allImportedEvents: prevState.allImportedEvents.filter((event) => event.event_id !== eventId), + selectedEvents: prevState.selectedEvents.filter((event) => event.event_id !== eventId), })); }; - onCheckboxToggle = e => { + onCheckboxToggle = (e) => { this.setState({ includePastEvents: e.target.checked, }); @@ -99,7 +99,7 @@ export class ImportModal extends Component { const { allImportedEvents, selectedEvents, includePastEvents } = this.state; const eventsToImport = includePastEvents ? allImportedEvents : selectedEvents; - const events = eventsToImport.map(event => ({ + const events = eventsToImport.map((event) => ({ description: event.description, start_time: event.start_time, end_time: event.end_time, @@ -135,7 +135,7 @@ export class ImportModal extends Component { importedEvents = selectedEvents; } - if (importedEvents.find(e => e.asterisk) !== undefined) { + if (importedEvents.find((e) => e.asterisk) !== undefined) { showRecurringWarning = true; } diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js index d24577826838e..07bf49ea6d7db 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js @@ -12,7 +12,7 @@ function createEvents(ical) { const events = ical.events(); const mlEvents = []; - events.forEach(e => { + events.forEach((e) => { if (e.element === 'VEVENT') { const description = e.properties.SUMMARY; const start = e.properties.DTSTART; @@ -38,7 +38,7 @@ function createEvents(ical) { export function filterEvents(events) { const now = moment().valueOf(); - return events.filter(e => e.start_time > now); + return events.filter((e) => e.start_time > now); } export function parseICSFile(data) { diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js index 67570e2c7c54f..7efc37d4bf8ce 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js @@ -59,8 +59,8 @@ class NewCalendarUI extends Component { try { const { jobIds, groupIds, calendars } = await getCalendarSettingsData(); - const jobIdOptions = jobIds.map(jobId => ({ label: jobId })); - const groupIdOptions = groupIds.map(groupId => ({ label: groupId })); + const jobIdOptions = jobIds.map((jobId) => ({ label: jobId })); + const groupIdOptions = groupIds.map((groupId) => ({ label: groupId })); const selectedJobOptions = []; const selectedGroupOptions = []; @@ -71,7 +71,7 @@ class NewCalendarUI extends Component { // Editing existing calendar. if (this.props.calendarId !== undefined) { - selectedCalendar = calendars.find(cal => cal.calendar_id === this.props.calendarId); + selectedCalendar = calendars.find((cal) => cal.calendar_id === this.props.calendarId); if (selectedCalendar) { formCalendarId = selectedCalendar.calendar_id; @@ -80,10 +80,10 @@ class NewCalendarUI extends Component { if (selectedCalendar.job_ids.includes(GLOBAL_CALENDAR)) { isGlobalCalendar = true; } else { - selectedCalendar.job_ids.forEach(id => { - if (jobIds.find(jobId => jobId === id)) { + selectedCalendar.job_ids.forEach((id) => { + if (jobIds.find((jobId) => jobId === id)) { selectedJobOptions.push({ label: id }); - } else if (groupIds.find(groupId => groupId === id)) { + } else if (groupIds.find((groupId) => groupId === id)) { selectedGroupOptions.push({ label: id }); } }); @@ -195,12 +195,12 @@ class NewCalendarUI extends Component { const allIds = isGlobalCalendar ? [GLOBAL_CALENDAR] : [ - ...selectedJobOptions.map(option => option.label), - ...selectedGroupOptions.map(option => option.label), + ...selectedJobOptions.map((option) => option.label), + ...selectedGroupOptions.map((option) => option.label), ]; // Reduce events to fields expected by api - const eventsToSave = events.map(event => ({ + const eventsToSave = events.map((event) => ({ description: event.description, start_time: event.start_time, end_time: event.end_time, @@ -217,12 +217,12 @@ class NewCalendarUI extends Component { return calendar; }; - onCreateGroupOption = newGroup => { + onCreateGroupOption = (newGroup) => { const newOption = { label: newGroup, }; // Select the option. - this.setState(prevState => ({ + this.setState((prevState) => ({ selectedGroupOptions: prevState.selectedGroupOptions.concat(newOption), })); }; @@ -233,19 +233,19 @@ class NewCalendarUI extends Component { }); }; - onJobSelection = selectedJobOptions => { + onJobSelection = (selectedJobOptions) => { this.setState({ selectedJobOptions, }); }; - onGroupSelection = selectedGroupOptions => { + onGroupSelection = (selectedGroupOptions) => { this.setState({ selectedGroupOptions, }); }; - onCalendarIdChange = e => { + onCalendarIdChange = (e) => { const isValid = validateCalendarId(e.target.value); this.setState({ @@ -254,14 +254,14 @@ class NewCalendarUI extends Component { }); }; - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setState({ description: e.target.value, }); }; showImportModal = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isImportModalVisible: !prevState.isImportModalVisible, })); }; @@ -272,9 +272,9 @@ class NewCalendarUI extends Component { }); }; - onEventDelete = eventId => { - this.setState(prevState => ({ - events: prevState.events.filter(event => event.event_id !== eventId), + onEventDelete = (eventId) => { + this.setState((prevState) => ({ + events: prevState.events.filter((event) => event.event_id !== eventId), })); }; @@ -286,15 +286,15 @@ class NewCalendarUI extends Component { this.setState({ isNewEventModalVisible: true }); }; - addEvent = event => { - this.setState(prevState => ({ + addEvent = (event) => { + this.setState((prevState) => ({ events: [...prevState.events, event], isNewEventModalVisible: false, })); }; - addImportedEvents = events => { - this.setState(prevState => ({ + addImportedEvents = (events) => { + this.setState((prevState) => ({ events: [...prevState.events, ...events], isImportModalVisible: false, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js index 7f5ade64e7f14..0a6e8916fa657 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js @@ -38,7 +38,7 @@ jest.mock('../../../services/ml_api_service', () => ({ jest.mock('./utils', () => ({ getCalendarSettingsData: jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { resolve({ jobIds: ['test-job-one', 'test-job-2'], groupIds: ['test-group-one', 'test-group-two'], @@ -48,7 +48,7 @@ jest.mock('./utils', () => ({ ), })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js index 814f30a70db54..8380fd36b458c 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js @@ -42,9 +42,7 @@ export class NewEventModal extends Component { super(props); const startDate = moment().startOf('day'); - const endDate = moment() - .startOf('day') - .add(1, 'days'); + const endDate = moment().startOf('day').add(1, 'days'); this.state = { startDate, @@ -55,7 +53,7 @@ export class NewEventModal extends Component { }; } - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setState({ description: e.target.value, }); @@ -76,7 +74,7 @@ export class NewEventModal extends Component { this.props.addEvent(event); }; - handleChangeStart = date => { + handleChangeStart = (date) => { let start = null; let end = this.state.endDate; @@ -96,7 +94,7 @@ export class NewEventModal extends Component { }); }; - handleChangeEnd = date => { + handleChangeEnd = (date) => { let start = this.state.startDate; let end = null; @@ -116,7 +114,7 @@ export class NewEventModal extends Component { }); }; - handleTimeStartChange = event => { + handleTimeStartChange = (event) => { const dateString = event.target.value; let isValidDate = false; @@ -136,7 +134,7 @@ export class NewEventModal extends Component { } }; - handleTimeEndChange = event => { + handleTimeEndChange = (event) => { const dateString = event.target.value; let isValidDate = false; diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js index e91dce6124cef..f8b9c97db09e3 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js @@ -42,10 +42,7 @@ describe('NewEventModal', () => { // trigger handleChangeStart directly with startMoment instance.handleChangeStart(startMoment); // add 3 days to endMoment as it will be adjusted to be one day after startDate - const expected = endMoment - .startOf('day') - .add(3, 'days') - .format(); + const expected = endMoment.startOf('day').add(3, 'days').format(); expect(wrapper.state('endDate').format()).toBe(expected); }); @@ -66,10 +63,7 @@ describe('NewEventModal', () => { // trigger handleChangeStart directly with endMoment instance.handleChangeStart(endMoment); // subtract 3 days from startDate as it will be adjusted to be one day before endDate - const expected = startMoment - .startOf('day') - .subtract(2, 'days') - .format(); + const expected = startMoment.startOf('day').subtract(2, 'days').format(); expect(wrapper.state('startDate').format()).toBe(expected); }); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js index efc54c181fdc1..874a1e14cb5aa 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js @@ -12,10 +12,10 @@ function getJobIds() { return new Promise((resolve, reject) => { ml.jobs .jobsSummary() - .then(resp => { - resolve(resp.map(job => job.id)); + .then((resp) => { + resolve(resp.map((job) => job.id)); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithFetchingJobSummariesErrorMessage', { @@ -33,10 +33,10 @@ function getGroupIds() { return new Promise((resolve, reject) => { ml.jobs .groups() - .then(resp => { - resolve(resp.map(group => group.id)); + .then((resp) => { + resolve(resp.map((group) => group.id)); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithLoadingGroupsErrorMessage', { @@ -53,10 +53,10 @@ function getGroupIds() { function getCalendars() { return new Promise((resolve, reject) => { ml.calendars() - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithLoadingCalendarsErrorMessage', { @@ -104,7 +104,5 @@ export function validateCalendarId(calendarId) { } export function generateTempId() { - return Math.random() - .toString(36) - .substr(2, 9); + return Math.random().toString(36).substr(2, 9); } diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js index c968db0b32d5a..c1c00bb022f20 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js @@ -75,7 +75,7 @@ export class CalendarsListUI extends Component { this.setState({ isDestroyModalVisible: true }); }; - setSelectedCalendarList = selectedCalendars => { + setSelectedCalendarList = (selectedCalendars) => { this.setState({ selectedForDeletion: selectedCalendars }); }; @@ -137,7 +137,7 @@ export class CalendarsListUI extends Component { defaultMessage="Delete {calendarsCount, plural, one {this calendar} other {these calendars}}? {calendarsList}" values={{ calendarsCount: selectedForDeletion.length, - calendarsList: selectedForDeletion.map(c => c.calendar_id).join(', '), + calendarsList: selectedForDeletion.map((c) => c.calendar_id).join(', '), }} />

diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js index b2fce2c1474cb..619478db54441 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js @@ -37,11 +37,11 @@ jest.mock('../../../services/ml_api_service', () => ({ jest.mock('react', () => { const r = jest.requireActual('react'); - return { ...r, memo: x => x }; + return { ...r, memo: (x) => x }; }); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js b/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js index 47dc373e537ba..857d2e7e6659b 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js @@ -10,7 +10,7 @@ import React from 'react'; import { CalendarsListHeader } from './header'; jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js b/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js index be41eabd5ae2d..b81cc6fbb4c30 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js @@ -45,7 +45,9 @@ export const CalendarsListTable = ({ sortable: true, truncateText: true, scope: 'row', - render: id => {id}, + render: (id) => ( + {id} + ), }, { field: 'job_ids_string', @@ -54,7 +56,7 @@ export const CalendarsListTable = ({ }), sortable: true, truncateText: true, - render: jobList => { + render: (jobList) => { return jobList === GLOBAL_CALENDAR ? ( + render: (eventsLength) => i18n.translate('xpack.ml.calendarsList.table.eventsCountLabel', { defaultMessage: '{eventsLength, plural, one {# event} other {# events}}', values: { eventsLength }, @@ -82,7 +84,7 @@ export const CalendarsListTable = ({ ]; const tableSelection = { - onSelectionChange: selection => setSelectedCalendarList(selection), + onSelectionChange: (selection) => setSelectedCalendarList(selection), }; const search = { diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js index 404484b8055f2..816eea39059a8 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js @@ -40,7 +40,7 @@ export class AddItemPopover extends Component { }; } - onItemsTextChange = e => { + onItemsTextChange = (e) => { this.setState({ itemsText: e.target.value, }); @@ -62,7 +62,7 @@ export class AddItemPopover extends Component { const items = this.state.itemsText.split('\n'); const addItems = []; // Remove duplicates. - items.forEach(item => { + items.forEach((item) => { if (addItems.indexOf(item) === -1 && item.length > 0) { addItems.push(item); } diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js index 0266bc2a55318..bb909ddc3aa78 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js @@ -9,7 +9,7 @@ // with 'mock' so it can be used lazily. const mockCheckPermission = jest.fn(() => true); jest.mock('../../../../capabilities/check_capabilities', () => ({ - checkPermission: privilege => mockCheckPermission(privilege), + checkPermission: (privilege) => mockCheckPermission(privilege), })); jest.mock('../../../../services/ml_api_service', () => 'ml'); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js index e1e32afe08dbe..e7846cb546852 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js @@ -33,7 +33,7 @@ export class EditDescriptionPopover extends Component { }; } - onChange = e => { + onChange = (e) => { this.setState({ value: e.target.value, }); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js index b3547b3ee6568..25c86c559e303 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js @@ -39,7 +39,7 @@ export class FilterListUsagePopover extends Component { const linkText = `${entityValues.length} ${entityType}${entityValues.length !== 1 ? 's' : ''}`; - const listItems = entityValues.map(value =>
  • {value}
  • ); + const listItems = entityValues.map((value) =>
  • {value}
  • ); const button = ( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js index adf57632bc84b..6437e819db04f 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js @@ -49,11 +49,11 @@ function getMatchingFilterItems(searchBarQuery, items) { // Convert the list of Strings into a list of Objects suitable for running through // the search bar query. - const allItems = items.map(item => ({ value: item })); + const allItems = items.map((item) => ({ value: item })); const matchingObjects = EuiSearchBar.Query.execute(searchBarQuery, allItems, { defaultFields: ['value'], }); - return matchingObjects.map(item => item.value); + return matchingObjects.map((item) => item.value); } function getActivePage(activePageState, itemsPerPage, numMatchingItems) { @@ -105,13 +105,13 @@ export class EditFilterListUI extends Component { } } - loadFilterList = filterId => { + loadFilterList = (filterId) => { ml.filters .filters({ filterId }) - .then(filter => { + .then((filter) => { this.setLoadedFilterState(filter); }) - .catch(resp => { + .catch((resp) => { console.log(`Error loading filter ${filterId}:`, resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -128,9 +128,9 @@ export class EditFilterListUI extends Component { }); }; - setLoadedFilterState = loadedFilter => { + setLoadedFilterState = (loadedFilter) => { // Store the loaded filter so we can diff changes to the items when saving updates. - this.setState(prevState => { + this.setState((prevState) => { const { itemsPerPage, searchQuery } = prevState; const matchingItems = getMatchingFilterItems(searchQuery, loadedFilter.items); @@ -150,23 +150,23 @@ export class EditFilterListUI extends Component { }); }; - updateNewFilterId = newFilterId => { + updateNewFilterId = (newFilterId) => { this.setState({ newFilterId, isNewFilterIdInvalid: !isValidFilterListId(newFilterId), }); }; - updateDescription = description => { + updateDescription = (description) => { this.setState({ description }); }; - addItems = itemsToAdd => { - this.setState(prevState => { + addItems = (itemsToAdd) => { + this.setState((prevState) => { const { itemsPerPage, searchQuery } = prevState; const items = [...prevState.items]; const alreadyInFilter = []; - itemsToAdd.forEach(item => { + itemsToAdd.forEach((item) => { if (items.indexOf(item) === -1) { items.push(item); } else { @@ -206,10 +206,10 @@ export class EditFilterListUI extends Component { }; deleteSelectedItems = () => { - this.setState(prevState => { + this.setState((prevState) => { const { selectedItems, itemsPerPage, searchQuery } = prevState; const items = [...prevState.items]; - selectedItems.forEach(item => { + selectedItems.forEach((item) => { const index = items.indexOf(item); if (index !== -1) { items.splice(index, 1); @@ -230,7 +230,7 @@ export class EditFilterListUI extends Component { }; onSearchChange = ({ query }) => { - this.setState(prevState => { + this.setState((prevState) => { const { items, itemsPerPage } = prevState; const matchingItems = getMatchingFilterItems(query, items); @@ -245,7 +245,7 @@ export class EditFilterListUI extends Component { }; setItemSelected = (item, isSelected) => { - this.setState(prevState => { + this.setState((prevState) => { const selectedItems = [...prevState.selectedItems]; const index = selectedItems.indexOf(item); if (isSelected === true && index === -1) { @@ -260,11 +260,11 @@ export class EditFilterListUI extends Component { }); }; - setActivePage = activePage => { + setActivePage = (activePage) => { this.setState({ activePage }); }; - setItemsPerPage = itemsPerPage => { + setItemsPerPage = (itemsPerPage) => { this.setState({ itemsPerPage, activePage: 0, @@ -277,11 +277,11 @@ export class EditFilterListUI extends Component { const { loadedFilter, newFilterId, description, items } = this.state; const filterId = this.props.filterId !== undefined ? this.props.filterId : newFilterId; saveFilterList(filterId, description, items, loadedFilter) - .then(savedFilter => { + .then((savedFilter) => { this.setLoadedFilterState(savedFilter); returnToFiltersList(); }) - .catch(resp => { + .catch((resp) => { console.log(`Error saving filter ${filterId}:`, resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js index a743a4b22ce92..1223194030e64 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js @@ -37,7 +37,7 @@ jest.mock('../../../services/ml_api_service', () => ({ })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js index f1efa173178f2..f47264221eaec 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js @@ -88,7 +88,7 @@ export const EditFilterListHeader = ({ name="new_filter_id" value={newFilterId} isInvalid={isNewFilterIdInvalid} - onChange={e => updateNewFilterId(e.target.value)} + onChange={(e) => updateNewFilterId(e.target.value)} /> ); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js index c82be4cbfa71e..b07dfcc48c891 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js @@ -21,19 +21,19 @@ export function saveFilterList(filterId, description, items, loadedFilterList) { if (loadedFilterList === undefined || loadedFilterList.filter_id === undefined) { // Create a new filter. addFilterList(filterId, description, items) - .then(newFilter => { + .then((newFilter) => { resolve(newFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { // Edit to existing filter. updateFilterList(loadedFilterList, description, items) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } @@ -55,16 +55,16 @@ export function addFilterList(filterId, description, items) { // First check the filterId isn't already in use by loading the current list of filters. ml.filters .filtersStats() - .then(filterLists => { - const savedFilterIds = filterLists.map(filterList => filterList.filter_id); + .then((filterLists) => { + const savedFilterIds = filterLists.map((filterList) => filterList.filter_id); if (savedFilterIds.indexOf(filterId) === -1) { // Save the new filter. ml.filters .addFilter(filterId, description, items) - .then(newFilter => { + .then((newFilter) => { resolve(newFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { @@ -73,7 +73,7 @@ export function addFilterList(filterId, description, items) { reject(new Error(filterWithIdExistsErrorMessage)); } }) - .catch(error => { + .catch((error) => { reject(error); }); }); @@ -83,15 +83,15 @@ export function updateFilterList(loadedFilterList, description, items) { return new Promise((resolve, reject) => { // Get items added and removed from loaded filter. const loadedItems = loadedFilterList.items; - const addItems = items.filter(item => loadedItems.includes(item) === false); - const removeItems = loadedItems.filter(item => items.includes(item) === false); + const addItems = items.filter((item) => loadedItems.includes(item) === false); + const removeItems = loadedItems.filter((item) => items.includes(item) === false); ml.filters .updateFilter(loadedFilterList.filter_id, description, addItems, removeItems) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); }); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js index 9e40d99f1c898..270d5fa350cae 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js @@ -42,11 +42,11 @@ export class FilterListsUI extends Component { this.refreshFilterLists(); } - setFilterLists = filterLists => { + setFilterLists = (filterLists) => { // Check selected filter lists still exist. - this.setState(prevState => { - const loadedFilterIds = filterLists.map(filterList => filterList.filter_id); - const selectedFilterLists = prevState.selectedFilterLists.filter(filterList => { + this.setState((prevState) => { + const loadedFilterIds = filterLists.map((filterList) => filterList.filter_id); + const selectedFilterLists = prevState.selectedFilterLists.filter((filterList) => { return loadedFilterIds.indexOf(filterList.filter_id) !== -1; }); @@ -57,7 +57,7 @@ export class FilterListsUI extends Component { }); }; - setSelectedFilterLists = selectedFilterLists => { + setSelectedFilterLists = (selectedFilterLists) => { this.setState({ selectedFilterLists }); }; @@ -65,10 +65,10 @@ export class FilterListsUI extends Component { // Load the list of filters. ml.filters .filtersStats() - .then(filterLists => { + .then((filterLists) => { this.setFilterLists(filterLists); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of filters:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js index c1bcee4acdd37..6ddea7a3281d3 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js @@ -17,7 +17,7 @@ jest.mock('../../../capabilities/check_capabilities', () => ({ })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js index fcbf90ec62d4a..7f94f1f2534fb 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js @@ -81,7 +81,9 @@ function getColumns() { name: i18n.translate('xpack.ml.settings.filterLists.table.idColumnName', { defaultMessage: 'ID', }), - render: id => {id}, + render: (id) => ( + {id} + ), sortable: true, scope: 'row', }, @@ -104,7 +106,7 @@ function getColumns() { name: i18n.translate('xpack.ml.settings.filterLists.table.inUseColumnName', { defaultMessage: 'In use', }), - render: usedBy => , + render: (usedBy) => , sortable: true, }, ]; @@ -157,10 +159,10 @@ export function FilterListsTable({ }; const tableSelection = { - selectable: filterList => + selectable: (filterList) => filterList.used_by === undefined || filterList.used_by.jobs.length === 0, selectableMessage: () => undefined, - onSelectionChange: selection => setSelectedFilterLists(selection), + onSelectionChange: (selection) => setSelectedFilterLists(selection), }; return ( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js index 43578e9f5898a..e9657ed601b78 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js @@ -39,13 +39,13 @@ export function ContextChartMask(contextGroup, data, drawBounds, swimlaneHeight) this._y = null; } -ContextChartMask.prototype.style = function(prop, val) { +ContextChartMask.prototype.style = function (prop, val) { this.leftGroup.style(prop, val); this.rightGroup.style(prop, val); return this; }; -ContextChartMask.prototype.x = function(f) { +ContextChartMask.prototype.x = function (f) { if (f == null) { return this._x; } @@ -53,7 +53,7 @@ ContextChartMask.prototype.x = function(f) { return this; }; -ContextChartMask.prototype.y = function(f) { +ContextChartMask.prototype.y = function (f) { if (f == null) { return this._y; } @@ -61,7 +61,7 @@ ContextChartMask.prototype.y = function(f) { return this; }; -ContextChartMask.prototype.redraw = function() { +ContextChartMask.prototype.redraw = function () { const yDomain = this._y.domain(); const minY = yDomain[0]; const maxY = yDomain[1]; @@ -71,11 +71,11 @@ ContextChartMask.prototype.redraw = function() { const that = this; - const leftData = this.data.filter(function(d) { + const leftData = this.data.filter(function (d) { return d.date < that.from; }); - const rightData = this.data.filter(function(d) { + const rightData = this.data.filter(function (d) { return d.date > that.to; }); @@ -83,29 +83,29 @@ ContextChartMask.prototype.redraw = function() { if (this.drawBounds === true) { const boundedArea = d3.svg .area() - .x(function(d) { + .x(function (d) { return that._x(d.date) || 1; }) - .y0(function(d) { + .y0(function (d) { return that._y(Math.min(maxY, Math.max(d.lower, minY))); }) - .y1(function(d) { + .y1(function (d) { return that._y(Math.max(minY, Math.min(d.upper, maxY))); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); this.leftGroup.select('.left.area.bounds').attr('d', boundedArea(leftData)); this.rightGroup.select('.right.area.bounds').attr('d', boundedArea(rightData)); } const valuesLine = d3.svg .line() - .x(function(d) { + .x(function (d) { return that._x(d.date); }) - .y(function(d) { + .y(function (d) { return that._y(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); this.leftGroup.select('.left.values-line').attr('d', valuesLine(leftData)); drawLineChartDots(leftData, this.leftGroup, valuesLine, 1); @@ -168,7 +168,7 @@ ContextChartMask.prototype.redraw = function() { return this; }; -ContextChartMask.prototype.reveal = function(extent) { +ContextChartMask.prototype.reveal = function (extent) { this.from = extent[0]; this.to = extent[1]; this.redraw(); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx index 7bb0b27472c88..c144525699d81 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx @@ -126,7 +126,7 @@ export class EntityControl extends Component { + inputRef={(input) => { if (input) { this.inputRef = input; } diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js index eded8460d2205..87bd2bb4af62c 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js @@ -72,17 +72,17 @@ export class ForecastingModalUI extends Component { addMessage = (message, status, clearFirst = false) => { const msg = { message, status }; - this.setState(prevState => ({ + this.setState((prevState) => ({ messages: clearFirst ? [msg] : [...prevState.messages, msg], })); }; - viewForecast = forecastId => { + viewForecast = (forecastId) => { this.props.setForecastId(forecastId); this.closeModal(); }; - onNewForecastDurationChange = event => { + onNewForecastDurationChange = (event) => { const newForecastDurationErrors = []; let isNewForecastDurationValid = true; const duration = parseInterval(event.target.value); @@ -157,7 +157,7 @@ export class ForecastingModalUI extends Component { }); this.runForecast(true); }) - .catch(resp => { + .catch((resp) => { console.log('Time series forecast modal - could not open job:', resp); this.addMessage( i18n.translate( @@ -200,7 +200,7 @@ export class ForecastingModalUI extends Component { .then(() => { this.setState({ jobClosingState: PROGRESS_STATES.DONE }); }) - .catch(response => { + .catch((response) => { console.log('Time series forecast modal - could not close job:', response); this.addMessage( i18n.translate( @@ -216,7 +216,7 @@ export class ForecastingModalUI extends Component { } }; - runForecast = closeJobAfterRunning => { + runForecast = (closeJobAfterRunning) => { this.setState({ forecastProgress: 0, }); @@ -227,7 +227,7 @@ export class ForecastingModalUI extends Component { mlForecastService .runForecast(this.props.job.job_id, `${durationInSeconds}s`) - .then(resp => { + .then((resp) => { // Endpoint will return { acknowledged:true, id: } before forecast is complete. // So wait for results and then refresh the dashboard to the end of the forecast. if (resp.forecast_id !== undefined) { @@ -236,7 +236,7 @@ export class ForecastingModalUI extends Component { this.runForecastErrorHandler(resp, closeJobAfterRunning); } }) - .catch(resp => this.runForecastErrorHandler(resp, closeJobAfterRunning)); + .catch((resp) => this.runForecastErrorHandler(resp, closeJobAfterRunning)); }; waitForForecastResults = (forecastId, closeJobAfterRunning) => { @@ -248,7 +248,7 @@ export class ForecastingModalUI extends Component { this.forecastChecker = setInterval(() => { mlForecastService .getForecastRequestStats(this.props.job, forecastId) - .then(resp => { + .then((resp) => { // Get the progress (stats value is between 0 and 1). const progress = _.get(resp, ['stats', 'forecast_progress'], previousProgress); const status = _.get(resp, ['stats', 'forecast_status']); @@ -264,7 +264,7 @@ export class ForecastingModalUI extends Component { // Display any messages returned in the request stats. let messages = _.get(resp, ['stats', 'forecast_messages'], []); - messages = messages.map(message => ({ message, status: MESSAGE_LEVEL.WARNING })); + messages = messages.map((message) => ({ message, status: MESSAGE_LEVEL.WARNING })); this.setState({ messages }); if (status === FORECAST_REQUEST_STATE.FINISHED) { @@ -281,7 +281,7 @@ export class ForecastingModalUI extends Component { this.props.setForecastId(forecastId); this.closeAfterRunningForecast(); }) - .catch(response => { + .catch((response) => { // Load the forecast data in the main page, // but leave this dialog open so the error can be viewed. console.log('Time series forecast modal - could not close job:', response); @@ -340,7 +340,7 @@ export class ForecastingModalUI extends Component { } } }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series forecast modal - error loading stats of forecast from elasticsearch:', resp @@ -376,12 +376,12 @@ export class ForecastingModalUI extends Component { }; mlForecastService .getForecastsSummary(job, statusFinishedQuery, bounds.min.valueOf(), FORECASTS_VIEW_MAX) - .then(resp => { + .then((resp) => { this.setState({ previousForecasts: resp.forecasts, }); }) - .catch(resp => { + .catch((resp) => { console.log('Time series forecast modal - error obtaining forecasts summary:', resp); this.addMessage( i18n.translate( @@ -396,7 +396,7 @@ export class ForecastingModalUI extends Component { // Display a warning about running a forecast if there is high number // of partitioning fields. - const entityFieldNames = this.props.entities.map(entity => entity.fieldName); + const entityFieldNames = this.props.entities.map((entity) => entity.fieldName); if (entityFieldNames.length > 0) { ml.getCardinalityOfFields({ index: job.datafeed_config.indices, @@ -406,9 +406,9 @@ export class ForecastingModalUI extends Component { earliestMs: job.data_counts.earliest_record_timestamp, latestMs: job.data_counts.latest_record_timestamp, }) - .then(results => { + .then((results) => { let numPartitions = 1; - Object.values(results).forEach(cardinality => { + Object.values(results).forEach((cardinality) => { numPartitions = numPartitions * cardinality; }); if (numPartitions > WARN_NUM_PARTITIONS) { @@ -426,7 +426,7 @@ export class ForecastingModalUI extends Component { ); } }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series forecast modal - error obtaining cardinality of fields:', resp diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js index 83c153ab39eba..42e9e28f5862d 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js @@ -25,7 +25,7 @@ function getColumns(viewForecast) { defaultMessage: 'Created', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -34,7 +34,7 @@ function getColumns(viewForecast) { defaultMessage: 'From', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -43,7 +43,7 @@ function getColumns(viewForecast) { defaultMessage: 'To', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -51,7 +51,7 @@ function getColumns(viewForecast) { defaultMessage: 'View', }), width: '60px', - render: forecast => { + render: (forecast) => { const viewForecastAriaLabel = i18n.translate( 'xpack.ml.timeSeriesExplorer.forecastsList.viewForecastAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index fca65ea2c1f3b..190bce1639c4a 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -158,25 +158,25 @@ class TimeseriesChartIntl extends Component { this.focusValuesLine = d3.svg .line() - .x(function(d) { + .x(function (d) { return focusXScale(d.date); }) - .y(function(d) { + .y(function (d) { return focusYScale(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); this.focusBoundedArea = d3.svg .area() - .x(function(d) { + .x(function (d) { return focusXScale(d.date) || 1; }) - .y0(function(d) { + .y0(function (d) { return focusYScale(d.upper); }) - .y1(function(d) { + .y1(function (d) { return focusYScale(d.lower); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); this.contextXScale = d3.time.scale().range([0, vizWidth]); this.contextYScale = d3.scale.linear().range([contextChartHeight, contextChartLineTopMargin]); @@ -274,10 +274,7 @@ class TimeseriesChartIntl extends Component { const fieldFormat = this.fieldFormat; - const svg = chartElement - .append('svg') - .attr('width', svgWidth) - .attr('height', svgHeight); + const svg = chartElement.append('svg').attr('width', svgWidth).attr('height', svgHeight); let contextDataMin; let contextDataMax; @@ -290,11 +287,11 @@ class TimeseriesChartIntl extends Component { ? contextChartData : contextChartData.concat(contextForecastData); - contextDataMin = d3.min(combinedData, d => Math.min(d.value, d.lower)); - contextDataMax = d3.max(combinedData, d => Math.max(d.value, d.upper)); + contextDataMin = d3.min(combinedData, (d) => Math.min(d.value, d.lower)); + contextDataMax = d3.max(combinedData, (d) => Math.max(d.value, d.upper)); } else { - contextDataMin = d3.min(contextChartData, d => d.value); - contextDataMax = d3.max(contextChartData, d => d.value); + contextDataMin = d3.min(contextChartData, (d) => d.value); + contextDataMax = d3.max(contextChartData, (d) => d.value); } // Set the size of the left margin according to the width of the largest y axis tick label. @@ -324,14 +321,14 @@ class TimeseriesChartIntl extends Component { .data(focusYScale.ticks()) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { return focusYScale.tickFormat()(d); } }) - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + focusYAxis.tickPadding(), maxYAxisLabelWidth @@ -359,10 +356,7 @@ class TimeseriesChartIntl extends Component { ); // Mask to hide annotations overflow - const annotationsMask = svg - .append('defs') - .append('mask') - .attr('id', ANNOTATION_MASK_ID); + const annotationsMask = svg.append('defs').append('mask').attr('id', ANNOTATION_MASK_ID); annotationsMask .append('rect') @@ -622,7 +616,7 @@ class TimeseriesChartIntl extends Component { (focusForecastData !== undefined && focusForecastData.length > 0) ) { if (this.fieldFormat !== undefined) { - this.focusYAxis.tickFormat(d => this.fieldFormat.convert(d, 'text')); + this.focusYAxis.tickFormat((d) => this.fieldFormat.convert(d, 'text')); } else { // Use default tick formatter. this.focusYAxis.tickFormat(null); @@ -637,7 +631,7 @@ class TimeseriesChartIntl extends Component { combinedData = data.concat(focusForecastData); } - yMin = d3.min(combinedData, d => { + yMin = d3.min(combinedData, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -653,7 +647,7 @@ class TimeseriesChartIntl extends Component { } return metricValue; }); - yMax = d3.max(combinedData, d => { + yMax = d3.max(combinedData, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -681,7 +675,7 @@ class TimeseriesChartIntl extends Component { // between annotation labels, chart lines and anomalies. if (focusAnnotationData && focusAnnotationData.length > 0) { const levels = getAnnotationLevels(focusAnnotationData); - const maxLevel = d3.max(Object.keys(levels).map(key => levels[key])); + const maxLevel = d3.max(Object.keys(levels).map((key) => levels[key])); // TODO needs revisiting to be a more robust normalization yMax = yMax * (1 + (maxLevel + 1) / 5); } @@ -698,9 +692,11 @@ class TimeseriesChartIntl extends Component { timeBuckets.setBounds(bounds); const xAxisTickFormat = timeBuckets.getScaledDateFormat(); focusChart.select('.x.axis').call( - this.focusXAxis.ticks(numTicksForDateFormat(this.vizWidth), xAxisTickFormat).tickFormat(d => { - return moment(d).format(xAxisTickFormat); - }) + this.focusXAxis + .ticks(numTicksForDateFormat(this.vizWidth), xAxisTickFormat) + .tickFormat((d) => { + return moment(d).format(xAxisTickFormat); + }) ); focusChart.select('.y.axis').call(this.focusYAxis); @@ -740,7 +736,7 @@ class TimeseriesChartIntl extends Component { .selectAll('.metric-value') .data( data.filter( - d => + (d) => (d.value !== null || typeof d.anomalyScore === 'number') && !showMultiBucketAnomalyMarker(d) ) @@ -753,20 +749,20 @@ class TimeseriesChartIntl extends Component { .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .on('mouseover', function(d) { + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); // Update all dots to new positions. dots - .attr('cx', d => { + .attr('cx', (d) => { return this.focusXScale(d.date); }) - .attr('cy', d => { + .attr('cy', (d) => { return this.focusYScale(d.value); }) - .attr('class', d => { + .attr('class', (d) => { let markerClass = 'metric-value'; if (_.has(d, 'anomalyScore')) { markerClass += ` anomaly-marker ${getSeverityWithLow(d.anomalyScore).id}`; @@ -778,7 +774,9 @@ class TimeseriesChartIntl extends Component { const multiBucketMarkers = d3 .select('.focus-chart-markers') .selectAll('.multi-bucket') - .data(data.filter(d => d.anomalyScore !== null && showMultiBucketAnomalyMarker(d) === true)); + .data( + data.filter((d) => d.anomalyScore !== null && showMultiBucketAnomalyMarker(d) === true) + ); // Remove multi-bucket markers that are no longer needed. multiBucketMarkers.exit().remove(); @@ -787,14 +785,8 @@ class TimeseriesChartIntl extends Component { multiBucketMarkers .enter() .append('path') - .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') - ) - .on('mouseover', function(d) { + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); @@ -803,15 +795,15 @@ class TimeseriesChartIntl extends Component { multiBucketMarkers .attr( 'transform', - d => `translate(${this.focusXScale(d.date)}, ${this.focusYScale(d.value)})` + (d) => `translate(${this.focusXScale(d.date)}, ${this.focusYScale(d.value)})` ) - .attr('class', d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`); + .attr('class', (d) => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`); // Add rectangular markers for any scheduled events. const scheduledEventMarkers = d3 .select('.focus-chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -828,8 +820,8 @@ class TimeseriesChartIntl extends Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => this.focusXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => this.focusYScale(d.value) - 3); + .attr('x', (d) => this.focusXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr('y', (d) => this.focusYScale(d.value) - 3); // Plot any forecast data in scope. if (focusForecastData !== undefined) { @@ -854,17 +846,17 @@ class TimeseriesChartIntl extends Component { .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .on('mouseover', function(d) { + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); // Update all dots to new positions. forecastDots - .attr('cx', d => { + .attr('cx', (d) => { return this.focusXScale(d.date); }) - .attr('cy', d => { + .attr('cy', (d) => { return this.focusYScale(d.value); }) .attr('class', 'metric-value') @@ -895,14 +887,14 @@ class TimeseriesChartIntl extends Component { ); const zoomOptions = [{ durationMs: autoZoomDuration, label: 'auto' }]; - _.each(ZOOM_INTERVAL_OPTIONS, option => { + _.each(ZOOM_INTERVAL_OPTIONS, (option) => { if (option.duration.asSeconds() > minSecs && option.duration.asSeconds() < boundsSecs) { zoomOptions.push({ durationMs: option.duration.asMilliseconds(), label: option.label }); } }); xPos += zoomLabel.node().getBBox().width + 4; - _.each(zoomOptions, option => { + _.each(zoomOptions, (option) => { const text = zoomGroup .append('a') .attr('data-ms', option.durationMs) @@ -949,7 +941,7 @@ class TimeseriesChartIntl extends Component { } const chartElement = d3.select(this.rootNode); - chartElement.selectAll('.focus-zoom a').on('click', function() { + chartElement.selectAll('.focus-zoom a').on('click', function () { d3.event.preventDefault(); setZoomInterval(d3.select(this).attr('data-ms')); }); @@ -968,7 +960,7 @@ class TimeseriesChartIntl extends Component { const combinedData = contextForecastData === undefined ? data : data.concat(contextForecastData); const valuesRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, item => { + _.each(combinedData, (item) => { valuesRange.min = Math.min(item.value, valuesRange.min); valuesRange.max = Math.max(item.value, valuesRange.max); }); @@ -981,7 +973,7 @@ class TimeseriesChartIntl extends Component { (contextForecastData !== undefined && contextForecastData.length > 0) ) { const boundsRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, item => { + _.each(combinedData, (item) => { boundsRange.min = Math.min(item.lower, boundsRange.min); boundsRange.max = Math.max(item.upper, boundsRange.max); }); @@ -1034,7 +1026,7 @@ class TimeseriesChartIntl extends Component { .outerTickSize(0) .tickPadding(0) .ticks(numTicksForDateFormat(cxtWidth, xAxisTickFormat)) - .tickFormat(d => { + .tickFormat((d) => { return moment(d).format(xAxisTickFormat); }); @@ -1042,16 +1034,16 @@ class TimeseriesChartIntl extends Component { const contextBoundsArea = d3.svg .area() - .x(d => { + .x((d) => { return this.contextXScale(d.date); }) - .y0(d => { + .y0((d) => { return this.contextYScale(Math.min(chartLimits.max, Math.max(d.lower, chartLimits.min))); }) - .y1(d => { + .y1((d) => { return this.contextYScale(Math.max(chartLimits.min, Math.min(d.upper, chartLimits.max))); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); if (modelPlotEnabled === true) { cxtGroup @@ -1063,19 +1055,15 @@ class TimeseriesChartIntl extends Component { const contextValuesLine = d3.svg .line() - .x(d => { + .x((d) => { return this.contextXScale(d.date); }) - .y(d => { + .y((d) => { return this.contextYScale(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); - cxtGroup - .append('path') - .datum(data) - .attr('class', 'values-line') - .attr('d', contextValuesLine); + cxtGroup.append('path').datum(data).attr('class', 'values-line').attr('d', contextValuesLine); drawLineChartDots(data, cxtGroup, contextValuesLine, 1); // Create the path elements for the forecast value line and bounds area. @@ -1107,10 +1095,7 @@ class TimeseriesChartIntl extends Component { .y(this.contextYScale); // Draw the x axis on top of the mask so that the labels are visible. - cxtGroup - .append('g') - .attr('class', 'x axis context-chart-axis') - .call(xAxis); + cxtGroup.append('g').attr('class', 'x axis context-chart-axis').call(xAxis); // Move the x axis labels up so that they are inside the contact chart area. cxtGroup.selectAll('.x.context-chart-axis text').attr('dy', cxtChartHeight - 5); @@ -1120,7 +1105,7 @@ class TimeseriesChartIntl extends Component { this.drawContextBrush(cxtGroup); } - drawContextBrush = contextGroup => { + drawContextBrush = (contextGroup) => { const { contextChartSelected } = this.props; const brush = this.brush; @@ -1128,10 +1113,7 @@ class TimeseriesChartIntl extends Component { const mask = this.mask; // Create the brush for zooming in to the focus area of interest. - brush - .x(contextXScale) - .on('brush', brushing) - .on('brushend', brushed); + brush.x(contextXScale).on('brush', brushing).on('brushend', brushed); contextGroup .append('g') @@ -1143,15 +1125,9 @@ class TimeseriesChartIntl extends Component { // move the left and right resize areas over to // be under the handles - contextGroup - .selectAll('.w rect') - .attr('x', -10) - .attr('width', 10); + contextGroup.selectAll('.w rect').attr('x', -10).attr('width', 10); - contextGroup - .selectAll('.e rect') - .attr('x', 0) - .attr('width', 10); + contextGroup.selectAll('.e rect').attr('x', 0).attr('width', 10); const handleBrushExtent = brush.extent(); @@ -1219,7 +1195,7 @@ class TimeseriesChartIntl extends Component { } // Set the color of the swimlane cells according to whether they are inside the selection. - contextGroup.selectAll('.swimlane-cell').style('fill', d => { + contextGroup.selectAll('.swimlane-cell').style('fill', (d) => { const cellMs = d.date.getTime(); if (cellMs < selectionMin || cellMs > selectionMax) { return anomalyGrayScale(d.score); @@ -1248,15 +1224,9 @@ class TimeseriesChartIntl extends Component { // Need to use the min(earliest) and max(earliest) of the context chart // aggregation to align the axes of the chart and swimlane elements. const xAxisDomain = this.calculateContextXAxisDomain(); - const x = d3.time - .scale() - .range([0, swlWidth]) - .domain(xAxisDomain); + const x = d3.time.scale().range([0, swlWidth]).domain(xAxisDomain); - const y = d3.scale - .linear() - .range([swlHeight, 0]) - .domain([0, swlHeight]); + const y = d3.scale.linear().range([swlHeight, 0]).domain([0, swlHeight]); const xAxis = d3.svg .axis() @@ -1281,10 +1251,7 @@ class TimeseriesChartIntl extends Component { .attr('transform', 'translate(0,' + swlHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); const earliest = xAxisDomain[0].getTime(); const latest = xAxisDomain[1].getTime(); @@ -1294,27 +1261,23 @@ class TimeseriesChartIntl extends Component { cellWidth = 1; } - const cells = swlGroup - .append('g') - .attr('class', 'swimlane-cells') - .selectAll('rect') - .data(data); + const cells = swlGroup.append('g').attr('class', 'swimlane-cells').selectAll('rect').data(data); cells .enter() .append('rect') - .attr('x', d => { + .attr('x', (d) => { return x(d.date); }) .attr('y', 0) .attr('rx', 0) .attr('ry', 0) - .attr('class', d => { + .attr('class', (d) => { return d.score > 0 ? 'swimlane-cell' : 'swimlane-cell-hidden'; }) .attr('width', cellWidth) .attr('height', swlHeight) - .style('fill', d => { + .style('fill', (d) => { return anomalyColorScale(d.score); }); }; @@ -1675,28 +1638,24 @@ class TimeseriesChartIntl extends Component { selectedMarker .enter() .append('path') - .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') - ) - .attr('transform', d => `translate(${focusXScale(d.date)}, ${focusYScale(d.value)})`) + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) + .attr('transform', (d) => `translate(${focusXScale(d.date)}, ${focusYScale(d.value)})`) .attr( 'class', - d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id} highlighted` + (d) => + `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id} highlighted` ); } else { selectedMarker .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .attr('cx', d => focusXScale(d.date)) - .attr('cy', d => focusYScale(d.value)) + .attr('cx', (d) => focusXScale(d.date)) + .attr('cy', (d) => focusYScale(d.value)) .attr( 'class', - d => `anomaly-marker metric-value ${getSeverityWithLow(d.anomalyScore).id} highlighted` + (d) => + `anomaly-marker metric-value ${getSeverityWithLow(d.anomalyScore).id} highlighted` ); } @@ -1713,9 +1672,7 @@ class TimeseriesChartIntl extends Component { } unhighlightFocusChartAnomaly() { - d3.select('.focus-chart-markers') - .selectAll('.anomaly-marker.highlighted') - .remove(); + d3.select('.focus-chart-markers').selectAll('.anomaly-marker.highlighted').remove(); this.props.tooltipService.hide(); } @@ -1732,7 +1689,7 @@ class TimeseriesChartIntl extends Component { } } -export const TimeseriesChart = props => { +export const TimeseriesChart = (props) => { const annotationProp = useObservable(annotation$); if (annotationProp === undefined) { return null; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js index 784ab102fd8ca..2a0fcd57467bd 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js @@ -13,7 +13,7 @@ import React from 'react'; import { TimeseriesChart } from './timeseries_chart'; jest.mock('../../../util/time_buckets', () => ({ - TimeBuckets: function() { + TimeBuckets: function () { this.setBounds = jest.fn(); this.setInterval = jest.fn(); this.getScaledDateFormat = jest.fn(); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts index f23c52fc7119a..0b541d54ee7b3 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts @@ -22,10 +22,7 @@ export const ANNOTATION_MASK_ID = 'mlAnnotationMask'; export function getAnnotationBrush(this: TimeseriesChart) { const focusXScale = this.focusXScale; - const annotateBrush = d3.svg - .brush() - .x(focusXScale) - .on('brushend', brushend.bind(this)); + const annotateBrush = d3.svg.brush().x(focusXScale).on('brushend', brushend.bind(this)); // cast a reference to this so we get the latest state when brushend() gets called function brushend(this: TimeseriesChart) { @@ -114,7 +111,7 @@ export function renderAnnotations( const upperTextMargin = ANNOTATION_UPPER_TEXT_MARGIN; const durations: Dictionary = {}; - focusAnnotationData.forEach(d => { + focusAnnotationData.forEach((d) => { if (d.key !== undefined) { const duration = (d.end_timestamp || 0) - d.timestamp; durations[d.key] = duration; @@ -137,10 +134,7 @@ export function renderAnnotations( .selectAll('g.mlAnnotation') .data(focusAnnotationData || [], (d: Annotation) => d._id || ''); - annotations - .enter() - .append('g') - .classed('mlAnnotation', true); + annotations.enter().append('g').classed('mlAnnotation', true); const rects = annotations.selectAll('.mlAnnotationRect').data((d: Annotation) => [d]); @@ -151,7 +145,7 @@ export function renderAnnotations( .attr('ry', ANNOTATION_RECT_BORDER_RADIUS) .classed('mlAnnotationRect', true) .attr('mask', `url(#${ANNOTATION_MASK_ID})`) - .on('mouseover', function(this: object, d: Annotation) { + .on('mouseover', function (this: object, d: Annotation) { showFocusChartTooltip(d, this); }) .on('mouseout', () => hideFocusChartTooltip()) @@ -189,8 +183,8 @@ export function renderAnnotations( rects.exit().remove(); - const textRects = annotations.selectAll('.mlAnnotationTextRect').data(d => [d]); - const texts = annotations.selectAll('.mlAnnotationText').data(d => [d]); + const textRects = annotations.selectAll('.mlAnnotationTextRect').data((d) => [d]); + const texts = annotations.selectAll('.mlAnnotationText').data((d) => [d]); textRects .enter() @@ -201,10 +195,7 @@ export function renderAnnotations( .attr('rx', ANNOTATION_RECT_BORDER_RADIUS) .attr('ry', ANNOTATION_RECT_BORDER_RADIUS); - texts - .enter() - .append('text') - .classed('mlAnnotationText', true); + texts.enter().append('text').classed('mlAnnotationText', true); function labelXOffset(ts: number) { const earliestMs = focusXScale.domain()[0]; @@ -271,7 +262,7 @@ export function getAnnotationWidth( export function highlightFocusChartAnnotation(annotation: Annotation) { const annotations = d3.selectAll('.mlAnnotation'); - annotations.each(function(d) { + annotations.each(function (d) { // @ts-ignore const element = d3.select(this); @@ -288,7 +279,7 @@ export function highlightFocusChartAnnotation(annotation: Annotation) { export function unhighlightFocusChartAnnotation() { const annotations = d3.selectAll('.mlAnnotation'); - annotations.each(function() { + annotations.each(function () { // @ts-ignore const element = d3.select(this); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts index 4c57eda65a9da..ce5a7565c519b 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts @@ -96,7 +96,7 @@ function getMetricData( interval ) .pipe( - map(resp => { + map((resp) => { _.each(resp.results, (value, time) => { // @ts-ignore obj.results[time] = { @@ -134,7 +134,7 @@ function getChartDetails( } obj.results.functionLabel = functionLabel; - const blankEntityFields = _.filter(entityFields, entity => { + const blankEntityFields = _.filter(entityFields, (entity) => { return entity.fieldValue === null; }); @@ -155,7 +155,7 @@ function getChartDetails( latestMs, }) .then((results: any) => { - _.each(blankEntityFields, field => { + _.each(blankEntityFields, (field) => { // results will not contain keys for non-aggregatable fields, // so store as 0 to indicate over all field values. obj.results.entityData.entities.push({ diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index 4e04a63640a87..34da6b8ef6af6 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -95,7 +95,7 @@ function getEntityControlOptions(fieldValues) { fieldValues.sort(); - return fieldValues.map(value => { + return fieldValues.map((value) => { return { label: value === '' ? EMPTY_FIELD_VALUE_LABEL : value, value }; }); } @@ -206,7 +206,7 @@ export class TimeSeriesExplorer extends React.Component { return fieldNamesWithEmptyValues.length === 0; }; - detectorIndexChangeHandler = e => { + detectorIndexChangeHandler = (e) => { const { appStateHandler } = this.props; const id = e.target.value; if (id !== undefined) { @@ -215,13 +215,13 @@ export class TimeSeriesExplorer extends React.Component { }; toggleShowAnnotationsHandler = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ showAnnotations: !prevState.showAnnotations, })); }; toggleShowForecastHandler = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ showForecast: !prevState.showForecast, })); }; @@ -304,14 +304,14 @@ export class TimeSeriesExplorer extends React.Component { focusAggregationInterval, selectedForecastId, modelPlotEnabled, - entityControls.filter(entity => entity.fieldValue !== null), + entityControls.filter((entity) => entity.fieldValue !== null), searchBounds, selectedJob, TIME_FIELD_NAME ); } - contextChartSelected = selection => { + contextChartSelected = (selection) => { const zoomState = { from: selection.from.toISOString(), to: selection.to.toISOString(), @@ -375,10 +375,10 @@ export class TimeSeriesExplorer extends React.Component { ANOMALIES_TABLE_DEFAULT_QUERY_SIZE ) .pipe( - map(resp => { + map((resp) => { const anomalies = resp.anomalies; const detectorsByJob = mlJobService.detectorsByJob; - anomalies.forEach(anomaly => { + anomalies.forEach((anomaly) => { // Add a detector property to each anomaly. // Default to functionDescription if no description available. // TODO - when job_service is moved server_side, move this to server endpoint. @@ -450,7 +450,7 @@ export class TimeSeriesExplorer extends React.Component { .toPromise(); const entityValues = {}; - entities.forEach(entity => { + entities.forEach((entity) => { let fieldValues; if (partitionField?.name === entity.fieldName) { @@ -468,7 +468,7 @@ export class TimeSeriesExplorer extends React.Component { this.setState({ entitiesLoading: false, entityValues }); }; - setForecastId = forecastId => { + setForecastId = (forecastId) => { this.props.appStateHandler(APP_STATE_ACTION.SET_FORECAST_ID, forecastId); }; @@ -528,7 +528,7 @@ export class TimeSeriesExplorer extends React.Component { // finish() function, called after each data set has been loaded and processed. // The last one to call it will trigger the page render. - const finish = counterVar => { + const finish = (counterVar) => { awaitingCount--; if (awaitingCount === 0 && counterVar === loadCounter) { stateUpdate.hasResults = @@ -575,7 +575,7 @@ export class TimeSeriesExplorer extends React.Component { } }; - const nonBlankEntities = entityControls.filter(entity => { + const nonBlankEntities = entityControls.filter((entity) => { return entity.fieldValue !== null; }); @@ -626,12 +626,12 @@ export class TimeSeriesExplorer extends React.Component { stateUpdate.contextAggregationInterval.expression ) .toPromise() - .then(resp => { + .then((resp) => { const fullRangeChartData = processMetricPlotResults(resp.results, modelPlotEnabled); stateUpdate.contextChartData = fullRangeChartData; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting metric data from elasticsearch:', resp @@ -648,12 +648,12 @@ export class TimeSeriesExplorer extends React.Component { searchBounds.max.valueOf(), stateUpdate.contextAggregationInterval.expression ) - .then(resp => { + .then((resp) => { const fullRangeRecordScoreData = processRecordScoreResults(resp.results); stateUpdate.swimlaneData = fullRangeRecordScoreData; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting bucket anomaly scores from elasticsearch:', resp @@ -669,11 +669,11 @@ export class TimeSeriesExplorer extends React.Component { searchBounds.min.valueOf(), searchBounds.max.valueOf() ) - .then(resp => { + .then((resp) => { stateUpdate.chartDetails = resp.results; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting entity counts from elasticsearch:', resp @@ -701,11 +701,11 @@ export class TimeSeriesExplorer extends React.Component { aggType ) .toPromise() - .then(resp => { + .then((resp) => { stateUpdate.contextForecastData = processForecastResults(resp.results); finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( `Time series explorer - error loading data for forecast ID ${selectedForecastId}`, resp @@ -775,7 +775,7 @@ export class TimeSeriesExplorer extends React.Component { */ getCriteriaFields(detectorIndex, entities) { // Only filter on the entity if the field has a value. - const nonBlankEntities = entities.filter(entity => entity.fieldValue !== null); + const nonBlankEntities = entities.filter((entity) => entity.fieldValue !== null); return [ { fieldName: 'detector_index', @@ -822,7 +822,7 @@ export class TimeSeriesExplorer extends React.Component { } // Populate the map of jobs / detectors / field formatters for the selected IDs and refresh. - mlFieldFormatService.populateFormats([jobId]).catch(err => { + mlFieldFormatService.populateFormats([jobId]).catch((err) => { console.log('Error populating field formats:', err); }); } @@ -839,14 +839,14 @@ export class TimeSeriesExplorer extends React.Component { this.subscriptions.add( this.contextChart$ .pipe( - tap(selection => { + tap((selection) => { this.setState({ zoomFrom: selection.from, zoomTo: selection.to, }); }), debounceTime(500), - tap(selection => { + tap((selection) => { const { contextChartData, contextForecastData, @@ -875,7 +875,7 @@ export class TimeSeriesExplorer extends React.Component { }); } }), - switchMap(selection => { + switchMap((selection) => { const { selectedJobId } = this.props; const jobs = createTimeSeriesJobData(mlJobService.jobs); const selectedJob = mlJobService.getJob(selectedJobId); @@ -987,7 +987,7 @@ export class TimeSeriesExplorer extends React.Component { const tableControlsListener = () => { const { zoomFrom, zoomTo } = this.state; if (zoomFrom !== undefined && zoomTo !== undefined) { - this.loadAnomaliesTableData(zoomFrom.getTime(), zoomTo.getTime()).subscribe(res => + this.loadAnomaliesTableData(zoomFrom.getTime(), zoomTo.getTime()).subscribe((res) => this.setState(res) ); } @@ -1076,7 +1076,7 @@ export class TimeSeriesExplorer extends React.Component { const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues(); const arePartitioningFieldsProvided = this.arePartitioningFieldsProvided(); - const detectorSelectOptions = getViewableDetectors(selectedJob).map(d => ({ + const detectorSelectOptions = getViewableDetectors(selectedJob).map((d) => ({ value: d.index, text: d.detector_description, })); @@ -1148,7 +1148,7 @@ export class TimeSeriesExplorer extends React.Component { /> - {entityControls.map(entity => { + {entityControls.map((entity) => { const entityKey = `${entity.fieldName}`; const forceSelection = !hasEmptyFieldValues && entity.fieldValue === null; hasEmptyFieldValues = !hasEmptyFieldValues && forceSelection; @@ -1219,7 +1219,7 @@ export class TimeSeriesExplorer extends React.Component { {chartDetails.entityData.entities.length > 0 && '('} {chartDetails.entityData.entities - .map(entity => { + .map((entity) => { return `${entity.fieldName}: ${entity.fieldValue}`; }) .join(', ')} @@ -1300,7 +1300,7 @@ export class TimeSeriesExplorer extends React.Component {
    - {tooltipService => ( + {(tooltipService) => ( { + return singleTimeSeriesJobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, @@ -110,7 +110,7 @@ export function processDataForFocusAnomalies( if (chartData !== undefined && chartData.length > 0) { lastChartDataPointTime = chartData[chartData.length - 1].date.getTime(); } - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { const recordTime = record[TIME_FIELD_NAME]; const chartPoint = findChartPointForAnomalyTime(chartData, recordTime, aggregationInterval); if (chartPoint === undefined) { @@ -123,7 +123,7 @@ export function processDataForFocusAnomalies( timesToAddPointsFor.sort((a, b) => a - b); - timesToAddPointsFor.forEach(time => { + timesToAddPointsFor.forEach((time) => { const pointToAdd = { date: new Date(time), value: null, @@ -138,7 +138,7 @@ export function processDataForFocusAnomalies( // Iterate through the anomaly records adding the // various properties required for display. - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { // Look for a chart point with the same time as the record. // If none found, find closest time in chartData set. const recordTime = record[TIME_FIELD_NAME]; diff --git a/x-pack/plugins/ml/public/application/util/calc_auto_interval.js b/x-pack/plugins/ml/public/application/util/calc_auto_interval.js index 29064db6689d0..c0a001b968970 100644 --- a/x-pack/plugins/ml/public/application/util/calc_auto_interval.js +++ b/x-pack/plugins/ml/public/application/util/calc_auto_interval.js @@ -81,7 +81,7 @@ export function timeBucketsCalcAutoIntervalProvider() { return moment.duration(ms, 'ms'); } - return function(buckets, duration) { + return function (buckets, duration) { const interval = pick(buckets, duration); if (interval) { return moment.duration(interval._data); @@ -111,7 +111,7 @@ export function timeBucketsCalcAutoIntervalProvider() { true ), - lessThan: find(revRoundingRules, function(upperBound, lowerBound, target) { + lessThan: find(revRoundingRules, function (upperBound, lowerBound, target) { // upperBound - first duration in rule // lowerBound - second duration in rule // target - target interval in milliseconds. Must not return intervals less than this duration. diff --git a/x-pack/plugins/ml/public/application/util/chart_utils.js b/x-pack/plugins/ml/public/application/util/chart_utils.js index 5a062320ca6c5..2caf964cb9774 100644 --- a/x-pack/plugins/ml/public/application/util/chart_utils.js +++ b/x-pack/plugins/ml/public/application/util/chart_utils.js @@ -21,7 +21,7 @@ export const SCHEDULED_EVENT_SYMBOL_HEIGHT = 5; const MAX_LABEL_WIDTH = 100; export function chartLimits(data = []) { - const domain = d3.extent(data, d => { + const domain = d3.extent(data, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -32,7 +32,7 @@ export function chartLimits(data = []) { const limits = { max: domain[1], min: domain[0] }; if (limits.max === limits.min) { - limits.max = d3.max(data, d => { + limits.max = d3.max(data, (d) => { if (d.typical) { return Math.max(d.value, d.typical); } else { @@ -42,7 +42,7 @@ export function chartLimits(data = []) { return d.value; } }); - limits.min = d3.min(data, d => { + limits.min = d3.min(data, (d) => { if (d.typical) { return Math.min(d.value, d.typical); } else { @@ -96,10 +96,7 @@ export function drawLineChartDots(data, lineChartGroup, lineChartValuesLine, rad // use d3's enter/update/exit pattern to render the dots const dots = dotGroup.selectAll('circle').data(dotsData); - dots - .enter() - .append('circle') - .attr('r', radius); + dots.enter().append('circle').attr('r', radius); dots.attr('cx', lineChartValuesLine.x()).attr('cy', lineChartValuesLine.y()); @@ -118,7 +115,7 @@ export function filterAxisLabels(selection, chartWidth) { .selectAll('.tick text') // don't refactor this to an arrow function because // we depend on using `this` here. - .text(function() { + .text(function () { const parent = d3.select(this.parentNode); const labelWidth = parent.node().getBBox().width; const labelXPos = d3.transform(parent.attr('transform')).translate[0]; @@ -142,13 +139,13 @@ export function getChartType(config) { if ( EVENT_DISTRIBUTION_ENABLED && config.functionDescription === 'rare' && - config.entityFields.some(f => f.fieldType === 'over') === false + config.entityFields.some((f) => f.fieldType === 'over') === false ) { chartType = CHART_TYPE.EVENT_DISTRIBUTION; } else if ( POPULATION_DISTRIBUTION_ENABLED && config.functionDescription !== 'rare' && - config.entityFields.some(f => f.fieldType === 'over') && + config.entityFields.some((f) => f.fieldType === 'over') && config.metricFunction !== null // Event distribution chart relies on the ML function mapping to an ES aggregation ) { chartType = CHART_TYPE.POPULATION_DISTRIBUTION; @@ -161,12 +158,12 @@ export function getChartType(config) { // Check that the config does not use script fields defined in the datafeed config. if (config.datafeedConfig !== undefined && config.datafeedConfig.script_fields !== undefined) { const scriptFields = Object.keys(config.datafeedConfig.script_fields); - const checkFields = config.entityFields.map(entity => entity.fieldName); + const checkFields = config.entityFields.map((entity) => entity.fieldName); if (config.metricFieldName) { checkFields.push(config.metricFieldName); } const usesScriptFields = - checkFields.find(fieldName => scriptFields.includes(fieldName)) !== undefined; + checkFields.find((fieldName) => scriptFields.includes(fieldName)) !== undefined; if (usesScriptFields === true) { // Only single metric chart type supports query of model plot data. chartType = CHART_TYPE.SINGLE_METRIC; @@ -193,7 +190,7 @@ export function getExploreSeriesLink(series) { // Initially pass them in the mlTimeSeriesExplorer part of the AppState. // TODO - do we want to pass the entities via the filter? const entityCondition = {}; - series.entityFields.forEach(entity => { + series.entityFields.forEach((entity) => { entityCondition[entity.fieldName] = entity.fieldValue; }); @@ -310,7 +307,8 @@ const LABEL_WRAP_THRESHOLD = 60; // and entity fields) is above LABEL_WRAP_THRESHOLD. export function isLabelLengthAboveThreshold({ detectorLabel, entityFields }) { const labelLength = - detectorLabel.length + entityFields.map(d => `${d.fieldName} ${d.fieldValue}`).join(' ').length; + detectorLabel.length + + entityFields.map((d) => `${d.fieldName} ${d.fieldValue}`).join(' ').length; return labelLength > LABEL_WRAP_THRESHOLD; } @@ -335,13 +333,10 @@ export function getXTransform(t) { export function removeLabelOverlap(axis, startTimeMs, tickInterval, width) { // Put emphasis on all tick lines, will again de-emphasize the // ones where we remove the label in the next steps. - axis - .selectAll('g.tick') - .select('line') - .classed('ml-tick-emphasis', true); + axis.selectAll('g.tick').select('line').classed('ml-tick-emphasis', true); function getNeighborTickFactory(operator) { - return function(ts) { + return function (ts) { switch (operator) { case TICK_DIRECTION.PREVIOUS: return ts - tickInterval; @@ -353,8 +348,8 @@ export function removeLabelOverlap(axis, startTimeMs, tickInterval, width) { function getTickDataFactory(operator) { const getNeighborTick = getNeighborTickFactory(operator); - const fn = function(ts) { - const filteredTicks = axis.selectAll('.tick').filter(d => d === ts); + const fn = function (ts) { + const filteredTicks = axis.selectAll('.tick').filter((d) => d === ts); if (filteredTicks.length === 0 || filteredTicks[0].length === 0) { return false; diff --git a/x-pack/plugins/ml/public/application/util/chart_utils.test.js b/x-pack/plugins/ml/public/application/util/chart_utils.test.js index 57aea3c0ab5aa..b7cf11c088a1e 100644 --- a/x-pack/plugins/ml/public/application/util/chart_utils.test.js +++ b/x-pack/plugins/ml/public/application/util/chart_utils.test.js @@ -10,7 +10,7 @@ jest.mock('./dependency_cache', () => { const dateMath = require('@elastic/datemath'); let _time = undefined; const timefilter = { - setTime: time => { + setTime: (time) => { _time = time; }, getActiveBounds: () => { @@ -436,15 +436,12 @@ describe('ML - chart utils', () => { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); const tickValues = getTickValues(startTimeMs, interval, plotEarliest, plotLatest); xAxis.tickValues(tickValues); - const svg = chartElement - .append('svg') - .attr('width', svgWidth) - .attr('height', svgHeight); + const svg = chartElement.append('svg').attr('width', svgWidth).attr('height', svgHeight); const axes = svg.append('g'); diff --git a/x-pack/plugins/ml/public/application/util/custom_url_utils.ts b/x-pack/plugins/ml/public/application/util/custom_url_utils.ts index 47f7b6f4d4fd2..20bb1c7f60597 100644 --- a/x-pack/plugins/ml/public/application/util/custom_url_utils.ts +++ b/x-pack/plugins/ml/public/application/util/custom_url_utils.ts @@ -170,7 +170,7 @@ function buildKibanaUrl(urlConfig: UrlConfig, record: CustomUrlAnomalyRecordDoc) // Split query string by AND operator. .split(/\sand\s/i) // Get property name from `influencerField:$influencerField$` string. - .map(v => v.split(':')[0]); + .map((v) => v.split(':')[0]); const queryParts: string[] = []; const joinOperator = ' AND '; @@ -226,7 +226,7 @@ export function isValidLabel(label: string, savedCustomUrls: any[]) { let isValid = label !== undefined && label.trim().length > 0; if (isValid === true && savedCustomUrls !== undefined) { // Check the label is unique. - const existingLabels = savedCustomUrls.map(customUrl => customUrl.url_name); + const existingLabels = savedCustomUrls.map((customUrl) => customUrl.url_name); isValid = !existingLabels.includes(label); } return isValid; diff --git a/x-pack/plugins/ml/public/application/util/dependency_cache.ts b/x-pack/plugins/ml/public/application/util/dependency_cache.ts index 356da38d5ad08..2586dfe45345e 100644 --- a/x-pack/plugins/ml/public/application/util/dependency_cache.ts +++ b/x-pack/plugins/ml/public/application/util/dependency_cache.ts @@ -204,7 +204,7 @@ export function getGetUrlGenerator() { export function clearCache() { console.log('clearing dependency cache'); // eslint-disable-line no-console - Object.keys(cache).forEach(k => { + Object.keys(cache).forEach((k) => { cache[k as keyof DependencyCache] = null; }); } diff --git a/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts b/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts index 6052cd0dfaa21..4275142d63d56 100644 --- a/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts +++ b/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts @@ -68,7 +68,7 @@ describe('ML - field type utils', () => { const mlKeys = Object.keys(ML_JOB_FIELD_TYPES); const receivedMlLabels: Record = {}; const testStorage = mlJobTypeAriaLabels; - mlKeys.forEach(constant => { + mlKeys.forEach((constant) => { receivedMlLabels[constant] = getMLJobTypeAriaLabel( ML_JOB_FIELD_TYPES[constant as keyof typeof ML_JOB_FIELD_TYPES] ); diff --git a/x-pack/plugins/ml/public/application/util/field_types_utils.ts b/x-pack/plugins/ml/public/application/util/field_types_utils.ts index d6e0a885269e8..8cf2661d7b74d 100644 --- a/x-pack/plugins/ml/public/application/util/field_types_utils.ts +++ b/x-pack/plugins/ml/public/application/util/field_types_utils.ts @@ -73,7 +73,7 @@ export const mlJobTypeAriaLabels = { export const getMLJobTypeAriaLabel = (type: string) => { const requestedFieldType = Object.keys(ML_JOB_FIELD_TYPES).find( - k => ML_JOB_FIELD_TYPES[k as keyof typeof ML_JOB_FIELD_TYPES] === type + (k) => ML_JOB_FIELD_TYPES[k as keyof typeof ML_JOB_FIELD_TYPES] === type ); if (requestedFieldType === undefined) { return null; diff --git a/x-pack/plugins/ml/public/application/util/index_utils.ts b/x-pack/plugins/ml/public/application/util/index_utils.ts index b8cf2e6fa8e96..192552b25d15a 100644 --- a/x-pack/plugins/ml/public/application/util/index_utils.ts +++ b/x-pack/plugins/ml/public/application/util/index_utils.ts @@ -28,7 +28,7 @@ export function loadIndexPatterns(indexPatterns: IndexPatternsContract) { fields: ['id', 'title', 'type', 'fields'], perPage: 10000, }) - .then(response => { + .then((response) => { indexPatternCache = response.savedObjects; return indexPatternCache; }); @@ -41,7 +41,7 @@ export function loadSavedSearches() { type: 'search', perPage: 10000, }) - .then(response => { + .then((response) => { savedSearchesCache = response.savedObjects; return savedSearchesCache; }); @@ -62,7 +62,7 @@ export function getIndexPatternsContract() { } export function getIndexPatternNames() { - return indexPatternCache.map(i => i.attributes && i.attributes.title); + return indexPatternCache.map((i) => i.attributes && i.attributes.title); } export function getIndexPatternIdFromName(name: string) { @@ -88,7 +88,7 @@ export async function getIndexPatternAndSavedSearch(savedSearchId: string) { if (ss === null) { return resp; } - const indexPatternId = ss.references.find(r => r.type === 'index-pattern')?.id; + const indexPatternId = ss.references.find((r) => r.type === 'index-pattern')?.id; resp.indexPattern = await getIndexPatternById(indexPatternId!); resp.savedSearch = ss; return resp; @@ -111,7 +111,7 @@ export function getIndexPatternById(id: string): Promise { } export function getSavedSearchById(id: string): SavedSearchSavedObject | undefined { - return savedSearchesCache.find(s => s.id === id); + return savedSearchesCache.find((s) => s.id === id); } /** diff --git a/x-pack/plugins/ml/public/application/util/string_utils.js b/x-pack/plugins/ml/public/application/util/string_utils.js index 66835984df5e5..450c166f90300 100644 --- a/x-pack/plugins/ml/public/application/util/string_utils.js +++ b/x-pack/plugins/ml/public/application/util/string_utils.js @@ -83,7 +83,7 @@ function quoteField(field) { // re-order an object based on the value of the keys export function sortByKey(list, reverse, comparator) { - let keys = _.sortBy(_.keys(list), key => { + let keys = _.sortBy(_.keys(list), (key) => { return comparator ? comparator(list[key], key) : key; }); @@ -93,7 +93,7 @@ export function sortByKey(list, reverse, comparator) { return _.object( keys, - _.map(keys, key => { + _.map(keys, (key) => { return list[key]; }) ); @@ -121,7 +121,7 @@ export function mlEscape(str) { "'": ''', '/': '/', }; - return String(str).replace(/[&<>"'\/]/g, s => entityMap[s]); + return String(str).replace(/[&<>"'\/]/g, (s) => entityMap[s]); } // Escapes reserved characters for use in Elasticsearch query terms. diff --git a/x-pack/plugins/ml/public/application/util/string_utils.test.ts b/x-pack/plugins/ml/public/application/util/string_utils.test.ts index d940fce2ee1d5..25f1cbd3abac3 100644 --- a/x-pack/plugins/ml/public/application/util/string_utils.test.ts +++ b/x-pack/plugins/ml/public/application/util/string_utils.test.ts @@ -102,7 +102,7 @@ describe('ML - string utils', () => { elephant: 'trunk', }; - const valueComparator = function(value: string) { + const valueComparator = function (value: string) { return value; }; diff --git a/x-pack/plugins/ml/public/application/util/time_buckets.js b/x-pack/plugins/ml/public/application/util/time_buckets.js index ccc51982678b7..2b23eca1ab5c0 100644 --- a/x-pack/plugins/ml/public/application/util/time_buckets.js +++ b/x-pack/plugins/ml/public/application/util/time_buckets.js @@ -46,7 +46,7 @@ export function TimeBuckets(timeBucketsConfig) { * * @returns {undefined} */ -TimeBuckets.prototype.setBarTarget = function(bt) { +TimeBuckets.prototype.setBarTarget = function (bt) { this.barTarget = bt; }; @@ -57,7 +57,7 @@ TimeBuckets.prototype.setBarTarget = function(bt) { * * @returns {undefined} */ -TimeBuckets.prototype.setMaxBars = function(mb) { +TimeBuckets.prototype.setMaxBars = function (mb) { this.maxBars = mb; }; @@ -72,7 +72,7 @@ TimeBuckets.prototype.setMaxBars = function(mb) { * * @returns {undefined} */ -TimeBuckets.prototype.setBounds = function(input) { +TimeBuckets.prototype.setBounds = function (input) { if (!input) return this.clearBounds(); let bounds; @@ -83,9 +83,7 @@ TimeBuckets.prototype.setBounds = function(input) { bounds = Array.isArray(input) ? input : []; } - const moments = _(bounds) - .map(_.ary(moment, 1)) - .sortBy(Number); + const moments = _(bounds).map(_.ary(moment, 1)).sortBy(Number); const valid = moments.size() === 2 && moments.every(isValidMoment); if (!valid) { @@ -105,7 +103,7 @@ TimeBuckets.prototype.setBounds = function(input) { * * @return {undefined} */ -TimeBuckets.prototype.clearBounds = function() { +TimeBuckets.prototype.clearBounds = function () { this._lb = this._ub = null; }; @@ -114,7 +112,7 @@ TimeBuckets.prototype.clearBounds = function() { * * @return {Boolean} */ -TimeBuckets.prototype.hasBounds = function() { +TimeBuckets.prototype.hasBounds = function () { return isValidMoment(this._ub) && isValidMoment(this._lb); }; @@ -130,7 +128,7 @@ TimeBuckets.prototype.hasBounds = function() { * min and max. Each property will be a moment() * object */ -TimeBuckets.prototype.getBounds = function() { +TimeBuckets.prototype.getBounds = function () { if (!this.hasBounds()) return; return { min: this._lb, @@ -145,7 +143,7 @@ TimeBuckets.prototype.getBounds = function() { * * @return {moment.duration|undefined} */ -TimeBuckets.prototype.getDuration = function() { +TimeBuckets.prototype.getDuration = function () { if (!this.hasBounds()) return; return moment.duration(this._ub - this._lb, 'ms'); }; @@ -161,7 +159,7 @@ TimeBuckets.prototype.getDuration = function() { * * @param {string|moment.duration} input - see desc */ -TimeBuckets.prototype.setInterval = function(input) { +TimeBuckets.prototype.setInterval = function (input) { // Preserve the original units because they're lost when the interval is converted to a // moment duration object. this.originalInterval = input; @@ -223,7 +221,7 @@ TimeBuckets.prototype.setInterval = function(input) { * * @return {[type]} [description] */ -TimeBuckets.prototype.getInterval = function() { +TimeBuckets.prototype.getInterval = function () { const self = this; const duration = self.getDuration(); return decorateInterval(maybeScaleInterval(readInterval()), duration); @@ -268,7 +266,7 @@ TimeBuckets.prototype.getInterval = function() { * * @return {moment.duration|undefined} */ -TimeBuckets.prototype.getIntervalToNearestMultiple = function(divisorSecs) { +TimeBuckets.prototype.getIntervalToNearestMultiple = function (divisorSecs) { const interval = this.getInterval(); const intervalSecs = interval.asSeconds(); @@ -306,7 +304,7 @@ TimeBuckets.prototype.getIntervalToNearestMultiple = function(divisorSecs) { * * @return {string} */ -TimeBuckets.prototype.getScaledDateFormat = function() { +TimeBuckets.prototype.getScaledDateFormat = function () { const interval = this.getInterval(); const rules = this._timeBucketsConfig['dateFormat:scaled']; @@ -320,7 +318,7 @@ TimeBuckets.prototype.getScaledDateFormat = function() { return this._timeBucketsConfig.dateFormat; }; -TimeBuckets.prototype.getScaledDateFormatter = function() { +TimeBuckets.prototype.getScaledDateFormatter = function () { const fieldFormats = getFieldFormats(); const DateFieldFormat = fieldFormats.getType(FIELD_FORMAT_IDS.DATE); return new DateFieldFormat( diff --git a/x-pack/plugins/ml/public/application/util/url_state.ts b/x-pack/plugins/ml/public/application/util/url_state.ts index b0699116895d4..beff5340ce7e4 100644 --- a/x-pack/plugins/ml/public/application/util/url_state.ts +++ b/x-pack/plugins/ml/public/application/util/url_state.ts @@ -35,7 +35,7 @@ export function getUrlState(search: string): Dictionary { const parsedQueryString = parse(search, { sort: false }); try { - Object.keys(parsedQueryString).forEach(a => { + Object.keys(parsedQueryString).forEach((a) => { if (isRisonSerializationRequired(a)) { urlState[a] = decode(parsedQueryString[a] as string); } else { @@ -77,7 +77,7 @@ export const useUrlState = (accessor: string): UrlState => { urlState[accessor][attribute] = value; } else { const attributes = attribute; - Object.keys(attributes).forEach(a => { + Object.keys(attributes).forEach((a) => { urlState[accessor][a] = attributes[a]; }); } @@ -85,7 +85,7 @@ export const useUrlState = (accessor: string): UrlState => { try { const oldLocationSearch = stringify(parsedQueryString, { sort: false, encode: false }); - Object.keys(urlState).forEach(a => { + Object.keys(urlState).forEach((a) => { if (isRisonSerializationRequired(a)) { parsedQueryString[a] = encode(urlState[a]); } else { diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx index 1f26bce165e9f..b53b08e5f6146 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx @@ -96,7 +96,7 @@ export class AnomalySwimlaneEmbeddable extends Embeddable< embeddableInput={this.getInput$()} services={this.services} refresh={this.reload$.asObservable()} - onOutputChange={output => this.updateOutput(output)} + onOutputChange={(output) => this.updateOutput(output)} />, node ); diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx index ab25137f2b7d6..00d47c0d897c7 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx @@ -38,7 +38,7 @@ export interface AnomalySwimlaneInitializerProps { onCancel: () => void; } -const limitOptions = [5, 10, 25, 50].map(limit => ({ +const limitOptions = [5, 10, 25, 50].map((limit) => ({ value: limit, text: `${limit}`, })); @@ -72,7 +72,7 @@ export const AnomalySwimlaneInitializer: FC = ( }, ]; - const viewBySwimlaneOptions = ['', ...influencers].map(influencer => { + const viewBySwimlaneOptions = ['', ...influencers].map((influencer) => { return { value: influencer, text: influencer, @@ -112,7 +112,7 @@ export const AnomalySwimlaneInitializer: FC = ( id="panelTitle" name="panelTitle" value={panelTitle} - onChange={e => setPanelTitle(e.target.value)} + onChange={(e) => setPanelTitle(e.target.value)} isInvalid={!isPanelTitleValid} /> @@ -135,7 +135,7 @@ export const AnomalySwimlaneInitializer: FC = ( })} options={swimlaneTypeOptions} idSelected={swimlaneType} - onChange={id => setSwimlaneType(id as SWIMLANE_TYPE)} + onChange={(id) => setSwimlaneType(id as SWIMLANE_TYPE)} /> @@ -151,7 +151,7 @@ export const AnomalySwimlaneInitializer: FC = ( name="selectViewBy" options={viewBySwimlaneOptions} value={viewBySwimlaneFieldName} - onChange={e => setViewBySwimlaneFieldName(e.target.value)} + onChange={(e) => setViewBySwimlaneFieldName(e.target.value)} /> = ( name="limit" options={limitOptions} value={limit} - onChange={e => setLimit(Number(e.target.value))} + onChange={(e) => setLimit(Number(e.target.value))} /> diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx index 89c237b205287..e5d8584683c55 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx @@ -79,11 +79,11 @@ export const ExplorerSwimlaneContainer: FC = ({ return ( - {resizeRef => ( + {(resizeRef) => (
    { + ref={(el) => { resizeRef(el); }} > @@ -93,7 +93,7 @@ export const ExplorerSwimlaneContainer: FC = ({ {chartWidth > 0 && swimlaneData && swimlaneType ? ( - {tooltipService => ( + {(tooltipService) => ( anomalyDetectorService.getJobs$(jobsIds)) + switchMap((jobsIds) => anomalyDetectorService.getJobs$(jobsIds)) ); } @@ -74,7 +74,7 @@ export function useSwimlaneInputResolver( getJobsObservable(embeddableInput, anomalyDetectorService), embeddableInput, chartWidth$.pipe( - skipWhile(v => !v), + skipWhile((v) => !v), distinctUntilChanged((prev, curr) => { // emit only if the width has been changed significantly return Math.abs(curr - prev) < RESIZE_IGNORED_DIFF_PX; @@ -100,7 +100,7 @@ export function useSwimlaneInputResolver( setSwimlaneType(swimlaneTypeInput); } - const explorerJobs: ExplorerJob[] = jobs.map(job => { + const explorerJobs: ExplorerJob[] = jobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, @@ -119,7 +119,7 @@ export function useSwimlaneInputResolver( } return from(explorerService.loadOverallData(explorerJobs, swimlaneContainerWidth)).pipe( - switchMap(overallSwimlaneData => { + switchMap((overallSwimlaneData) => { const { earliest, latest } = overallSwimlaneData; if (overallSwimlaneData && swimlaneTypeInput === SWIMLANE_TYPE.VIEW_BY) { @@ -134,7 +134,7 @@ export function useSwimlaneInputResolver( appliedFilters ) ).pipe( - map(viewBySwimlaneData => { + map((viewBySwimlaneData) => { return { ...viewBySwimlaneData!, earliest, @@ -147,12 +147,12 @@ export function useSwimlaneInputResolver( }) ); }), - catchError(e => { + catchError((e) => { setError(e.body); return of(undefined); }) ) - .subscribe(data => { + .subscribe((data) => { if (data !== undefined) { setError(null); setSwimlaneData(data); diff --git a/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts b/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts index 543cf4ddad982..5ad0db3c58ce4 100644 --- a/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts +++ b/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts @@ -31,7 +31,7 @@ describe('ML - Endpoints', () => { factory(obj: ClientAction) { // add each endpoint URL to a list if (obj.urls) { - obj.urls.forEach(url => { + obj.urls.forEach((url) => { urls.push(url.fmt); }); } @@ -52,7 +52,7 @@ describe('ML - Endpoints', () => { describe('paths', () => { it(`should start with ${PATH_START}`, () => { - urls.forEach(url => { + urls.forEach((url) => { expect(url[0]).toEqual(PATH_START); }); }); diff --git a/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts b/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts index 8e350b8382276..a5c04092fab77 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts @@ -13,7 +13,7 @@ import { export function getAdminCapabilities() { const caps: any = {}; - Object.keys(adminMlCapabilities).forEach(k => { + Object.keys(adminMlCapabilities).forEach((k) => { caps[k] = true; }); return { ...getUserCapabilities(), ...caps } as MlCapabilities; @@ -21,7 +21,7 @@ export function getAdminCapabilities() { export function getUserCapabilities() { const caps: any = {}; - Object.keys(userMlCapabilities).forEach(k => { + Object.keys(userMlCapabilities).forEach((k) => { caps[k] = true; }); diff --git a/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts b/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts index aef22debf3642..5b8cbc4bdbbe8 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts @@ -40,13 +40,13 @@ function getSwitcher(license$: Observable, logger: Logger): Capabiliti const originalCapabilities = cloneDeep(mlCaps); // not full licence, switch off all capabilities - Object.keys(mlCaps).forEach(k => { + Object.keys(mlCaps).forEach((k) => { mlCaps[k as keyof MlCapabilities] = false; }); // for a basic license, reapply the original capabilities for the basic license features if (isMinimumLicense(license)) { - basicLicenseMlCapabilities.forEach(c => (mlCaps[c] = originalCapabilities[c])); + basicLicenseMlCapabilities.forEach((c) => (mlCaps[c] = originalCapabilities[c])); } return capabilities; diff --git a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts index 746c9da47d0ad..3354523b1718c 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts @@ -27,7 +27,7 @@ const callWithRequestUpgrade = async () => ({ upgrade_mode: true }); describe('check_capabilities', () => { describe('getCapabilities() - right number of capabilities', () => { - test('kibana capabilities count', async done => { + test('kibana capabilities count', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getAdminCapabilities(), @@ -42,7 +42,7 @@ describe('check_capabilities', () => { }); describe('getCapabilities() with security', () => { - test('ml_user capabilities only', async done => { + test('ml_user capabilities only', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getUserCapabilities(), @@ -91,7 +91,7 @@ describe('check_capabilities', () => { done(); }); - test('full capabilities', async done => { + test('full capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getAdminCapabilities(), @@ -140,7 +140,7 @@ describe('check_capabilities', () => { done(); }); - test('upgrade in progress with full capabilities', async done => { + test('upgrade in progress with full capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestUpgrade, getAdminCapabilities(), @@ -189,7 +189,7 @@ describe('check_capabilities', () => { done(); }); - test('upgrade in progress with partial capabilities', async done => { + test('upgrade in progress with partial capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestUpgrade, getUserCapabilities(), @@ -238,7 +238,7 @@ describe('check_capabilities', () => { done(); }); - test('full capabilities, ml disabled in space', async done => { + test('full capabilities, ml disabled in space', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getDefaultCapabilities(), @@ -288,7 +288,7 @@ describe('check_capabilities', () => { }); }); - test('full capabilities, basic license, ml disabled in space', async done => { + test('full capabilities, basic license, ml disabled in space', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getDefaultCapabilities(), diff --git a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts index d955cf981faca..ce775a425fa73 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts @@ -41,7 +41,7 @@ export function capabilitiesProvider( } function disableAdminPrivileges(capabilities: MlCapabilities) { - Object.keys(adminMlCapabilities).forEach(k => { + Object.keys(adminMlCapabilities).forEach((k) => { capabilities[k as keyof MlCapabilities] = false; }); capabilities.canCreateAnnotation = false; diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts index 8d70b11bce152..0d88fd0cd1bb0 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts @@ -35,7 +35,7 @@ describe('annotation_service', () => { }); describe('deleteAnnotation()', () => { - it('should delete annotation', async done => { + it('should delete annotation', async (done) => { const { deleteAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -56,7 +56,7 @@ describe('annotation_service', () => { }); describe('getAnnotation()', () => { - it('should get annotations for specific job', async done => { + it('should get annotations for specific job', async (done) => { const { getAnnotations } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -104,7 +104,7 @@ describe('annotation_service', () => { }); describe('indexAnnotation()', () => { - it('should index annotation', async done => { + it('should index annotation', async (done) => { const { indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -132,7 +132,7 @@ describe('annotation_service', () => { done(); }); - it('should remove ._id and .key before updating annotation', async done => { + it('should remove ._id and .key before updating annotation', async (done) => { const { indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -164,7 +164,7 @@ describe('annotation_service', () => { done(); }); - it('should update annotation text and the username for modified_username', async done => { + it('should update annotation text and the username for modified_username', async (done) => { const { getAnnotations, indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js index d2e4311bf6f22..2e03a9532c831 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js @@ -128,7 +128,7 @@ export function estimateBucketSpanFactory( this.polledDataChecker .run() - .then(result => { + .then((result) => { // if the data is polled, set a minimum threshold // of bucket span if (result.isPolled) { @@ -154,10 +154,10 @@ export function estimateBucketSpanFactory( } }; - _.each(this.checkers, check => { + _.each(this.checkers, (check) => { check.check .run() - .then(interval => { + .then((interval) => { check.result = interval; runComplete(); }) @@ -170,7 +170,7 @@ export function estimateBucketSpanFactory( }); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -188,8 +188,8 @@ export function estimateBucketSpanFactory( const pos = i * numberOfSplitFields; let resultsSubset = allResults.slice(pos, pos + numberOfSplitFields); // remove results of tests which have failed - resultsSubset = _.remove(resultsSubset, res => res !== null); - resultsSubset = _.sortBy(resultsSubset, r => r.ms); + resultsSubset = _.remove(resultsSubset, (res) => res !== null); + resultsSubset = _.sortBy(resultsSubset, (r) => r.ms); const tempMedian = this.findMedian(resultsSubset); if (tempMedian !== null) { @@ -197,7 +197,7 @@ export function estimateBucketSpanFactory( } } - reducedResults = _.sortBy(reducedResults, r => r.ms); + reducedResults = _.sortBy(reducedResults, (r) => r.ms); return this.findMedian(reducedResults); } @@ -243,7 +243,7 @@ export function estimateBucketSpanFactory( } } - const getFieldCardinality = function(index, field) { + const getFieldCardinality = function (index, field) { return new Promise((resolve, reject) => { callAsCurrentUser('search', { index, @@ -258,24 +258,24 @@ export function estimateBucketSpanFactory( }, }, }) - .then(resp => { + .then((resp) => { const value = _.get(resp, ['aggregations', 'field_count', 'value'], 0); resolve(value); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); }; - const getRandomFieldValues = function(index, field, query) { + const getRandomFieldValues = function (index, field, query) { let fieldValues = []; return new Promise((resolve, reject) => { const NUM_PARTITIONS = 10; // use a partitioned search to load 10 random fields // load ten fields, to test that there are at least 10. getFieldCardinality(index, field) - .then(value => { + .then((value) => { const numPartitions = Math.floor(value / NUM_PARTITIONS) || 1; callAsCurrentUser('search', { index, @@ -295,24 +295,24 @@ export function estimateBucketSpanFactory( }, }, }) - .then(partitionResp => { + .then((partitionResp) => { if (_.has(partitionResp, 'aggregations.fields_bucket_counts.buckets')) { const buckets = partitionResp.aggregations.fields_bucket_counts.buckets; - fieldValues = _.map(buckets, b => b.key); + fieldValues = _.map(buckets, (b) => b.key); } resolve(fieldValues); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); }; - return function(formConfig) { + return function (formConfig) { if (typeof formConfig !== 'object' || formConfig === null) { throw new Error('Invalid formConfig: formConfig needs to be an object.'); } @@ -342,7 +342,7 @@ export function estimateBucketSpanFactory( includeDefaults: true, filterPath: '*.*max_buckets', }) - .then(settings => { + .then((settings) => { if (typeof settings !== 'object') { reject('Unable to retrieve cluster settings'); } @@ -368,10 +368,10 @@ export function estimateBucketSpanFactory( bucketSpanEstimator .run() - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }; @@ -380,10 +380,10 @@ export function estimateBucketSpanFactory( // bucket span tests. if (formConfig.splitField !== undefined) { getRandomFieldValues(formConfig.index, formConfig.splitField, formConfig.query) - .then(splitFieldValues => { + .then((splitFieldValues) => { runEstimator(splitFieldValues); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } else { @@ -391,7 +391,7 @@ export function estimateBucketSpanFactory( runEstimator(); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } @@ -413,7 +413,7 @@ export function estimateBucketSpanFactory( ], }; callAsCurrentUser('ml.privilegeCheck', { body }) - .then(resp => { + .then((resp) => { if ( resp.cluster['cluster:monitor/xpack/ml/job/get'] && resp.cluster['cluster:monitor/xpack/ml/job/stats/get'] && diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts index f5daadfe86be0..8e8301db2a3a3 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts @@ -18,7 +18,7 @@ import { estimateBucketSpanFactory, BucketSpanEstimatorData } from './bucket_spa // permissions. const permissions = [false, true]; const callWithRequest: APICaller = (method: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { if (method === 'ml.privilegeCheck') { resolve({ cluster: { @@ -35,7 +35,7 @@ const callWithRequest: APICaller = (method: string) => { }; const callWithInternalUser: APICaller = () => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({}); }) as Promise; }; @@ -58,20 +58,20 @@ const formConfig: BucketSpanEstimatorData = { describe('ML - BucketSpanEstimator', () => { it('call factory', () => { - expect(function() { + expect(function () { estimateBucketSpanFactory(callWithRequest, callWithInternalUser, false); }).not.toThrow('Not initialized.'); }); - it('call factory and estimator with security disabled', done => { - expect(function() { + it('call factory and estimator with security disabled', (done) => { + expect(function () { const estimateBucketSpan = estimateBucketSpanFactory( callWithRequest, callWithInternalUser, true ); - estimateBucketSpan(formConfig).catch(catchData => { + estimateBucketSpan(formConfig).catch((catchData) => { expect(catchData).toBe('Unable to retrieve cluster setting search.max_buckets'); done(); @@ -79,14 +79,14 @@ describe('ML - BucketSpanEstimator', () => { }).not.toThrow('Not initialized.'); }); - it('call factory and estimator with security enabled.', done => { - expect(function() { + it('call factory and estimator with security enabled.', (done) => { + expect(function () { const estimateBucketSpan = estimateBucketSpanFactory( callWithRequest, callWithInternalUser, false ); - estimateBucketSpan(formConfig).catch(catchData => { + estimateBucketSpan(formConfig).catch((catchData) => { expect(catchData).toBe('Unable to retrieve cluster setting search.max_buckets'); done(); diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js index 674875f8d5d16..de9fd06c34e6a 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js @@ -28,7 +28,7 @@ export function polledDataCheckerFactory(callAsCurrentUser) { return new Promise((resolve, reject) => { const interval = { name: '1m', ms: 60000 }; this.performSearch(interval.ms) - .then(resp => { + .then((resp) => { const fullBuckets = _.get(resp, 'aggregations.non_empty_buckets.buckets', []); const result = this.isPolledData(fullBuckets, interval); if (result.pass) { @@ -42,7 +42,7 @@ export function polledDataCheckerFactory(callAsCurrentUser) { minimumBucketSpan: this.minimumBucketSpan, }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js index 71e692d089b49..6ae485fe11307 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js @@ -39,11 +39,11 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { const start = () => { // run all tests, returns a suggested interval this.runTests() - .then(interval => { + .then((interval) => { this.interval = interval; resolve(this.interval); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }; @@ -56,7 +56,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { .then(() => { start(); }) - .catch(resp => { + .catch((resp) => { mlLog.warn('SingleSeriesChecker: Could not load metric reference data'); reject(resp); }); @@ -105,10 +105,10 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { // recursive function called with the index of the INTERVALS array // each time one of the checks fails, the index is increased and // the tests are repeated. - const runTest = i => { + const runTest = (i) => { const interval = intervals[i]; this.performSearch(interval.ms) - .then(resp => { + .then((resp) => { const buckets = resp.aggregations.non_empty_buckets.buckets; const fullBuckets = this.getFullBuckets(buckets); if (fullBuckets.length) { @@ -149,7 +149,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { reject('runTest stopped because fullBuckets is empty'); } }) - .catch(resp => { + .catch((resp) => { // do something better with this reject(resp); }); @@ -265,7 +265,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { } this.performSearch(intervalMs) // 1h - .then(resp => { + .then((resp) => { const buckets = resp.aggregations.non_empty_buckets.buckets; const fullBuckets = this.getFullBuckets(buckets); if (fullBuckets.length) { @@ -275,7 +275,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { resolve(); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts index 1cc2a07ddbc88..9533fbc89c76c 100644 --- a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts +++ b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts @@ -77,8 +77,8 @@ const cardinalityCheckProvider = (callAsCurrentUser: APICaller) => { } ) => { [byFieldName, partitionFieldName, overFieldName] - .filter(field => field !== undefined && field !== '' && !excludedKeywords.has(field)) - .forEach(key => { + .filter((field) => field !== undefined && field !== '' && !excludedKeywords.has(field)) + .forEach((key) => { acc.add(key as string); }); return acc; @@ -87,7 +87,7 @@ const cardinalityCheckProvider = (callAsCurrentUser: APICaller) => { ); const maxBucketFieldCardinalities: string[] = influencers.filter( - influencerField => + (influencerField) => !!influencerField && !excludedKeywords.has(influencerField) && !overallCardinalityFields.has(influencerField) diff --git a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts index 581770e59043f..acb1bed6a37c0 100644 --- a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts @@ -47,11 +47,11 @@ export class CalendarManager { const events: CalendarEvent[] = await this._eventManager.getAllEvents(); const calendars: Calendar[] = calendarsResp.calendars; - calendars.forEach(cal => (cal.events = [])); + calendars.forEach((cal) => (cal.events = [])); // loop events and combine with related calendars - events.forEach(event => { - const calendar = calendars.find(cal => cal.calendar_id === event.calendar_id); + events.forEach((event) => { + const calendar = calendars.find((cal) => cal.calendar_id === event.calendar_id); if (calendar) { calendar.events.push(event); } @@ -66,7 +66,7 @@ export class CalendarManager { */ async getCalendarsByIds(calendarIds: string) { const calendars: Calendar[] = await this.getAllCalendars(); - return calendars.filter(calendar => calendarIds.includes(calendar.calendar_id)); + return calendars.filter((calendar) => calendarIds.includes(calendar.calendar_id)); } async newCalendar(calendar: FormCalendar) { @@ -96,12 +96,12 @@ export class CalendarManager { // workout the differences between the original events list and the new one // if an event has no event_id, it must be new const eventsToAdd = calendar.events.filter( - event => origCalendar.events.find(e => this._eventManager.isEqual(e, event)) === undefined + (event) => origCalendar.events.find((e) => this._eventManager.isEqual(e, event)) === undefined ); // if an event in the original calendar cannot be found, it must have been deleted const eventsToRemove: CalendarEvent[] = origCalendar.events.filter( - event => calendar.events.find(e => this._eventManager.isEqual(e, event)) === undefined + (event) => calendar.events.find((e) => this._eventManager.isEqual(e, event)) === undefined ); // note, both of the loops below could be removed if the add and delete endpoints @@ -130,7 +130,7 @@ export class CalendarManager { // remove all removed events await Promise.all( - eventsToRemove.map(async event => { + eventsToRemove.map(async (event) => { await this._eventManager.deleteEvent(calendarId, event.event_id); }) ); diff --git a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 92ab7739dbcfb..82a272b068bb3 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -125,7 +125,7 @@ export class DataRecognizer { if (err) { reject(err); } - fileNames.forEach(fileName => { + fileNames.forEach((fileName) => { const path = `${dirName}/${fileName}`; if (fs.lstatSync(path).isDirectory()) { dirs.push(fileName); @@ -152,7 +152,7 @@ export class DataRecognizer { const configs: Config[] = []; const dirs = await this.listDirs(this.modulesDir); await Promise.all( - dirs.map(async dir => { + dirs.map(async (dir) => { let file: string | undefined; try { file = await this.readFile(`${this.modulesDir}/${dir}/manifest.json`); @@ -179,7 +179,7 @@ export class DataRecognizer { // get the manifest.json file for a specified id, e.g. "nginx" async getManifestFile(id: string) { const manifestFiles = await this.loadManifestFiles(); - return manifestFiles.find(i => i.json.id === id); + return manifestFiles.find((i) => i.json.id === id); } // called externally by an endpoint @@ -188,7 +188,7 @@ export class DataRecognizer { const results: RecognizeResult[] = []; await Promise.all( - manifestFiles.map(async i => { + manifestFiles.map(async (i) => { const moduleConfig = i.json; let match = false; try { @@ -278,7 +278,7 @@ export class DataRecognizer { const kibana: KibanaObjects = {}; // load all of the job configs await Promise.all( - manifestJSON.jobs.map(async job => { + manifestJSON.jobs.map(async (job) => { try { const jobConfig = await this.readFile( `${this.modulesDir}/${dirName}/${ML_DIR}/${job.file}` @@ -298,7 +298,7 @@ export class DataRecognizer { // load all of the datafeed configs await Promise.all( - manifestJSON.datafeeds.map(async datafeed => { + manifestJSON.datafeeds.map(async (datafeed) => { try { const datafeedConfig = await this.readFile( `${this.modulesDir}/${dirName}/${ML_DIR}/${datafeed.file}` @@ -323,10 +323,10 @@ export class DataRecognizer { if (manifestJSON.kibana !== undefined) { const kKeys = Object.keys(manifestJSON.kibana) as Array; await Promise.all( - kKeys.map(async key => { + kKeys.map(async (key) => { kibana[key] = []; await Promise.all( - manifestJSON!.kibana[key].map(async obj => { + manifestJSON!.kibana[key].map(async (obj) => { try { const kConfig = await this.readFile( `${this.modulesDir}/${dirName}/${KIBANA_DIR}/${key}/${obj.file}` @@ -416,9 +416,9 @@ export class DataRecognizer { savedObjects: [] as KibanaObjectResponse[], }; - this.jobsForModelMemoryEstimation = moduleConfig.jobs.map(job => ({ + this.jobsForModelMemoryEstimation = moduleConfig.jobs.map((job) => ({ job, - query: moduleConfig.datafeeds.find(d => d.config.job_id === job.id)?.config.query ?? null, + query: moduleConfig.datafeeds.find((d) => d.config.job_id === job.id)?.config.query ?? null, })); this.applyJobConfigOverrides(moduleConfig, jobOverrides, jobPrefix); @@ -431,12 +431,12 @@ export class DataRecognizer { if (moduleConfig.jobs && moduleConfig.jobs.length) { if (Array.isArray(groups)) { // update groups list for each job - moduleConfig.jobs.forEach(job => (job.config.groups = groups)); + moduleConfig.jobs.forEach((job) => (job.config.groups = groups)); } // Set the results_index_name property for each job if useDedicatedIndex is true if (useDedicatedIndex === true) { - moduleConfig.jobs.forEach(job => (job.config.results_index_name = job.id)); + moduleConfig.jobs.forEach((job) => (job.config.results_index_name = job.id)); } saveResults.jobs = await this.saveJobs(moduleConfig.jobs); } @@ -444,20 +444,20 @@ export class DataRecognizer { // create the datafeeds if (moduleConfig.datafeeds && moduleConfig.datafeeds.length) { if (typeof query === 'object' && query !== null) { - moduleConfig.datafeeds.forEach(df => { + moduleConfig.datafeeds.forEach((df) => { df.config.query = query; }); } saveResults.datafeeds = await this.saveDatafeeds(moduleConfig.datafeeds); if (startDatafeed) { - const savedDatafeeds = moduleConfig.datafeeds.filter(df => { - const datafeedResult = saveResults.datafeeds.find(d => d.id === df.id); + const savedDatafeeds = moduleConfig.datafeeds.filter((df) => { + const datafeedResult = saveResults.datafeeds.find((d) => d.id === df.id); return datafeedResult !== undefined && datafeedResult.success === true; }); const startResults = await this.startDatafeeds(savedDatafeeds, start, end); - saveResults.datafeeds.forEach(df => { + saveResults.datafeeds.forEach((df) => { const startedDatafeed = startResults[df.id]; if (startedDatafeed !== undefined) { df.started = startedDatafeed.started; @@ -494,7 +494,7 @@ export class DataRecognizer { if (module && module.jobs) { // Add a wildcard at the front of each of the job IDs in the module, // as a prefix may have been supplied when creating the jobs in the module. - const jobIds = module.jobs.map(job => `*${job.id}`); + const jobIds = module.jobs.map((job) => `*${job.id}`); const { jobsExist } = jobServiceProvider(this.callAsCurrentUser); const jobInfo = await jobsExist(jobIds); @@ -507,11 +507,11 @@ export class DataRecognizer { const jobStats: MlJobStats = await this.callAsCurrentUser('ml.jobStats', { jobId: jobIds }); const jobStatsJobs: JobStat[] = []; if (jobStats.jobs && jobStats.jobs.length > 0) { - const foundJobIds = jobStats.jobs.map(job => job.job_id); + const foundJobIds = jobStats.jobs.map((job) => job.job_id); const { getLatestBucketTimestampByJob } = resultsServiceProvider(this.callAsCurrentUser); const latestBucketTimestampsByJob = await getLatestBucketTimestampByJob(foundJobIds); - jobStats.jobs.forEach(job => { + jobStats.jobs.forEach((job) => { const jobStat = { id: job.job_id, } as JobStat; @@ -548,7 +548,7 @@ export class DataRecognizer { if (indexPatterns === undefined || indexPatterns.saved_objects === undefined) { return; } - const ip = indexPatterns.saved_objects.find(i => i.attributes.title === name); + const ip = indexPatterns.saved_objects.find((i) => i.attributes.title === name); return ip !== undefined ? ip.id : undefined; } catch (error) { mlLog.warn(`Error loading index patterns, ${error}`); @@ -563,10 +563,10 @@ export class DataRecognizer { // first check if the saved objects already exist. const savedObjectExistResults = await this.checkIfSavedObjectsExist(moduleConfig.kibana); // loop through the kibanaSaveResults and update - Object.keys(moduleConfig.kibana).forEach(type => { + Object.keys(moduleConfig.kibana).forEach((type) => { // type e.g. dashboard, search ,visualization - moduleConfig.kibana[type]!.forEach(configItem => { - const existsResult = savedObjectExistResults.find(o => o.id === configItem.id); + moduleConfig.kibana[type]!.forEach((configItem) => { + const existsResult = savedObjectExistResults.find((o) => o.id === configItem.id); if (existsResult !== undefined) { configItem.exists = existsResult.exists; if (existsResult.exists === false) { @@ -590,9 +590,9 @@ export class DataRecognizer { objectExistResults: ObjectExistResult[] ) { (Object.keys(kibanaSaveResults) as Array).forEach( - type => { - kibanaSaveResults[type].forEach(resultItem => { - const i = objectExistResults.find(o => o.id === resultItem.id && o.type === type); + (type) => { + kibanaSaveResults[type].forEach((resultItem) => { + const i = objectExistResults.find((o) => o.id === resultItem.id && o.type === type); resultItem.exists = i !== undefined; }); } @@ -606,11 +606,11 @@ export class DataRecognizer { async checkIfSavedObjectsExist(kibanaObjects: KibanaObjects): Promise { const types = Object.keys(kibanaObjects); const results: ObjectExistResponse[][] = await Promise.all( - types.map(async type => { + types.map(async (type) => { const existingObjects = await this.loadExistingSavedObjects(type); - return kibanaObjects[type]!.map(obj => { + return kibanaObjects[type]!.map((obj) => { const existingObject = existingObjects.saved_objects.find( - o => o.attributes && o.attributes.title === obj.title + (o) => o.attributes && o.attributes.title === obj.title ); return { id: obj.id, @@ -634,13 +634,16 @@ export class DataRecognizer { async saveKibanaObjects(objectExistResults: ObjectExistResponse[]) { let results = { saved_objects: [] as any[] }; const filteredSavedObjects = objectExistResults - .filter(o => o.exists === false) - .map(o => o.savedObject); + .filter((o) => o.exists === false) + .map((o) => o.savedObject); if (filteredSavedObjects.length) { results = await this.savedObjectsClient.bulkCreate( // Add an empty migrationVersion attribute to each saved object to ensure // it is automatically migrated to the 7.0+ format with a references attribute. - filteredSavedObjects.map(doc => ({ ...doc, migrationVersion: doc.migrationVersion || {} })) + filteredSavedObjects.map((doc) => ({ + ...doc, + migrationVersion: doc.migrationVersion || {}, + })) ); } return results.saved_objects; @@ -651,7 +654,7 @@ export class DataRecognizer { // as success: false async saveJobs(jobs: ModuleJob[]): Promise { return await Promise.all( - jobs.map(async job => { + jobs.map(async (job) => { const jobId = job.id; try { job.id = jobId; @@ -674,7 +677,7 @@ export class DataRecognizer { // as success: false async saveDatafeeds(datafeeds: ModuleDataFeed[]) { return await Promise.all( - datafeeds.map(async datafeed => { + datafeeds.map(async (datafeed) => { try { await this.saveDatafeed(datafeed); return { id: datafeed.id, success: true, started: false }; @@ -748,8 +751,8 @@ export class DataRecognizer { // which is returned from the endpoint async updateResults(results: DataRecognizerConfigResponse, saveResults: SaveResults) { // update job results - results.jobs.forEach(j => { - saveResults.jobs.forEach(j2 => { + results.jobs.forEach((j) => { + saveResults.jobs.forEach((j2) => { if (j.id === j2.id) { j.success = j2.success; if (j2.error !== undefined) { @@ -760,8 +763,8 @@ export class DataRecognizer { }); // update datafeed results - results.datafeeds.forEach(d => { - saveResults.datafeeds.forEach(d2 => { + results.datafeeds.forEach((d) => { + saveResults.datafeeds.forEach((d2) => { if (d.id === d2.id) { d.success = d2.success; d.started = d2.started; @@ -774,9 +777,9 @@ export class DataRecognizer { // update savedObjects results (Object.keys(results.kibana) as Array).forEach( - category => { - results.kibana[category].forEach(item => { - const result = saveResults.savedObjects.find(o => o.id === item.id); + (category) => { + results.kibana[category].forEach((item) => { + const result = saveResults.savedObjects.find((o) => o.id === item.id); if (result !== undefined) { item.exists = result.exists; @@ -808,7 +811,7 @@ export class DataRecognizer { index: string | number ): void { resultItems[index] = []; - configItems.forEach(j => { + configItems.forEach((j) => { resultItems[index].push({ id: j.id, success: false, @@ -816,12 +819,12 @@ export class DataRecognizer { }); } - (Object.keys(reducedConfig) as Array).forEach(i => { + (Object.keys(reducedConfig) as Array).forEach((i) => { if (Array.isArray(reducedConfig[i])) { createResultsItems(reducedConfig[i] as any[], results, i); } else { results[i] = {} as any; - Object.keys(reducedConfig[i]).forEach(k => { + Object.keys(reducedConfig[i]).forEach((k) => { createResultsItems((reducedConfig[i] as Module['kibana'])[k] as any[], results[i], k); }); } @@ -837,13 +840,13 @@ export class DataRecognizer { // add each one to the datafeed const indexPatternNames = splitIndexPatternNames(this.indexPatternName); - moduleConfig.datafeeds.forEach(df => { + moduleConfig.datafeeds.forEach((df) => { const newIndices: string[] = []; // the datafeed can contain indexes and indices const currentIndices = df.config.indexes !== undefined ? df.config.indexes : df.config.indices; - currentIndices.forEach(index => { + currentIndices.forEach((index) => { if (index === INDEX_PATTERN_NAME) { // the datafeed index is INDEX_PATTERN_NAME, so replace it with index pattern(s) // supplied by the user or the default one from the manifest @@ -864,11 +867,11 @@ export class DataRecognizer { // marker for the id of the specified index pattern updateJobUrlIndexPatterns(moduleConfig: Module) { if (Array.isArray(moduleConfig.jobs)) { - moduleConfig.jobs.forEach(job => { + moduleConfig.jobs.forEach((job) => { // if the job has custom_urls if (job.config.custom_settings && job.config.custom_settings.custom_urls) { // loop through each url, replacing the INDEX_PATTERN_ID marker - job.config.custom_settings.custom_urls.forEach(cUrl => { + job.config.custom_settings.custom_urls.forEach((cUrl) => { const url = cUrl.url_value; if (url.match(INDEX_PATTERN_ID)) { const newUrl = url.replace( @@ -906,8 +909,8 @@ export class DataRecognizer { // INDEX_PATTERN_NAME markers for the id or name of the specified index pattern updateSavedObjectIndexPatterns(moduleConfig: Module) { if (moduleConfig.kibana) { - Object.keys(moduleConfig.kibana).forEach(category => { - moduleConfig.kibana[category]!.forEach(item => { + Object.keys(moduleConfig.kibana).forEach((category) => { + moduleConfig.kibana[category]!.forEach((item) => { let jsonString = item.config.kibanaSavedObjectMeta!.searchSourceJSON; if (jsonString.match(INDEX_PATTERN_ID)) { jsonString = jsonString.replace( @@ -1094,7 +1097,7 @@ export class DataRecognizer { const generalOverrides: GeneralJobsOverride[] = []; const jobSpecificOverrides: JobSpecificOverride[] = []; - overrides.forEach(override => { + overrides.forEach((override) => { if (isGeneralJobOverride(override)) { generalOverrides.push(override); } else { @@ -1102,17 +1105,18 @@ export class DataRecognizer { } }); - if (generalOverrides.some(override => !!override.analysis_limits?.model_memory_limit)) { + if (generalOverrides.some((override) => !!override.analysis_limits?.model_memory_limit)) { this.jobsForModelMemoryEstimation = []; } else { this.jobsForModelMemoryEstimation = moduleConfig.jobs - .filter(job => { - const override = jobSpecificOverrides.find(o => `${jobPrefix}${o.job_id}` === job.id); + .filter((job) => { + const override = jobSpecificOverrides.find((o) => `${jobPrefix}${o.job_id}` === job.id); return override?.analysis_limits?.model_memory_limit === undefined; }) - .map(job => ({ + .map((job) => ({ job, - query: moduleConfig.datafeeds.find(d => d.config.job_id === job.id)?.config.query || null, + query: + moduleConfig.datafeeds.find((d) => d.config.job_id === job.id)?.config.query || null, })); } @@ -1121,7 +1125,7 @@ export class DataRecognizer { return; } - Object.keys(source).forEach(key => { + Object.keys(source).forEach((key) => { const sourceValue = source[key]; const updateValue = update[key]; @@ -1142,17 +1146,17 @@ export class DataRecognizer { }); } - generalOverrides.forEach(generalOverride => { - jobs.forEach(job => { + generalOverrides.forEach((generalOverride) => { + jobs.forEach((job) => { merge(job.config, generalOverride); processArrayValues(job.config, generalOverride); }); }); - jobSpecificOverrides.forEach(jobSpecificOverride => { + jobSpecificOverrides.forEach((jobSpecificOverride) => { // for each override, find the relevant job. // note, the job id already has the prefix prepended to it - const job = jobs.find(j => j.id === `${jobPrefix}${jobSpecificOverride.job_id}`); + const job = jobs.find((j) => j.id === `${jobPrefix}${jobSpecificOverride.job_id}`); if (job !== undefined) { // delete the job_id in the override as this shouldn't be overridden delete jobSpecificOverride.job_id; @@ -1183,7 +1187,7 @@ export class DataRecognizer { // the overrides which don't contain a datafeed id or a job id will be applied to all jobs in the module const generalOverrides: GeneralDatafeedsOverride[] = []; const datafeedSpecificOverrides: DatafeedOverride[] = []; - overrides.forEach(o => { + overrides.forEach((o) => { if (o.datafeed_id === undefined && o.job_id === undefined) { generalOverrides.push(o); } else { @@ -1191,20 +1195,20 @@ export class DataRecognizer { } }); - generalOverrides.forEach(o => { + generalOverrides.forEach((o) => { datafeeds.forEach(({ config }) => { merge(config, o); }); }); // collect all the overrides which contain either a job id or a datafeed id - datafeedSpecificOverrides.forEach(o => { + datafeedSpecificOverrides.forEach((o) => { // either a job id or datafeed id has been specified, so create a new id // containing either one plus the prefix const tempId: string = String(o.datafeed_id !== undefined ? o.datafeed_id : o.job_id); const dId = prefixDatafeedId(tempId, jobPrefix); - const datafeed = datafeeds.find(d => d.id === dId); + const datafeed = datafeeds.find((d) => d.id === dId); if (datafeed !== undefined) { delete o.job_id; delete o.datafeed_id; diff --git a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts index 8ccd359137b67..43581ad75fb17 100644 --- a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts @@ -142,7 +142,7 @@ export class DataVisualizer { // To avoid checking for the existence of too many aggregatable fields in one request, // split the check into multiple batches (max 200 fields per request). const batches: string[][] = [[]]; - _.each(aggregatableFields, field => { + _.each(aggregatableFields, (field) => { let lastArray: string[] = _.last(batches); if (lastArray.length === AGGREGATABLE_EXISTS_REQUEST_BATCH_SIZE) { lastArray = []; @@ -152,7 +152,7 @@ export class DataVisualizer { }); await Promise.all( - batches.map(async fields => { + batches.map(async (fields) => { const batchStats = await this.checkAggregatableFieldsExist( indexPatternTitle, query, @@ -173,7 +173,7 @@ export class DataVisualizer { ); await Promise.all( - nonAggregatableFields.map(async field => { + nonAggregatableFields.map(async (field) => { const existsInDocs = await this.checkNonAggregatableFieldExists( indexPatternTitle, query, @@ -217,7 +217,7 @@ export class DataVisualizer { // Batch up fields by type, getting stats for multiple fields at a time. const batches: Field[][] = []; const batchedFields: { [key: string]: Field[][] } = {}; - _.each(fields, field => { + _.each(fields, (field) => { if (field.fieldName === undefined) { // undefined fieldName is used for a document count request. // getDocumentCountStats requires timeField - don't add to batched requests if not defined @@ -238,13 +238,13 @@ export class DataVisualizer { } }); - _.each(batchedFields, lists => { + _.each(batchedFields, (lists) => { batches.push(...lists); }); let results: BatchStats[] = []; await Promise.all( - batches.map(async batch => { + batches.map(async (batch) => { let batchStats: BatchStats[] = []; const first = batch[0]; switch (first.type) { @@ -313,7 +313,7 @@ export class DataVisualizer { // Use an exists filter on the the field name to get // examples of the field, so cannot batch up. await Promise.all( - batch.map(async field => { + batch.map(async (field) => { const stats = await this.getFieldExamples( indexPatternTitle, query, @@ -492,7 +492,7 @@ export class DataVisualizer { ['aggregations', 'eventRate', 'buckets'], [] ); - _.each(dataByTimeBucket, dataForTime => { + _.each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; buckets[time] = dataForTime.doc_count; }); @@ -867,7 +867,7 @@ export class DataVisualizer { [...aggsPath, `${safeFieldName}_values`, 'buckets'], [] ); - _.each(valueBuckets, bucket => { + _.each(valueBuckets, (bucket) => { stats[`${bucket.key_as_string}Count`] = bucket.doc_count; }); diff --git a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts index 6558d0d48ded9..d9d765028b123 100644 --- a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts +++ b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts @@ -42,7 +42,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { fields: fieldNames, }); const aggregatableFields: string[] = []; - fieldNames.forEach(fieldName => { + fieldNames.forEach((fieldName) => { const fieldInfo = fieldCapsResp.fields[fieldName]; const typeKeys = fieldInfo !== undefined ? Object.keys(fieldInfo) : []; if (typeKeys.length > 0) { @@ -88,7 +88,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { ) ?? {}; // No need to perform aggregation over the cached fields - const fieldsToAgg = aggregatableFields.filter(field => !cachedValues.hasOwnProperty(field)); + const fieldsToAgg = aggregatableFields.filter((field) => !cachedValues.hasOwnProperty(field)); if (fieldsToAgg.length === 0) { return cachedValues; @@ -276,7 +276,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { ) ?? {}; // No need to perform aggregation over the cached fields - const fieldsToAgg = aggregatableFields.filter(field => !cachedValues.hasOwnProperty(field)); + const fieldsToAgg = aggregatableFields.filter((field) => !cachedValues.hasOwnProperty(field)); if (fieldsToAgg.length === 0) { return cachedValues; diff --git a/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts index 9d7009955124f..afe699cc7fecf 100644 --- a/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts +++ b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts @@ -175,7 +175,5 @@ export function importDataProvider(callAsCurrentUser: APICaller) { } function generateId() { - return Math.random() - .toString(36) - .substr(2, 9); + return Math.random().toString(36).substr(2, 9); } diff --git a/x-pack/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts index 42440057a2d1a..11208b4d941f3 100644 --- a/x-pack/plugins/ml/server/models/filter/filter_manager.ts +++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts @@ -174,16 +174,16 @@ export class FilterManager { buildFiltersInUse(jobsList: PartialJob[]) { // Build a map of filter_ids against jobs and detectors using that filter. const filtersInUse: FiltersInUse = {}; - jobsList.forEach(job => { + jobsList.forEach((job) => { const detectors = job.analysis_config.detectors; - detectors.forEach(detector => { + detectors.forEach((detector) => { if (detector.custom_rules) { const rules = detector.custom_rules; - rules.forEach(rule => { + rules.forEach((rule) => { if (rule.scope) { const ruleScope: DetectorRuleScope = rule.scope; const scopeFields = Object.keys(ruleScope); - scopeFields.forEach(scopeField => { + scopeFields.forEach((scopeField) => { const filter = ruleScope[scopeField]; const filterId = filter.filter_id; if (filtersInUse[filterId] === undefined) { diff --git a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js index 2cdfc0ef4f4c5..6b782f8652363 100644 --- a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js +++ b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js @@ -113,7 +113,7 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { let messages = []; if (resp.hits.total !== 0) { - messages = resp.hits.hits.map(hit => hit._source); + messages = resp.hits.hits.map((hit) => hit._source); } return messages; } catch (e) { @@ -210,14 +210,14 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { messagesPerJob = resp.aggregations.levelsPerJob.buckets; } - messagesPerJob.forEach(job => { + messagesPerJob.forEach((job) => { // ignore system messages (id==='') if (job.key !== '' && job.levels && job.levels.buckets && job.levels.buckets.length) { let highestLevel = 0; let highestLevelText = ''; let msgTime = 0; - job.levels.buckets.forEach(level => { + job.levels.buckets.forEach((level) => { const label = level.key; // note the highest message level if (LEVEL[label] > highestLevel) { @@ -227,7 +227,7 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { level.latestMessage.buckets && level.latestMessage.buckets.length ) { - level.latestMessage.buckets.forEach(msg => { + level.latestMessage.buckets.forEach((msg) => { // there should only be one result here. highestLevelText = msg.key; diff --git a/x-pack/plugins/ml/server/models/job_service/groups.ts b/x-pack/plugins/ml/server/models/job_service/groups.ts index e44609bc66711..56757e4cc3ff7 100644 --- a/x-pack/plugins/ml/server/models/job_service/groups.ts +++ b/x-pack/plugins/ml/server/models/job_service/groups.ts @@ -35,10 +35,10 @@ export function groupsProvider(callAsCurrentUser: APICaller) { ]); if (jobs) { - jobs.forEach(job => { + jobs.forEach((job) => { jobIds[job.job_id] = null; if (job.groups !== undefined) { - job.groups.forEach(g => { + job.groups.forEach((g) => { if (groups[g] === undefined) { groups[g] = { id: g, @@ -53,8 +53,8 @@ export function groupsProvider(callAsCurrentUser: APICaller) { }); } if (calendars) { - calendars.forEach(cal => { - cal.job_ids.forEach(jId => { + calendars.forEach((cal) => { + cal.job_ids.forEach((jId) => { // don't include _all in the calendar groups list if (jId !== GLOBAL_CALENDAR && jobIds[jId] === undefined) { if (groups[jId] === undefined) { @@ -71,7 +71,7 @@ export function groupsProvider(callAsCurrentUser: APICaller) { }); } - return Object.keys(groups).map(g => groups[g]); + return Object.keys(groups).map((g) => groups[g]); } async function updateGroups(jobs: Job[]) { diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index 225cd43e411a4..5503169f2d371 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -130,7 +130,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { async function jobsSummary(jobIds: string[] = []) { const fullJobsList: CombinedJobWithStats[] = await createFullJobsList(); - const fullJobsIds = fullJobsList.map(job => job.job_id); + const fullJobsIds = fullJobsList.map((job) => job.job_id); const auditMessages: AuditMessage[] = await getAuditMessagesSummary(fullJobsIds); const auditMessagesByJob = auditMessages.reduce((acc, cur) => { acc[cur.job_id] = cur; @@ -141,7 +141,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { defaultMessage: 'deleting', }); - const jobs = fullJobsList.map(job => { + const jobs = fullJobsList.map((job) => { const hasDatafeed = typeof job.datafeed_config === 'object' && Object.keys(job.datafeed_config).length > 0; const dataCounts = job.data_counts; @@ -169,7 +169,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { nodeName: job.node ? job.node.name : undefined, deleting: job.deleting || undefined, }; - if (jobIds.find(j => j === tempJob.id)) { + if (jobIds.find((j) => j === tempJob.id)) { tempJob.fullJob = job; } const auditMessage = auditMessagesByJob[tempJob.id]; @@ -193,7 +193,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const fullJobsList = await createFullJobsList(); const jobsMap: { [id: string]: string[] } = {}; - const jobs = fullJobsList.map(job => { + const jobs = fullJobsList.map((job) => { jobsMap[job.job_id] = job.groups || []; const hasDatafeed = typeof job.datafeed_config === 'object' && Object.keys(job.datafeed_config).length > 0; @@ -267,10 +267,10 @@ export function jobsProvider(callAsCurrentUser: APICaller) { >(requests); if (datafeedResults && datafeedResults.datafeeds) { - datafeedResults.datafeeds.forEach(datafeed => { + datafeedResults.datafeeds.forEach((datafeed) => { if (datafeedStatsResults && datafeedStatsResults.datafeeds) { const datafeedStats = datafeedStatsResults.datafeeds.find( - ds => ds.datafeed_id === datafeed.datafeed_id + (ds) => ds.datafeed_id === datafeed.datafeed_id ); if (datafeedStats) { datafeeds[datafeed.job_id] = { ...datafeed, ...datafeedStats }; @@ -283,11 +283,11 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // used for assigning calendars to jobs when a calendar has // only been attached to a group if (jobResults && jobResults.jobs) { - jobResults.jobs.forEach(job => { + jobResults.jobs.forEach((job) => { calendarsByJobId[job.job_id] = []; if (job.groups !== undefined) { - job.groups.forEach(gId => { + job.groups.forEach((gId) => { if (groups[gId] === undefined) { groups[gId] = []; } @@ -299,12 +299,12 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // assign calendars to jobs if (calendarResults) { - calendarResults.forEach(cal => { - cal.job_ids.forEach(id => { + calendarResults.forEach((cal) => { + cal.job_ids.forEach((id) => { if (id === GLOBAL_CALENDAR) { globalCalendars.push(cal.calendar_id); } else if (groups[id]) { - groups[id].forEach(jId => { + groups[id].forEach((jId) => { if (calendarsByJobId[jId] !== undefined) { calendarsByJobId[jId].push(cal.calendar_id); } @@ -327,7 +327,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // create jobs objects containing job stats, datafeeds, datafeed stats and calendars if (jobResults && jobResults.jobs) { - jobResults.jobs.forEach(job => { + jobResults.jobs.forEach((job) => { let tempJob = job as CombinedJobWithStats; const calendars: string[] = [ @@ -339,7 +339,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { } if (jobStatsResults && jobStatsResults.jobs) { - const jobStats = jobStatsResults.jobs.find(js => js.job_id === tempJob.job_id); + const jobStats = jobStatsResults.jobs.find((js) => js.job_id === tempJob.job_id); if (jobStats !== undefined) { tempJob = { ...tempJob, ...jobStats }; if (jobStats.node) { @@ -375,9 +375,9 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const jobIds = []; try { const tasksList = await callAsCurrentUser('tasks.list', { actions, detailed }); - Object.keys(tasksList.nodes).forEach(nodeId => { + Object.keys(tasksList.nodes).forEach((nodeId) => { const tasks = tasksList.nodes[nodeId].tasks; - Object.keys(tasks).forEach(taskId => { + Object.keys(tasks).forEach((taskId) => { jobIds.push(tasks[taskId].description.replace(/^delete-job-/, '')); }); }); @@ -385,7 +385,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // if the user doesn't have permission to load the task list, // use the jobs list to get the ids of deleting jobs const { jobs } = await callAsCurrentUser('ml.jobs'); - jobIds.push(...jobs.filter(j => j.deleting === true).map(j => j.job_id)); + jobIds.push(...jobs.filter((j) => j.deleting === true).map((j) => j.job_id)); } return { jobIds }; } @@ -401,17 +401,17 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const results: { [id: string]: boolean } = {}; if (jobsInfo.count > 0) { - const allJobIds = jobsInfo.jobs.map(job => job.job_id); + const allJobIds = jobsInfo.jobs.map((job) => job.job_id); // Check if each of the supplied IDs match existing jobs. - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { // Create a Regex for each supplied ID as wildcard * is allowed. const regexp = new RegExp(`^${jobId.replace(/\*+/g, '.*')}$`); - const exists = allJobIds.some(existsJobId => regexp.test(existsJobId)); + const exists = allJobIds.some((existsJobId) => regexp.test(existsJobId)); results[jobId] = exists; }); } else { - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { results[jobId] = false; }); } @@ -422,9 +422,9 @@ export function jobsProvider(callAsCurrentUser: APICaller) { async function getAllJobAndGroupIds() { const { getAllGroups } = groupsProvider(callAsCurrentUser); const jobs = await callAsCurrentUser('ml.jobs'); - const jobIds = jobs.jobs.map(job => job.job_id); + const jobIds = jobs.jobs.map((job) => job.job_id); const groups = await getAllGroups(); - const groupIds = groups.map(group => group.id); + const groupIds = groups.map((group) => group.id); return { jobIds, diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts index b209dc5681563..bf0d79b3ec072 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts @@ -92,7 +92,7 @@ export function categorizationExamplesProvider( return { examples: examplesWithTokens }; } catch (error) { validationResults.createTooManyTokensResult(error, halfChunkSize); - return { examples: halfExamples.map(e => ({ text: e, tokens: [] })) }; + return { examples: halfExamples.map((e) => ({ text: e, tokens: [] })) }; } } } @@ -119,10 +119,10 @@ export function categorizationExamplesProvider( }, }); - const lengths = examples.map(e => e.length); - const sumLengths = lengths.map((s => (a: number) => (s += a))(0)); + const lengths = examples.map((e) => e.length); + const sumLengths = lengths.map(((s) => (a: number) => (s += a))(0)); - const tokensPerExample: Token[][] = examples.map(e => []); + const tokensPerExample: Token[][] = examples.map((e) => []); tokens.forEach((t, i) => { for (let g = 0; g < sumLengths.length; g++) { @@ -193,7 +193,7 @@ export function categorizationExamplesProvider( // sort back into original order and remove origIndex property const processedExamples = filteredExamples .sort((a, b) => a.origIndex - b.origIndex) - .map(e => ({ text: e.text, tokens: e.tokens })); + .map((e) => ({ text: e.text, tokens: e.tokens })); return { overallValidStatus: validationResults.overallResult, diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts index 3361cc454e2b7..13c5f107972eb 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts @@ -125,7 +125,7 @@ export function topCategoriesProvider(callWithRequest: callWithRequestType) { const catCounts = await getTopCategoryCounts(jobId, numberOfCategories); const categories = await getCategories( jobId, - catCounts.map(c => c.id), + catCounts.map((c) => c.id), catCounts.length || numberOfCategories ); @@ -149,7 +149,7 @@ export function topCategoriesProvider(callWithRequest: callWithRequestType) { } else { return { total, - categories: categories.map(category => { + categories: categories.map((category) => { return { category, }; diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts index e3b37fffa9c77..4b90283a3a966 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts @@ -28,17 +28,19 @@ export class ValidationResults { } public get overallResult() { - if (this._results.some(c => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID)) { + if (this._results.some((c) => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID)) { return CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID; } - if (this._results.some(c => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID)) { + if ( + this._results.some((c) => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID) + ) { return CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID; } return CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID; } private _resultExists(id: VALIDATION_RESULT) { - return this._results.some(r => r.id === id); + return this._results.some((r) => r.id === id); } public createTokenCountResult(examples: CategoryFieldExample[], sampleSize: number) { @@ -53,7 +55,7 @@ export class ValidationResults { return; } - const validExamplesSize = examples.filter(e => e.tokens.length >= VALID_TOKEN_COUNT).length; + const validExamplesSize = examples.filter((e) => e.tokens.length >= VALID_TOKEN_COUNT).length; const percentValid = sampleSize === 0 ? 0 : validExamplesSize / sampleSize; let valid = CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID; @@ -119,7 +121,7 @@ export class ValidationResults { } public createNullValueResult(examples: Array) { - const nullCount = examples.filter(e => e === null).length; + const nullCount = examples.filter((e) => e === null).length; if (nullCount / examples.length >= NULL_COUNT_PERCENT_LIMIT) { this._results.push({ diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts index a198fac4e3fef..4872f0f5e0ea4 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts @@ -50,7 +50,7 @@ export function newJobLineChartProvider(callWithRequest: callWithRequestType) { const results = await callWithRequest('search', json); return processSearchResults( results, - aggFieldNamePairs.map(af => af.field) + aggFieldNamePairs.map((af) => af.field) ); } diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts index ee35f13c44ee6..26609bdcc8f7d 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts @@ -55,7 +55,7 @@ export function newJobPopulationChartProvider(callWithRequest: callWithRequestTy const results = await callWithRequest('search', json); return processSearchResults( results, - aggFieldNamePairs.map(af => af.field) + aggFieldNamePairs.map((af) => af.field) ); } catch (error) { return { error }; diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts index 405f645ca0e1d..a5ed4a18bf51c 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts @@ -149,27 +149,27 @@ async function combineFieldsAndAggs( const isRollup = Object.keys(rollupFields).length > 0; const mix = mixFactory(isRollup, rollupFields); - aggs.forEach(a => { + aggs.forEach((a) => { if (a.type === METRIC_AGG_TYPE && a.fields !== undefined) { switch (a.id) { case ML_JOB_AGGREGATION.LAT_LONG: - geoFields.forEach(f => mix(f, a)); + geoFields.forEach((f) => mix(f, a)); break; case ML_JOB_AGGREGATION.INFO_CONTENT: case ML_JOB_AGGREGATION.HIGH_INFO_CONTENT: case ML_JOB_AGGREGATION.LOW_INFO_CONTENT: - textFields.forEach(f => mix(f, a)); + textFields.forEach((f) => mix(f, a)); case ML_JOB_AGGREGATION.DISTINCT_COUNT: case ML_JOB_AGGREGATION.HIGH_DISTINCT_COUNT: case ML_JOB_AGGREGATION.LOW_DISTINCT_COUNT: // distinct count (i.e. cardinality) takes keywords, ips // as well as numerical fields - keywordFields.forEach(f => mix(f, a)); - ipFields.forEach(f => mix(f, a)); + keywordFields.forEach((f) => mix(f, a)); + ipFields.forEach((f) => mix(f, a)); // note, no break to fall through to add numerical fields. default: // all other aggs take numerical fields - numericalFields.forEach(f => { + numericalFields.forEach((f) => { mix(f, a); }); break; @@ -186,7 +186,7 @@ async function combineFieldsAndAggs( // remove fields that have no aggs associated to them, unless they are date fields function filterFields(fields: Field[]): Field[] { return fields.filter( - f => f.aggs && (f.aggs.length > 0 || (f.aggs.length === 0 && f.type === ES_FIELD_TYPES.DATE)) + (f) => f.aggs && (f.aggs.length > 0 || (f.aggs.length === 0 && f.type === ES_FIELD_TYPES.DATE)) ); } @@ -196,7 +196,7 @@ function mixFactory(isRollup: boolean, rollupFields: RollupFields) { return function mix(field: Field, agg: Aggregation): void { if ( isRollup === false || - (rollupFields[field.id] && rollupFields[field.id].find(f => f.agg === agg.dslName)) + (rollupFields[field.id] && rollupFields[field.id].find((f) => f.agg === agg.dslName)) ) { if (field.aggs !== undefined) { field.aggs.push(agg); @@ -210,14 +210,14 @@ function mixFactory(isRollup: boolean, rollupFields: RollupFields) { function combineAllRollupFields(rollupConfigs: RollupJob[]): RollupFields { const rollupFields: RollupFields = {}; - rollupConfigs.forEach(conf => { - Object.keys(conf.fields).forEach(fieldName => { + rollupConfigs.forEach((conf) => { + Object.keys(conf.fields).forEach((fieldName) => { if (rollupFields[fieldName] === undefined) { rollupFields[fieldName] = conf.fields[fieldName]; } else { const aggs = conf.fields[fieldName]; - aggs.forEach(agg => { - if (rollupFields[fieldName].find(f => f.agg === agg.agg) === null) { + aggs.forEach((agg) => { + if (rollupFields[fieldName].find((f) => f.agg === agg.agg) === null) { rollupFields[fieldName].push(agg); } }); @@ -228,20 +228,20 @@ function combineAllRollupFields(rollupConfigs: RollupJob[]): RollupFields { } function getKeywordFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.KEYWORD); + return fields.filter((f) => f.type === ES_FIELD_TYPES.KEYWORD); } function getTextFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.TEXT); + return fields.filter((f) => f.type === ES_FIELD_TYPES.TEXT); } function getIpFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.IP); + return fields.filter((f) => f.type === ES_FIELD_TYPES.IP); } function getNumericalFields(fields: Field[]): Field[] { return fields.filter( - f => + (f) => f.type === ES_FIELD_TYPES.LONG || f.type === ES_FIELD_TYPES.INTEGER || f.type === ES_FIELD_TYPES.SHORT || @@ -255,6 +255,6 @@ function getNumericalFields(fields: Field[]): Field[] { function getGeoFields(fields: Field[]): Field[] { return fields.filter( - f => f.type === ES_FIELD_TYPES.GEO_POINT || f.type === ES_FIELD_TYPES.GEO_SHAPE + (f) => f.type === ES_FIELD_TYPES.GEO_POINT || f.type === ES_FIELD_TYPES.GEO_SHAPE ); } diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts index f1af7614b4232..02fef16a384d0 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts @@ -45,7 +45,7 @@ describe('job_service - job_caps', () => { }); describe('farequote newJobCaps()', () => { - it('can get job caps for index pattern', async done => { + it('can get job caps for index pattern', async (done) => { const indexPattern = 'farequote-*'; const isRollup = false; const { newJobCaps } = newJobCapsProvider(callWithRequestNonRollupMock); @@ -54,7 +54,7 @@ describe('job_service - job_caps', () => { done(); }); - it('can get rollup job caps for non rollup index pattern', async done => { + it('can get rollup job caps for non rollup index pattern', async (done) => { const indexPattern = 'farequote-*'; const isRollup = true; const { newJobCaps } = newJobCapsProvider(callWithRequestNonRollupMock); @@ -65,7 +65,7 @@ describe('job_service - job_caps', () => { }); describe('cloudwatch newJobCaps()', () => { - it('can get rollup job caps for rollup index pattern', async done => { + it('can get rollup job caps for rollup index pattern', async (done) => { const indexPattern = 'cloud_roll_index'; const isRollup = true; const { newJobCaps } = newJobCapsProvider(callWithRequestRollupMock); @@ -74,7 +74,7 @@ describe('job_service - job_caps', () => { done(); }); - it('can get non rollup job caps for rollup index pattern', async done => { + it('can get non rollup job caps for rollup index pattern', async (done) => { const indexPattern = 'cloud_roll_index'; const isRollup = false; const { newJobCaps } = newJobCapsProvider(callWithRequestRollupMock); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts index 3a9d979ccb22c..a0ab4b5cf4e3e 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts @@ -43,15 +43,15 @@ export function newJobCapsProvider(callWithRequest: any) { // map of ids to allow it to be stringified for transportation // over the network. function convertForStringify(aggs: Aggregation[], fields: Field[]): void { - fields.forEach(f => { - f.aggIds = f.aggs ? f.aggs.map(a => a.id) : []; + fields.forEach((f) => { + f.aggIds = f.aggs ? f.aggs.map((a) => a.id) : []; delete f.aggs; }); - aggs.forEach(a => { + aggs.forEach((a) => { if (a.fields !== undefined) { // if the aggregation supports fields, i.e. it's fields list isn't undefined, // create a list of field ids - a.fieldIds = a.fields.map(f => f.id); + a.fieldIds = a.fields.map((f) => f.id); } delete a.fields; }); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts index 2845006dae05f..f7d846839503d 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts @@ -67,7 +67,7 @@ async function loadRollupIndexPattern( }); const obj = resp.saved_objects.find( - r => + (r) => r.attributes && r.attributes.type === 'rollup' && r.attributes.title === indexPattern && diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts index 3a86693e91828..f9999a06f38ed 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts @@ -11,7 +11,7 @@ import { JobValidationMessage } from '../../../common/constants/messages'; // mock callWithRequest const callWithRequest: APICaller = (method: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { if (method === 'fieldCaps') { resolve({ fields: [] }); return; @@ -36,8 +36,8 @@ describe('ML - validateJob', () => { job: { analysis_config: { detectors: [] } }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_empty', @@ -49,7 +49,7 @@ describe('ML - validateJob', () => { }); const jobIdTests = (testIds: string[], messageId: string) => { - const promises = testIds.map(id => { + const promises = testIds.map((id) => { const payload = ({ job: { analysis_config: { detectors: [] }, @@ -61,11 +61,11 @@ describe('ML - validateJob', () => { }); }); - return Promise.all(promises).then(testResults => { - testResults.forEach(messages => { + return Promise.all(promises).then((testResults) => { + testResults.forEach((messages) => { expect(Array.isArray(messages)).toBe(true); if (Array.isArray(messages)) { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); } }); @@ -77,8 +77,8 @@ describe('ML - validateJob', () => { job: { analysis_config: { detectors: [] }, groups: testIds }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); }); }; @@ -113,7 +113,7 @@ describe('ML - validateJob', () => { }); const bucketSpanFormatTests = (testFormats: string[], messageId: string) => { - const promises = testFormats.map(format => { + const promises = testFormats.map((format) => { const payload = ({ job: { analysis_config: { bucket_span: format, detectors: [] } }, } as unknown) as ValidateJobPayload; @@ -122,11 +122,11 @@ describe('ML - validateJob', () => { }); }); - return Promise.all(promises).then(testResults => { - testResults.forEach(messages => { + return Promise.all(promises).then((testResults) => { + testResults.forEach((messages) => { expect(Array.isArray(messages)).toBe(true); if (Array.isArray(messages)) { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); } }); @@ -156,8 +156,8 @@ describe('ML - validateJob', () => { function: undefined, }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('detectors_function_empty')).toBe(true); }); }); @@ -170,8 +170,8 @@ describe('ML - validateJob', () => { function: 'count', }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('detectors_function_not_empty')).toBe(true); }); }); @@ -182,8 +182,8 @@ describe('ML - validateJob', () => { fields: {}, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('index_fields_invalid')).toBe(true); }); }); @@ -194,8 +194,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('index_fields_valid')).toBe(true); }); }); @@ -218,7 +218,7 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }); - it('throws an error because job.analysis_config.influencers is not an Array', done => { + it('throws an error because job.analysis_config.influencers is not an Array', (done) => { const payload = getBasicPayload() as any; delete payload.job.analysis_config.influencers; @@ -234,8 +234,8 @@ describe('ML - validateJob', () => { it('detect duplicate detectors', () => { const payload = getBasicPayload() as any; payload.job.analysis_config.detectors.push({ function: 'count' }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -257,8 +257,8 @@ describe('ML - validateJob', () => { { function: 'count', by_field_name: 'airline' }, { function: 'count', partition_field_name: 'airline' }, ]; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -272,8 +272,8 @@ describe('ML - validateJob', () => { // Failing https://github.com/elastic/kibana/issues/65865 it('basic validation passes, extended checks return some messages', () => { const payload = getBasicPayload(); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -305,8 +305,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -338,8 +338,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -381,8 +381,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -400,18 +400,18 @@ describe('ML - validateJob', () => { const docsTestPayload = getBasicPayload() as any; docsTestPayload.job.analysis_config.detectors = [{ function: 'count', by_field_name: 'airline' }]; it('creates a docs url pointing to the current docs version', () => { - return validateJob(callWithRequest, docsTestPayload).then(messages => { + return validateJob(callWithRequest, docsTestPayload).then((messages) => { const message = messages[ - messages.findIndex(m => m.id === 'field_not_aggregatable') + messages.findIndex((m) => m.id === 'field_not_aggregatable') ] as JobValidationMessage; expect(message.url!.search('/current/')).not.toBe(-1); }); }); it('creates a docs url pointing to the master docs version', () => { - return validateJob(callWithRequest, docsTestPayload, 'master').then(messages => { + return validateJob(callWithRequest, docsTestPayload, 'master').then((messages) => { const message = messages[ - messages.findIndex(m => m.id === 'field_not_aggregatable') + messages.findIndex((m) => m.id === 'field_not_aggregatable') ] as JobValidationMessage; expect(message.url!.search('/master/')).not.toBe(-1); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts index f852de785c70a..9d7154bbbb304 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts @@ -58,7 +58,7 @@ export async function validateJob( if (basicValidation.valid === true) { // remove basic success messages from tests // where we run additional extended tests. - const filteredBasicValidationMessages = basicValidation.messages.filter(m => { + const filteredBasicValidationMessages = basicValidation.messages.filter((m) => { return m.id !== 'bucket_span_valid'; }); @@ -83,7 +83,7 @@ export async function validateJob( // so we can decide later whether certain additional tests should be run const cardinalityMessages = await validateCardinality(callWithRequest, job); validationMessages.push(...cardinalityMessages); - const cardinalityError = cardinalityMessages.some(m => { + const cardinalityError = cardinalityMessages.some((m) => { return messages[m.id as MessageId].status === VALIDATION_STATUS.ERROR; }); @@ -111,7 +111,7 @@ export async function validateJob( validationMessages.push({ id: 'skipped_extended_tests' }); } - return uniqWithIsEqual(validationMessages).map(message => { + return uniqWithIsEqual(validationMessages).map((message) => { const messageId = message.id as MessageId; const messageDef = messages[messageId] as JobValidationMessageDef; if (typeof messageDef !== 'undefined') { diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js index 883f1aed1209e..46d05d3cf7637 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js +++ b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js @@ -13,7 +13,7 @@ import { validateJobObject } from './validate_job_object'; const BUCKET_SPAN_HIGH_THRESHOLD = 1; -const wrapQuery = query => ({ +const wrapQuery = (query) => ({ bool: { must: [query], must_not: [], @@ -28,7 +28,7 @@ const wrapQuery = query => ({ // 3 * (30 - 10) + 30 - 30 + 60 - 30 = 90, // 3 * (60 - 10) + 60 - 30 + 60 - 60 = 180] // 70 is the lowest so 10m would be picked -const pickBucketSpan = bucketSpans => { +const pickBucketSpan = (bucketSpans) => { if (bucketSpans.length === 1) { return bucketSpans[0]; } @@ -39,10 +39,10 @@ const pickBucketSpan = bucketSpans => { }, 0); }; - const spansMs = bucketSpans.map(span => span.ms); - const sumDistances = spansMs.map(ms => getSumDistance(spansMs, ms)); + const spansMs = bucketSpans.map((span) => span.ms); + const sumDistances = spansMs.map((ms) => getSumDistance(spansMs, ms)); const minSumDistance = Math.min(...sumDistances); - const i = sumDistances.findIndex(d => d === minSumDistance); + const i = sumDistances.findIndex((d) => d === minSumDistance); return bucketSpans[i]; }; @@ -105,7 +105,7 @@ export async function validateBucketSpan( const estimatorConfigs = []; - job.analysis_config.detectors.forEach(detector => { + job.analysis_config.detectors.forEach((detector) => { const data = getRequestData(); const aggType = mlFunctionToESAggregation(detector.function); const fieldName = typeof detector.field_name === 'undefined' ? null : detector.field_name; @@ -119,8 +119,8 @@ export async function validateBucketSpan( // do the actual bucket span estimation try { - const estimations = estimatorConfigs.map(data => { - return new Promise(resolve => { + const estimations = estimatorConfigs.map((data) => { + return new Promise((resolve) => { estimateBucketSpanFactory( callWithRequest, callAsInternalUser, @@ -131,7 +131,7 @@ export async function validateBucketSpan( // but isn't able to come up with a bucket span estimation. // this doesn't trigger a HTTP error but an object with an error message. // triggering a HTTP error would be too severe for this case. - .catch(resp => { + .catch((resp) => { resolve({ error: true, message: resp, @@ -142,7 +142,7 @@ export async function validateBucketSpan( // run the estimations, filter valid results, then pick a bucket span. const results = await Promise.all(estimations); - const bucketSpans = results.filter(result => result.name && result.ms); + const bucketSpans = results.filter((result) => result.name && result.ms); if (bucketSpans.length > 0) { const bucketSpan = pickBucketSpan(bucketSpans); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts index 84f865879d67f..8d77fd5a1fd0e 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts @@ -23,28 +23,28 @@ import mockItSearchResponse from './__mocks__/mock_it_search_response.json'; // mock callWithRequestFactory const callWithRequestFactory = (mockSearchResponse: any) => { return () => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(mockSearchResponse); }); }; }; describe('ML - validateBucketSpan', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse)).then( () => done(new Error('Promise should not resolve for this test without job argument.')), () => done() ); }); - it('called with non-valid job argument #1, missing datafeed_config', done => { + it('called with non-valid job argument #1, missing datafeed_config', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), {}).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing datafeed_config.indices', done => { + it('called with non-valid job argument #2, missing datafeed_config.indices', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), { datafeed_config: {}, }).then( @@ -53,7 +53,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #3, missing data_description', done => { + it('called with non-valid job argument #3, missing data_description', (done) => { const job = { datafeed_config: { indices: [] } }; validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -61,7 +61,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #4, missing data_description.time_field', done => { + it('called with non-valid job argument #4, missing data_description.time_field', (done) => { const job = { datafeed_config: { indices: [] }, data_description: {} }; validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -69,7 +69,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #5, missing analysis_config.influencers', done => { + it('called with non-valid job argument #5, missing analysis_config.influencers', (done) => { const job = { datafeed_config: { indices: [] }, data_description: { time_field: '@timestamp' }, @@ -89,7 +89,7 @@ describe('ML - validateBucketSpan', () => { return validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( (messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); } ); @@ -114,7 +114,7 @@ describe('ML - validateBucketSpan', () => { job, duration ).then((messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_bucket_span']); }); }); @@ -128,7 +128,7 @@ describe('ML - validateBucketSpan', () => { job, duration ).then((messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['bucket_span_high']); }); }); @@ -149,20 +149,20 @@ describe('ML - validateBucketSpan', () => { return validateBucketSpan(callWithRequestFactory(mockSearchResponse), job, {}).then( (messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); test(ids); } ); }; it('farequote count detector, bucket span estimation matches 15m', () => { - return testBucketSpan('15m', mockFareQuoteSearchResponse, ids => { + return testBucketSpan('15m', mockFareQuoteSearchResponse, (ids) => { expect(ids).toStrictEqual(['success_bucket_span']); }); }); it('farequote count detector, bucket span estimation does not match 1m', () => { - return testBucketSpan('1m', mockFareQuoteSearchResponse, ids => { + return testBucketSpan('1m', mockFareQuoteSearchResponse, (ids) => { expect(ids).toStrictEqual(['bucket_span_estimation_mismatch']); }); }); @@ -172,7 +172,7 @@ describe('ML - validateBucketSpan', () => { // not many non-empty buckets. future work on bucket estimation and sparsity validation // should result in a lower bucket span estimation. it('it_ops_app_logs count detector, bucket span estimation matches 6h', () => { - return testBucketSpan('6h', mockItSearchResponse, ids => { + return testBucketSpan('6h', mockItSearchResponse, (ids) => { expect(ids).toStrictEqual(['success_bucket_span']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts index e5111629f1182..13e5495aac4c4 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts @@ -35,21 +35,21 @@ const callWithRequestFactory = (responses: Record, fail = false): A }; describe('ML - validateCardinality', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateCardinality(callWithRequestFactory(mockResponses)).then( () => done(new Error('Promise should not resolve for this test without job argument.')), () => done() ); }); - it('called with non-valid job argument #1, missing analysis_config', done => { + it('called with non-valid job argument #1, missing analysis_config', (done) => { validateCardinality(callWithRequestFactory(mockResponses), {} as CombinedJob).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing datafeed_config', done => { + it('called with non-valid job argument #2, missing datafeed_config', (done) => { validateCardinality(callWithRequestFactory(mockResponses), { analysis_config: {}, } as CombinedJob).then( @@ -58,7 +58,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #3, missing datafeed_config.indices', done => { + it('called with non-valid job argument #3, missing datafeed_config.indices', (done) => { const job = { analysis_config: {}, datafeed_config: {} } as CombinedJob; validateCardinality(callWithRequestFactory(mockResponses), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -66,7 +66,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #4, missing data_description', done => { + it('called with non-valid job argument #4, missing data_description', (done) => { const job = ({ analysis_config: {}, datafeed_config: { indices: [] }, @@ -77,7 +77,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #5, missing data_description.time_field', done => { + it('called with non-valid job argument #5, missing data_description.time_field', (done) => { const job = ({ analysis_config: {}, data_description: {}, @@ -89,7 +89,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #6, missing analysis_config.influencers', done => { + it('called with non-valid job argument #6, missing analysis_config.influencers', (done) => { const job = ({ analysis_config: {}, datafeed_config: { indices: [] }, @@ -110,8 +110,8 @@ describe('ML - validateCardinality', () => { }, } as unknown) as CombinedJob; - return validateCardinality(callWithRequestFactory(mockResponses), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockResponses), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); }); }); @@ -143,8 +143,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockCardinality), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); test(ids); }); }; @@ -155,8 +155,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockResponses), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['field_not_aggregatable']); }); }); @@ -166,8 +166,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockResponses), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_cardinality']); }); }); @@ -175,8 +175,8 @@ describe('ML - validateCardinality', () => { it('field not aggregatable', () => { const job = getJobConfig('partition_field_name'); return validateCardinality(callWithRequestFactory({}), (job as unknown) as CombinedJob).then( - messages => { - const ids = messages.map(m => m.id); + (messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['field_not_aggregatable']); } ); @@ -191,50 +191,50 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory({}, true), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['fields_not_aggregatable']); }); }); it('valid partition field cardinality', () => { - return testCardinality('partition_field_name', 50, ids => { + return testCardinality('partition_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too high partition field cardinality', () => { - return testCardinality('partition_field_name', 1001, ids => { + return testCardinality('partition_field_name', 1001, (ids) => { expect(ids).toStrictEqual(['cardinality_partition_field']); }); }); it('valid by field cardinality', () => { - return testCardinality('by_field_name', 50, ids => { + return testCardinality('by_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too high by field cardinality', () => { - return testCardinality('by_field_name', 1001, ids => { + return testCardinality('by_field_name', 1001, (ids) => { expect(ids).toStrictEqual(['cardinality_by_field']); }); }); it('valid over field cardinality', () => { - return testCardinality('over_field_name', 50, ids => { + return testCardinality('over_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too low over field cardinality', () => { - return testCardinality('over_field_name', 9, ids => { + return testCardinality('over_field_name', 9, (ids) => { expect(ids).toStrictEqual(['cardinality_over_field_low']); }); }); it('too high over field cardinality', () => { - return testCardinality('over_field_name', 1000001, ids => { + return testCardinality('over_field_name', 1000001, (ids) => { expect(ids).toStrictEqual(['cardinality_over_field_high']); }); }); @@ -245,8 +245,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: false }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_cardinality']); }); }); @@ -256,8 +256,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_model_plot_high']); }); }); @@ -267,8 +267,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: false }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_by_field']); }); }); @@ -278,8 +278,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_model_plot_high', 'cardinality_by_field']); }); }); @@ -289,8 +289,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true, terms: 'AAL,AAB' }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_by_field']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts index 2ad483fb07ca7..62f272f26bb3f 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts @@ -62,13 +62,15 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato >; const detectors = job.analysis_config.detectors; - const relevantDetectors = detectors.filter(detector => { + const relevantDetectors = detectors.filter((detector) => { return typeof detector[fieldName] !== 'undefined'; }); if (relevantDetectors.length > 0) { try { - const uniqueFieldNames = [...new Set(relevantDetectors.map(f => f[fieldName]))] as string[]; + const uniqueFieldNames = [ + ...new Set(relevantDetectors.map((f) => f[fieldName])), + ] as string[]; // use fieldCaps endpoint to get data about whether fields are aggregatable const fieldCaps = await callWithRequest('fieldCaps', { @@ -79,7 +81,7 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato let aggregatableFieldNames: string[] = []; // parse fieldCaps to return an array of just the fields which are aggregatable if (typeof fieldCaps === 'object' && typeof fieldCaps.fields === 'object') { - aggregatableFieldNames = uniqueFieldNames.filter(field => { + aggregatableFieldNames = uniqueFieldNames.filter((field) => { if (typeof fieldCaps.fields[field] !== 'undefined') { const fieldType = Object.keys(fieldCaps.fields[field])[0]; return fieldCaps.fields[field][fieldType].aggregatable; @@ -96,9 +98,9 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato job.data_description.time_field ); - uniqueFieldNames.forEach(uniqueFieldName => { + uniqueFieldNames.forEach((uniqueFieldName) => { const field = stats.aggregatableExistsFields.find( - fieldData => fieldData.fieldName === uniqueFieldName + (fieldData) => fieldData.fieldName === uniqueFieldName ); if (field !== undefined && typeof field === 'object' && field.stats) { modelPlotCardinality += @@ -160,7 +162,7 @@ export async function validateCardinality( // find out if there are any relevant detector field names // where cardinality checks could be run against. - const numDetectorsWithFieldNames = job.analysis_config.detectors.filter(d => { + const numDetectorsWithFieldNames = job.analysis_config.detectors.filter((d) => { return d.by_field_name || d.over_field_name || d.partition_field_name; }); if (numDetectorsWithFieldNames.length === 0) { @@ -175,23 +177,23 @@ export async function validateCardinality( // check over fields (population analysis) const validateOverFieldsLow = validate({ type: 'over', - isInvalid: cardinality => cardinality < OVER_FIELD_CARDINALITY_THRESHOLD_LOW, + isInvalid: (cardinality) => cardinality < OVER_FIELD_CARDINALITY_THRESHOLD_LOW, messageId: 'cardinality_over_field_low', }); const validateOverFieldsHigh = validate({ type: 'over', - isInvalid: cardinality => cardinality > OVER_FIELD_CARDINALITY_THRESHOLD_HIGH, + isInvalid: (cardinality) => cardinality > OVER_FIELD_CARDINALITY_THRESHOLD_HIGH, messageId: 'cardinality_over_field_high', }); // check partition/by fields (multi-metric analysis) const validatePartitionFields = validate({ type: 'partition', - isInvalid: cardinality => cardinality > PARTITION_FIELD_CARDINALITY_THRESHOLD, + isInvalid: (cardinality) => cardinality > PARTITION_FIELD_CARDINALITY_THRESHOLD, }); const validateByFields = validate({ type: 'by', - isInvalid: cardinality => cardinality > BY_FIELD_CARDINALITY_THRESHOLD, + isInvalid: (cardinality) => cardinality > BY_FIELD_CARDINALITY_THRESHOLD, }); // we already called the validation functions above, @@ -217,7 +219,7 @@ export async function validateCardinality( } // add all messages returned from the individual cardinality checks - validations.forEach(v => messages.push(...v.messages)); + validations.forEach((v) => messages.push(...v.messages)); if (messages.length === 0) { messages.push({ id: 'success_cardinality' }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts index df3310ad9f5e8..89c265d0b6f60 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts @@ -11,7 +11,7 @@ import { CombinedJob } from '../../../common/types/anomaly_detection_jobs'; import { validateInfluencers } from './validate_influencers'; describe('ML - validateInfluencers', () => { - it('called without arguments throws an error', done => { + it('called without arguments throws an error', (done) => { validateInfluencers( (undefined as unknown) as APICaller, (undefined as unknown) as CombinedJob @@ -21,14 +21,14 @@ describe('ML - validateInfluencers', () => { ); }); - it('called with non-valid job argument #1, missing analysis_config', done => { + it('called with non-valid job argument #1, missing analysis_config', (done) => { validateInfluencers((undefined as unknown) as APICaller, ({} as unknown) as CombinedJob).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing analysis_config.influencers', done => { + it('called with non-valid job argument #2, missing analysis_config.influencers', (done) => { const job = { analysis_config: {}, datafeed_config: { indices: [] }, @@ -40,7 +40,7 @@ describe('ML - validateInfluencers', () => { ); }); - it('called with non-valid job argument #3, missing analysis_config.detectors', done => { + it('called with non-valid job argument #3, missing analysis_config.detectors', (done) => { const job = { analysis_config: { influencers: [] }, datafeed_config: { indices: [] }, @@ -66,8 +66,8 @@ describe('ML - validateInfluencers', () => { it('success_influencer', () => { const job = getJobConfig(['airline']); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_influencers']); }); }); @@ -84,24 +84,24 @@ describe('ML - validateInfluencers', () => { ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); }); }); it('influencer_low', () => { const job = getJobConfig(); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_low']); }); }); it('influencer_high', () => { const job = getJobConfig(['i1', 'i2', 'i3', 'i4']); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_high']); }); }); @@ -118,8 +118,8 @@ describe('ML - validateInfluencers', () => { }, ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_low_suggestion']); }); }); @@ -148,7 +148,7 @@ describe('ML - validateInfluencers', () => { }, ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { expect(messages).toStrictEqual([ { id: 'influencer_low_suggestions', diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts index e54ffc4586a8e..531d4dfdba0c5 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts @@ -21,7 +21,7 @@ export async function validateInfluencers(callWithRequest: APICaller, job: Combi const influencers = job.analysis_config.influencers; const detectorFieldNames: string[] = []; - job.analysis_config.detectors.forEach(d => { + job.analysis_config.detectors.forEach((d) => { if (d.by_field_name) { detectorFieldNames.push(d.by_field_name); } @@ -56,7 +56,7 @@ export async function validateInfluencers(callWithRequest: APICaller, job: Combi if (detectorFieldNames.length > 1) { id = 'influencer_low_suggestions'; const uniqueInfluencers = [...new Set(detectorFieldNames)]; - influencerSuggestion = `[${uniqueInfluencers.map(i => `"${i}"`).join(',')}]`; + influencerSuggestion = `[${uniqueInfluencers.map((i) => `"${i}"`).join(',')}]`; } messages.push({ id, influencerSuggestion }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts index bf88716181bb3..581153036fed7 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts @@ -129,8 +129,8 @@ describe('ML - validateModelMemoryLimit', () => { const job = getJobConfig(); const duration = undefined; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual([]); }); }); @@ -141,8 +141,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '31mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_greater_than_max_mml']); }); }); @@ -158,8 +158,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '66mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['estimated_mml_greater_than_max_mml']); }); }); @@ -175,8 +175,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '24mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); @@ -192,8 +192,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '22mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -206,8 +206,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -218,8 +218,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '31mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual([]); }); }); @@ -230,8 +230,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '41mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_greater_than_effective_max_mml']); }); }); @@ -247,8 +247,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '19mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); @@ -260,8 +260,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '0mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -273,8 +273,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10mbananas'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -286,8 +286,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -299,8 +299,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = 'mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -312,8 +312,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = 'asdf'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -325,8 +325,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '1023KB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -338,8 +338,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '1024KB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -351,8 +351,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '6MB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -368,8 +368,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '20mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts index 2c3b2dd4dc6ae..3ba8701b4bbd2 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts @@ -23,7 +23,7 @@ const mockSearchResponse = { const callWithRequestFactory = (resp: any): APICaller => { return (path: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(resp[path]); }) as Promise; }; @@ -44,7 +44,7 @@ function getMinimalValidJob() { } describe('ML - isValidTimeField', () => { - it('called without job config argument triggers Promise rejection', done => { + it('called without job config argument triggers Promise rejection', (done) => { isValidTimeField( callWithRequestFactory(mockSearchResponse), (undefined as unknown) as CombinedJob @@ -54,9 +54,9 @@ describe('ML - isValidTimeField', () => { ); }); - it('time_field `@timestamp`', done => { + it('time_field `@timestamp`', (done) => { isValidTimeField(callWithRequestFactory(mockSearchResponse), getMinimalValidJob()).then( - valid => { + (valid) => { expect(valid).toBe(true); done(); }, @@ -64,7 +64,7 @@ describe('ML - isValidTimeField', () => { ); }); - it('time_field `metadata.timestamp`', done => { + it('time_field `metadata.timestamp`', (done) => { const mockJobConfigNestedDate = getMinimalValidJob(); mockJobConfigNestedDate.data_description.time_field = 'metadata.timestamp'; @@ -77,7 +77,7 @@ describe('ML - isValidTimeField', () => { callWithRequestFactory(mockSearchResponseNestedDate), mockJobConfigNestedDate ).then( - valid => { + (valid) => { expect(valid).toBe(true); done(); }, @@ -87,7 +87,7 @@ describe('ML - isValidTimeField', () => { }); describe('ML - validateTimeRange', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateTimeRange( callWithRequestFactory(mockSearchResponse), (undefined as unknown) as CombinedJob @@ -97,7 +97,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #2, missing datafeed_config', done => { + it('called with non-valid job argument #2, missing datafeed_config', (done) => { validateTimeRange(callWithRequestFactory(mockSearchResponse), ({ analysis_config: {}, } as unknown) as CombinedJob).then( @@ -106,7 +106,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #3, missing datafeed_config.indices', done => { + it('called with non-valid job argument #3, missing datafeed_config.indices', (done) => { const job = { analysis_config: {}, datafeed_config: {} }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -117,7 +117,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #4, missing data_description', done => { + it('called with non-valid job argument #4, missing data_description', (done) => { const job = { analysis_config: {}, datafeed_config: { indices: [] } }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -128,7 +128,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #5, missing data_description.time_field', done => { + it('called with non-valid job argument #5, missing data_description.time_field', (done) => { const job = { analysis_config: {}, data_description: {}, datafeed_config: { indices: [] } }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -147,8 +147,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponseInvalid), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_field_invalid']); }); }); @@ -161,8 +161,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), jobShortTimeRange, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -173,8 +173,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -185,8 +185,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -197,8 +197,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_time_range']); }); }); @@ -209,8 +209,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_before_epoch']); }); }); diff --git a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js index 4934a0ba07081..e664a1403d7d6 100644 --- a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js +++ b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js @@ -25,7 +25,7 @@ export function buildAnomalyTableItems(anomalyRecords, aggregationInterval, date displayRecords = aggregateAnomalies(anomalyRecords, aggregationInterval, dateFormatTz); } else { // Show all anomaly records. - displayRecords = anomalyRecords.map(record => { + displayRecords = anomalyRecords.map((record) => { return { time: record.timestamp, source: record, @@ -56,9 +56,9 @@ export function buildAnomalyTableItems(anomalyRecords, aggregationInterval, date if (source.influencers !== undefined) { const influencers = []; const sourceInfluencers = _.sortBy(source.influencers, 'influencer_field_name'); - sourceInfluencers.forEach(influencer => { + sourceInfluencers.forEach((influencer) => { const influencerFieldName = influencer.influencer_field_name; - influencer.influencer_field_values.forEach(influencerFieldValue => { + influencer.influencer_field_values.forEach((influencerFieldValue) => { influencers.push({ [influencerFieldName]: influencerFieldValue, }); @@ -125,17 +125,12 @@ function aggregateAnomalies(anomalyRecords, interval, dateFormatTz) { } const aggregatedData = {}; - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { // Use moment.js to get start of interval. const roundedTime = dateFormatTz !== undefined - ? moment(record.timestamp) - .tz(dateFormatTz) - .startOf(interval) - .valueOf() - : moment(record.timestamp) - .startOf(interval) - .valueOf(); + ? moment(record.timestamp).tz(dateFormatTz).startOf(interval).valueOf() + : moment(record.timestamp).startOf(interval).valueOf(); if (aggregatedData[roundedTime] === undefined) { aggregatedData[roundedTime] = {}; } @@ -178,9 +173,9 @@ function aggregateAnomalies(anomalyRecords, interval, dateFormatTz) { // the highest score per bucketed time / jobId / detectorIndex. const summaryRecords = []; _.each(aggregatedData, (times, roundedTime) => { - _.each(times, jobIds => { - _.each(jobIds, entityDetectors => { - _.each(entityDetectors, record => { + _.each(times, (jobIds) => { + _.each(jobIds, (entityDetectors) => { + _.each(entityDetectors, (record) => { summaryRecords.push({ time: +roundedTime, source: record, diff --git a/x-pack/plugins/ml/server/models/results_service/results_service.ts b/x-pack/plugins/ml/server/models/results_service/results_service.ts index 1df53d9cee79c..a985ef7b8f3f5 100644 --- a/x-pack/plugins/ml/server/models/results_service/results_service.ts +++ b/x-pack/plugins/ml/server/models/results_service/results_service.ts @@ -89,7 +89,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { } // Add in term queries for each of the specified criteria. - criteriaFields.forEach(criteria => { + criteriaFields.forEach((criteria) => { boolCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -105,7 +105,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { nested: { path: 'influencers', @@ -169,7 +169,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { }; if (resp.hits.total !== 0) { let records: AnomalyRecordDoc[] = []; - resp.hits.hits.forEach(hit => { + resp.hits.hits.forEach((hit) => { records.push(hit._source); }); @@ -195,7 +195,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { tableData.examplesByJobId = {}; const categoryIdsByJobId: { [key: string]: any } = {}; - categoryAnomalies.forEach(anomaly => { + categoryAnomalies.forEach((anomaly) => { if (!_.has(categoryIdsByJobId, anomaly.jobId)) { categoryIdsByJobId[anomaly.jobId] = []; } @@ -206,7 +206,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { const categoryJobIds = Object.keys(categoryIdsByJobId); await Promise.all( - categoryJobIds.map(async jobId => { + categoryJobIds.map(async (jobId) => { const examplesByCategoryId = await getCategoryExamples( jobId, categoryIdsByJobId[jobId], @@ -358,7 +358,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { [] ); const timestampByJobId: { [key: string]: number | undefined } = {}; - bucketsByJobId.forEach(bucket => { + bucketsByJobId.forEach((bucket) => { timestampByJobId[bucket.key] = bucket.maxTimestamp.value; }); diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts index 01adcb462689e..7116d1c23b515 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts @@ -67,7 +67,7 @@ export function extractDocumentation( return collection; } - members.forEach(member => { + members.forEach((member) => { collection.push(serializeProperty(member)); }); @@ -138,7 +138,7 @@ export function extractDocumentation( ? `${symbol.getName()}[]` : symbol.getName(); - members.forEach(member => { + members.forEach((member) => { nestedEntries.push(serializeProperty(member)); }); } diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts index 0eaf3143eaac0..8b9b35f7a0d3c 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts @@ -13,11 +13,11 @@ export function postProcess(parsedFiles: any[]): void { const schemasDirPath = `${__dirname}${path.sep}..${path.sep}..${path.sep}schemas${path.sep}`; const schemaFiles = fs .readdirSync(schemasDirPath) - .map(filename => path.resolve(schemasDirPath + filename)); + .map((filename) => path.resolve(schemasDirPath + filename)); const schemaDocs = extractDocumentation(schemaFiles); - parsedFiles.forEach(parsedFile => { + parsedFiles.forEach((parsedFile) => { parsedFile.forEach((block: Block) => { const { local: { schemas }, diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts index 8cbe38d667b2c..754368e318f38 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts @@ -13,7 +13,7 @@ const API_VERSION = '7.8.0'; * Updates api version of the endpoints. */ export function postFilter(parsedFiles: any[]) { - parsedFiles.forEach(parsedFile => { + parsedFiles.forEach((parsedFile) => { parsedFile.forEach((block: Block) => { block.local.version = API_VERSION; }); diff --git a/x-pack/plugins/ml/server/routes/system.ts b/x-pack/plugins/ml/server/routes/system.ts index 7ae7dd8eef065..99c7805a62e76 100644 --- a/x-pack/plugins/ml/server/routes/system.ts +++ b/x-pack/plugins/ml/server/routes/system.ts @@ -29,7 +29,7 @@ export function systemRoutes( let count = 0; if (typeof resp.nodes === 'object') { - Object.keys(resp.nodes).forEach(k => { + Object.keys(resp.nodes).forEach((k) => { if (resp.nodes[k].attributes !== undefined) { const maxOpenJobs = resp.nodes[k].attributes['ml.max_open_jobs']; if (maxOpenJobs !== null && maxOpenJobs > 0) { diff --git a/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js b/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js index 470d596bd2bdc..aec30f0628f31 100644 --- a/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js +++ b/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js @@ -24,16 +24,12 @@ describe('formatTimestampToDuration', () => { formatTimestampToDuration(fiftyNineSeconds, CALCULATE_DURATION_SINCE, getTestTime()) ).to.be('59 seconds'); - const fiveMins = getTestTime() - .subtract(5, 'minutes') - .subtract(30, 'seconds'); + const fiveMins = getTestTime().subtract(5, 'minutes').subtract(30, 'seconds'); expect(formatTimestampToDuration(fiveMins, CALCULATE_DURATION_SINCE, getTestTime())).to.be( '6 mins' ); - const sixHours = getTestTime() - .subtract(6, 'hours') - .subtract(30, 'minutes'); + const sixHours = getTestTime().subtract(6, 'hours').subtract(30, 'minutes'); expect(formatTimestampToDuration(sixHours, CALCULATE_DURATION_SINCE, getTestTime())).to.be( '6 hrs 30 mins' ); @@ -85,17 +81,12 @@ describe('formatTimestampToDuration', () => { '10 mins' ); - const sixHours = getTestTime() - .add(6, 'hours') - .add(30, 'minutes'); + const sixHours = getTestTime().add(6, 'hours').add(30, 'minutes'); expect(formatTimestampToDuration(sixHours, CALCULATE_DURATION_UNTIL, getTestTime())).to.be( '6 hrs 30 mins' ); - const sevenDays = getTestTime() - .add(7, 'days') - .add(6, 'hours') - .add(18, 'minutes'); + const sevenDays = getTestTime().add(7, 'days').add(6, 'hours').add(18, 'minutes'); expect(formatTimestampToDuration(sevenDays, CALCULATE_DURATION_UNTIL, getTestTime())).to.be( '7 days 6 hrs 18 mins' ); diff --git a/x-pack/plugins/monitoring/common/cancel_promise.ts b/x-pack/plugins/monitoring/common/cancel_promise.ts index f100edda50796..e8d9282945947 100644 --- a/x-pack/plugins/monitoring/common/cancel_promise.ts +++ b/x-pack/plugins/monitoring/common/cancel_promise.ts @@ -53,13 +53,13 @@ export class PromiseWithCancel { return new Promise((resolve, reject) => { this._status = Status.Awaiting; return this._promise - .then(response => { + .then((response) => { if (this._status !== Status.Canceled) { this._status = Status.Resolved; return resolve(response); } }) - .catch(error => { + .catch((error) => { if (this._status !== Status.Canceled) { this._status = Status.Failed; return reject(error); diff --git a/x-pack/plugins/monitoring/public/angular/app_modules.ts b/x-pack/plugins/monitoring/public/angular/app_modules.ts index 3fa79cedf4ce7..96b122801085f 100644 --- a/x-pack/plugins/monitoring/public/angular/app_modules.ts +++ b/x-pack/plugins/monitoring/public/angular/app_modules.ts @@ -102,7 +102,7 @@ function createMonitoringAppConfigConstants(keys: MonitoringPluginDependencies[' function createLocalStateModule(query: any) { angular .module('monitoring/State', ['monitoring/Private']) - .service('globalState', function( + .service('globalState', function ( Private: IPrivate, $rootScope: ng.IRootScopeService, $location: ng.ILocationService @@ -129,7 +129,7 @@ function createLocalStateModule(query: any) { function createLocalKbnUrlModule() { angular .module('monitoring/KbnUrl', ['monitoring/Private', 'ngRoute']) - .service('kbnUrl', function(Private: IPrivate) { + .service('kbnUrl', function (Private: IPrivate) { return Private(KbnUrlProvider); }); } @@ -137,22 +137,22 @@ function createLocalKbnUrlModule() { function createMonitoringAppServices() { angular .module('monitoring/services', ['monitoring/Private']) - .service('breadcrumbs', function(Private: IPrivate) { + .service('breadcrumbs', function (Private: IPrivate) { return Private(breadcrumbsProvider); }) - .service('monitoringClusters', function(Private: IPrivate) { + .service('monitoringClusters', function (Private: IPrivate) { return Private(monitoringClustersProvider); }) - .service('$executor', function(Private: IPrivate) { + .service('$executor', function (Private: IPrivate) { return Private(executorProvider); }) - .service('features', function(Private: IPrivate) { + .service('features', function (Private: IPrivate) { return Private(featuresProvider); }) - .service('license', function(Private: IPrivate) { + .service('license', function (Private: IPrivate) { return Private(licenseProvider); }) - .service('title', function(Private: IPrivate) { + .service('title', function (Private: IPrivate) { return Private(titleProvider); }); } @@ -169,24 +169,24 @@ function createMonitoringAppDirectives() { function createMonitoringAppFilters() { angular .module('monitoring/filters', []) - .filter('capitalize', function() { - return function(input: string) { + .filter('capitalize', function () { + return function (input: string) { return capitalize(input?.toLowerCase()); }; }) - .filter('formatNumber', function() { + .filter('formatNumber', function () { return formatNumber; }) - .filter('formatMetric', function() { + .filter('formatMetric', function () { return formatMetric; }) - .filter('extractIp', function() { + .filter('extractIp', function () { return extractIp; }); } function createLocalConfigModule(core: MonitoringPluginDependencies['core']) { - angular.module('monitoring/Config', []).provider('config', function() { + angular.module('monitoring/Config', []).provider('config', function () { return { $get: () => ({ get: (key: string) => core.uiSettings?.get(key), @@ -198,13 +198,13 @@ function createLocalConfigModule(core: MonitoringPluginDependencies['core']) { function createLocalStorage() { angular .module('monitoring/Storage', []) - .service('localStorage', function($window: IWindowService) { + .service('localStorage', function ($window: IWindowService) { return new Storage($window.localStorage); }) - .service('sessionStorage', function($window: IWindowService) { + .service('sessionStorage', function ($window: IWindowService) { return new Storage($window.sessionStorage); }) - .service('sessionTimeout', function() { + .service('sessionTimeout', function () { return {}; }); } @@ -230,12 +230,12 @@ function createLocalI18nModule() { function createHrefModule(core: AppMountContext['core']) { const name: string = 'kbnHref'; - angular.module('monitoring/href', []).directive(name, function() { + angular.module('monitoring/href', []).directive(name, function () { return { restrict: 'A', link: { pre: (_$scope, _$el, $attr) => { - $attr.$observe(name, val => { + $attr.$observe(name, (val) => { if (val) { const url = getSafeForExternalLink(val as string); $attr.$set('href', core.http.basePath.prepend(url)); diff --git a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts b/x-pack/plugins/monitoring/public/angular/helpers/routes.ts index b9307e8594a7a..22b6fd8a4e912 100644 --- a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts +++ b/x-pack/plugins/monitoring/public/angular/helpers/routes.ts @@ -26,7 +26,7 @@ class Routes { }; public addToProvider = ($routeProvider: any) => { - this.routes.forEach(args => { + this.routes.forEach((args) => { $routeProvider.when.apply(this, args); }); diff --git a/x-pack/plugins/monitoring/public/angular/providers/private.js b/x-pack/plugins/monitoring/public/angular/providers/private.js index e456f2617f7b8..3a667037b2919 100644 --- a/x-pack/plugins/monitoring/public/angular/providers/private.js +++ b/x-pack/plugins/monitoring/public/angular/providers/private.js @@ -86,13 +86,7 @@ import _ from 'lodash'; const nextId = _.partial(_.uniqueId, 'privateProvider#'); function name(fn) { - return ( - fn.name || - fn - .toString() - .split('\n') - .shift() - ); + return fn.name || fn.toString().split('\n').shift(); } export function PrivateProvider() { @@ -112,12 +106,12 @@ export function PrivateProvider() { else return (fn.$$id = nextId()); } - provider.stub = function(fn, instance) { + provider.stub = function (fn, instance) { cache[identify(fn)] = instance; return instance; }; - provider.swap = function(fn, prov) { + provider.swap = function (fn, prov) { const id = identify(fn); swaps[id] = prov; }; @@ -127,7 +121,7 @@ export function PrivateProvider() { function PrivateFactory($injector) { // prevent circular deps by tracking where we came from const privPath = []; - const pathToString = function() { + const pathToString = function () { return privPath.map(name).join(' -> '); }; diff --git a/x-pack/plugins/monitoring/public/angular/providers/url.js b/x-pack/plugins/monitoring/public/angular/providers/url.js index 57b63708b546e..0c984a71c9f2c 100644 --- a/x-pack/plugins/monitoring/public/angular/providers/url.js +++ b/x-pack/plugins/monitoring/public/angular/providers/url.js @@ -34,7 +34,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.change = function(url, paramObj, appState) { + self.change = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, false, appState); }; @@ -46,7 +46,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.changePath = function(path, paramObj) { + self.changePath = function (path, paramObj) { self._changeLocation('path', path, paramObj); }; @@ -57,7 +57,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.redirect = function(url, paramObj, appState) { + self.redirect = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, true, appState); }; @@ -69,7 +69,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.redirectPath = function(path, paramObj) { + self.redirectPath = function (path, paramObj) { self._changeLocation('path', path, paramObj, true); }; @@ -82,10 +82,10 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @return {String} - the evaluated result * @throws {Error} If any of the expressions can't be parsed. */ - self.eval = function(template, paramObj) { + self.eval = function (template, paramObj) { paramObj = paramObj || {}; - return template.replace(/\{\{([^\}]+)\}\}/g, function(match, expr) { + return template.replace(/\{\{([^\}]+)\}\}/g, function (match, expr) { // remove filters const key = expr.split('|')[0].trim(); @@ -109,7 +109,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {string} - the computed href */ - self.getRouteHref = function(obj, route) { + self.getRouteHref = function (obj, route) { return '#' + self.getRouteUrl(obj, route); }; @@ -120,7 +120,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {string} - the computed url */ - self.getRouteUrl = function(obj, route) { + self.getRouteUrl = function (obj, route) { const template = obj && obj.routes && obj.routes[route]; if (template) return self.eval(template, obj); }; @@ -133,7 +133,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {undefined} */ - self.redirectToRoute = function(obj, route) { + self.redirectToRoute = function (obj, route) { self.redirect(self.getRouteUrl(obj, route)); }; @@ -145,7 +145,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {undefined} */ - self.changeToRoute = function(obj, route) { + self.changeToRoute = function (obj, route) { self.change(self.getRouteUrl(obj, route)); }; @@ -154,7 +154,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * history. * @param param */ - self.removeParam = function(param) { + self.removeParam = function (param) { $location.search(param, null).replace(); }; @@ -163,7 +163,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { ///// let reloading; - self._changeLocation = function(type, url, paramObj, replace, appState) { + self._changeLocation = function (type, url, paramObj, replace, appState) { const prev = { path: $location.path(), search: $location.search(), @@ -186,7 +186,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { const $route = $injector.get('$route'); if (self._shouldForceReload(next, prev, $route)) { - reloading = $rootScope.$on('$locationChangeSuccess', function() { + reloading = $rootScope.$on('$locationChangeSuccess', function () { // call the "unlisten" function returned by $on reloading(); reloading = false; @@ -198,7 +198,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { }; // determine if the router will automatically reload the route - self._shouldForceReload = function(next, prev, $route) { + self._shouldForceReload = function (next, prev, $route) { if (reloading) return false; const route = $route.current && $route.current.$$route; diff --git a/x-pack/plugins/monitoring/public/components/alerts/alerts.js b/x-pack/plugins/monitoring/public/components/alerts/alerts.js index a86fdb1041a5c..0ac67228db359 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/alerts.js +++ b/x-pack/plugins/monitoring/public/components/alerts/alerts.js @@ -36,7 +36,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'status', sortable: true, - render: severity => { + render: (severity) => { const severityIconDefaults = { title: i18n.translate('xpack.monitoring.alerts.severityTitle.unknown', { defaultMessage: 'Unknown', @@ -67,7 +67,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'resolved_timestamp', sortable: true, - render: resolvedTimestamp => { + render: (resolvedTimestamp) => { const notResolvedLabel = i18n.translate('xpack.monitoring.alerts.notResolvedDescription', { defaultMessage: 'Not Resolved', }); @@ -109,7 +109,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ suffix={alert.suffix} message={message} metadata={alert.metadata} - changeUrl={target => { + changeUrl={(target) => { scope.$evalAsync(() => { kbnUrl.changePath(target); }); @@ -124,7 +124,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'category', sortable: true, - render: link => + render: (link) => linkToCategories[link] ? linkToCategories[link] : i18n.translate('xpack.monitoring.alerts.categoryColumn.generalLabel', { @@ -137,7 +137,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'update_timestamp', sortable: true, - render: timestamp => formatDateTimeLocal(timestamp, timezone), + render: (timestamp) => formatDateTimeLocal(timestamp, timezone), }, { name: i18n.translate('xpack.monitoring.alerts.triggeredColumnTitle', { @@ -145,7 +145,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'timestamp', sortable: true, - render: timestamp => + render: (timestamp) => i18n.translate('xpack.monitoring.alerts.triggeredColumnValue', { defaultMessage: '{timestamp} ago', values: { @@ -156,7 +156,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ ]; export const Alerts = ({ alerts, angular, sorting, pagination, onTableChange }) => { - const alertsFlattened = alerts.map(alert => ({ + const alertsFlattened = alerts.map((alert) => ({ ...alert, status: get(alert, 'metadata.severity', get(alert, 'severity', 0)), category: get(alert, 'metadata.link', get(alert, 'type', null)), diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx index 2c2d7c6464e1b..7caef8c230bf4 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx @@ -30,13 +30,7 @@ describe('Configuration', () => { }); function getStep(component: ShallowWrapper, index: number) { - return component - .find('EuiSteps') - .shallow() - .find('EuiStep') - .at(index) - .children() - .shallow(); + return component.find('EuiSteps').shallow().find('EuiStep').at(index).children().shallow(); } describe('shallow view', () => { @@ -82,12 +76,7 @@ describe('Configuration', () => { it('reflect in Step1', async () => { const steps = component.find('EuiSteps').dive(); - expect( - steps - .find('EuiStep') - .at(0) - .prop('title') - ).toBe('Select email action'); + expect(steps.find('EuiStep').at(0).prop('title')).toBe('Select email action'); expect(steps.find('Step1').prop('selectedEmailActionId')).toBe(actionId); }); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx index 5734d379dfb0c..69dedd71284af 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx @@ -209,7 +209,7 @@ describe('Step1', () => { jest.doMock('../../../legacy_shims', () => ({ Legacy: { shims: { - kfetch: jest.fn().mockImplementation(arg => { + kfetch: jest.fn().mockImplementation((arg) => { if (arg.pathname === '/api/action/1/_execute') { return { status: 'ok' }; } @@ -223,29 +223,11 @@ describe('Step1', () => { const component = shallow(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(false); - component - .find('EuiButton') - .at(1) - .simulate('click'); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(true); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); + component.find('EuiButton').at(1).simulate('click'); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(true); await component.update(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(false); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); }); it('should show a successful test', async () => { @@ -267,10 +249,7 @@ describe('Step1', () => { const component = shallow(); - component - .find('EuiButton') - .at(1) - .simulate('click'); + component.find('EuiButton').at(1).simulate('click'); await component.update(); expect(component).toMatchSnapshot(); }); @@ -294,10 +273,7 @@ describe('Step1', () => { const component = shallow(); - component - .find('EuiButton') - .at(1) - .simulate('click'); + component.find('EuiButton').at(1).simulate('click'); await component.update(); expect(component).toMatchSnapshot(); }); @@ -307,12 +283,7 @@ describe('Step1', () => { emailAddress: '', }; const component = shallow(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isDisabled') - ).toBe(true); + expect(component.find('EuiButton').at(1).prop('isDisabled')).toBe(true); }); it('should should a tooltip if there is no email address', () => { @@ -344,10 +315,7 @@ describe('Step1', () => { }; const component = shallow(); - await component - .find('EuiButton') - .at(2) - .simulate('click'); + await component.find('EuiButton').at(2).simulate('click'); await component.update(); expect(kfetch).toHaveBeenCalledWith({ @@ -357,12 +325,7 @@ describe('Step1', () => { expect(customProps.setSelectedEmailActionId).toHaveBeenCalledWith(''); expect(customProps.onActionDone).toHaveBeenCalled(); - expect( - component - .find('EuiButton') - .at(2) - .prop('isLoading') - ).toBe(false); + expect(component.find('EuiButton').at(2).prop('isLoading')).toBe(false); }); }); }); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx index 7953010005885..27e46ef82a1b4 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx @@ -178,7 +178,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { ); const options = [ - ...props.emailActions.map(action => { + ...props.emailActions.map((action) => { const actionLabel = i18n.translate( 'xpack.monitoring.alerts.configuration.selectAction.inputDisplay', { @@ -207,7 +207,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { props.setSelectedEmailActionId(id)} + onChange={(id) => props.setSelectedEmailActionId(id)} hasDividers /> ); @@ -238,7 +238,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { let manageConfiguration = null; const selectedEmailAction = props.emailActions.find( - action => action.id === props.selectedEmailActionId + (action) => action.id === props.selectedEmailActionId ); if ( @@ -288,7 +288,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { iconType="pencil" onClick={() => { const editAction = - props.emailActions.find(action => action.id === props.selectedEmailActionId) || + props.emailActions.find((action) => action.id === props.selectedEmailActionId) || null; props.setEditAction(editAction); }} diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx index 974dd8513d231..2c215e310af69 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx @@ -30,7 +30,7 @@ export const Step2: React.FC = (props: GetStep2Props) => { props.setEmailAddress(e.target.value)} + onChange={(e) => props.setEmailAddress(e.target.value)} /> diff --git a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx b/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx index 3ef9654076340..87588a435078d 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx @@ -108,7 +108,7 @@ export const ManageEmailAction: React.FC = ( } } - const serviceOptions = ALERT_EMAIL_SERVICES.map(service => ({ + const serviceOptions = ALERT_EMAIL_SERVICES.map((service) => ({ value: service, inputDisplay: {service}, dropdownDisplay: {service}, @@ -139,7 +139,7 @@ export const ManageEmailAction: React.FC = ( setNewService(e.target.value)} + onChange={(e) => setNewService(e.target.value)} isInvalid={showErrors} /> @@ -166,7 +166,7 @@ export const ManageEmailAction: React.FC = ( { + onChange={(id) => { if (id === NEW_SERVICE_ID) { setCreateNewService(true); setData({ ...data, service: NEW_SERVICE_ID }); @@ -194,7 +194,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, host: e.target.value })} + onChange={(e) => setData({ ...data, host: e.target.value })} isInvalid={showErrors && !!errors.host} /> @@ -211,7 +211,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, port: parseInt(e.target.value, 10) })} + onChange={(e) => setData({ ...data, port: parseInt(e.target.value, 10) })} isInvalid={showErrors && !!errors.port} /> @@ -227,7 +227,7 @@ export const ManageEmailAction: React.FC = ( setData({ ...data, secure: e.target.checked })} + onChange={(e) => setData({ ...data, secure: e.target.checked })} /> @@ -243,7 +243,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, from: e.target.value })} + onChange={(e) => setData({ ...data, from: e.target.value })} isInvalid={showErrors && !!errors.from} /> @@ -260,7 +260,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, user: e.target.value })} + onChange={(e) => setData({ ...data, user: e.target.value })} isInvalid={showErrors && !!errors.user} /> @@ -277,7 +277,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, password: e.target.value })} + onChange={(e) => setData({ ...data, password: e.target.value })} isInvalid={showErrors && !!errors.password} /> diff --git a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx index a0031f50951bd..1c35328d2f881 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx @@ -71,7 +71,7 @@ describe('Status', () => { it('should render a success message if all alerts have been migrated and in setup mode', async () => { (Legacy.shims.kfetch as jest.Mock).mockReturnValue({ - data: ALERT_TYPES.map(type => ({ alertTypeId: type })), + data: ALERT_TYPES.map((type) => ({ alertTypeId: type })), }); (getSetupModeState as jest.Mock).mockReturnValue({ diff --git a/x-pack/plugins/monitoring/public/components/apm/instances/instances.js b/x-pack/plugins/monitoring/public/components/apm/instances/instances.js index a48fbc51341f1..9d0d2c5aefa56 100644 --- a/x-pack/plugins/monitoring/public/components/apm/instances/instances.js +++ b/x-pack/plugins/monitoring/public/components/apm/instances/instances.js @@ -79,28 +79,28 @@ function getColumns(setupMode) { defaultMessage: 'Total Events Rate', }), field: 'total_events_rate', - render: value => formatMetric(value, '', '/s'), + render: (value) => formatMetric(value, '', '/s'), }, { name: i18n.translate('xpack.monitoring.apm.instances.bytesSentRateTitle', { defaultMessage: 'Bytes Sent Rate', }), field: 'bytes_sent_rate', - render: value => formatMetric(value, 'byte', '/s'), + render: (value) => formatMetric(value, 'byte', '/s'), }, { name: i18n.translate('xpack.monitoring.apm.instances.outputErrorsTitle', { defaultMessage: 'Output Errors', }), field: 'errors', - render: value => formatMetric(value, '0'), + render: (value) => formatMetric(value, '0'), }, { name: i18n.translate('xpack.monitoring.apm.instances.lastEventTitle', { defaultMessage: 'Last Event', }), field: 'time_of_last_event', - render: value => + render: (value) => i18n.translate('xpack.monitoring.apm.instances.lastEventValue', { defaultMessage: '{timeOfLastEvent} ago', values: { @@ -113,7 +113,7 @@ function getColumns(setupMode) { defaultMessage: 'Allocated Memory', }), field: 'memory', - render: value => formatMetric(value, 'byte'), + render: (value) => formatMetric(value, 'byte'), }, { name: i18n.translate('xpack.monitoring.apm.instances.versionTitle', { @@ -138,7 +138,7 @@ export function ApmServerInstances({ apms, setupMode }) { ); } - const versions = uniq(data.apms.map(item => item.version)).map(version => { + const versions = uniq(data.apms.map((item) => item.version)).map((version) => { return { value: version }; }); diff --git a/x-pack/plugins/monitoring/public/components/beats/listing/listing.js b/x-pack/plugins/monitoring/public/components/beats/listing/listing.js index 5863f6e5161ad..81ae6796d7294 100644 --- a/x-pack/plugins/monitoring/public/components/beats/listing/listing.js +++ b/x-pack/plugins/monitoring/public/components/beats/listing/listing.js @@ -86,28 +86,28 @@ export class Listing extends PureComponent { defaultMessage: 'Total Events Rate', }), field: 'total_events_rate', - render: value => formatMetric(value, '', '/s'), + render: (value) => formatMetric(value, '', '/s'), }, { name: i18n.translate('xpack.monitoring.beats.instances.bytesSentRateTitle', { defaultMessage: 'Bytes Sent Rate', }), field: 'bytes_sent_rate', - render: value => formatMetric(value, 'byte', '/s'), + render: (value) => formatMetric(value, 'byte', '/s'), }, { name: i18n.translate('xpack.monitoring.beats.instances.outputErrorsTitle', { defaultMessage: 'Output Errors', }), field: 'errors', - render: value => formatMetric(value, '0'), + render: (value) => formatMetric(value, '0'), }, { name: i18n.translate('xpack.monitoring.beats.instances.allocatedMemoryTitle', { defaultMessage: 'Allocated Memory', }), field: 'memory', - render: value => formatMetric(value, 'byte'), + render: (value) => formatMetric(value, 'byte'), }, { name: i18n.translate('xpack.monitoring.beats.instances.versionTitle', { @@ -132,11 +132,11 @@ export class Listing extends PureComponent { ); } - const types = uniq(data.map(item => item.type)).map(type => { + const types = uniq(data.map((item) => item.type)).map((type) => { return { value: type }; }); - const versions = uniq(data.map(item => item.version)).map(version => { + const versions = uniq(data.map((item) => item.version)).map((version) => { return { value: version }; }); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js index c1f0d3e8bbb23..7b70f1d1fb224 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getColor } from '../get_color'; -describe('getColors', function() { +describe('getColors', function () { it('elasticsearch colors', () => { expect(getColor('elasticsearch', 0)).to.be('#3ebeb0'); expect(getColor('elasticsearch', 1)).to.be('#3b73ac'); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js index bc469b7149e2c..c089b47408e81 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getLastValue } from '../get_last_value'; -describe('monitoringChartGetLastValue', function() { +describe('monitoringChartGetLastValue', function () { it('getLastValue for single number', () => { expect(getLastValue(3)).to.be(3); }); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js index 66100ee573aca..a7f4b48a5862a 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getTitle } from '../get_title'; -describe('getTitle', function() { +describe('getTitle', function () { it('with metric.title', () => { const series = [ { metric: { title: 'Foo', label: 'Bar X' } }, diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js index 59386996678dc..e5c933426efcd 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { findIndexByX, getValuesByX, getValuesForSeriesIndex } from '../get_values_for_legend'; -describe('monitoringChartHelpers', function() { +describe('monitoringChartHelpers', function () { it('getValuesForSeriesIndex sets does not impact callback without series', () => { const callback = sinon.stub(); diff --git a/x-pack/plugins/monitoring/public/components/chart/chart_target.js b/x-pack/plugins/monitoring/public/components/chart/chart_target.js index e6a6cc4b77755..31199c5b092f6 100644 --- a/x-pack/plugins/monitoring/public/components/chart/chart_target.js +++ b/x-pack/plugins/monitoring/public/components/chart/chart_target.js @@ -42,8 +42,8 @@ export class ChartTarget extends React.Component { filterByShow(seriesToShow) { if (seriesToShow) { - return metric => { - return seriesToShow.some(id => id.toLowerCase() === metric.id.toLowerCase()); + return (metric) => { + return seriesToShow.some((id) => id.toLowerCase() === metric.id.toLowerCase()); }; } return () => true; @@ -73,9 +73,7 @@ export class ChartTarget extends React.Component { } filterData(data, seriesToShow) { - return _(data) - .filter(this.filterByShow(seriesToShow)) - .value(); + return _(data).filter(this.filterByShow(seriesToShow)).value(); } async getOptions() { diff --git a/x-pack/plugins/monitoring/public/components/chart/get_title.js b/x-pack/plugins/monitoring/public/components/chart/get_title.js index 4450352add45f..bb40551fe8428 100644 --- a/x-pack/plugins/monitoring/public/components/chart/get_title.js +++ b/x-pack/plugins/monitoring/public/components/chart/get_title.js @@ -12,7 +12,7 @@ import { chain } from 'lodash'; */ export function getTitle(series = []) { return chain( - series.map(s => { + series.map((s) => { return s.metric.title || s.metric.label; }) ) diff --git a/x-pack/plugins/monitoring/public/components/chart/get_units.js b/x-pack/plugins/monitoring/public/components/chart/get_units.js index e8348059a6d4d..fd377cced122c 100644 --- a/x-pack/plugins/monitoring/public/components/chart/get_units.js +++ b/x-pack/plugins/monitoring/public/components/chart/get_units.js @@ -13,7 +13,7 @@ export function getUnits(series) { // For Bytes, find the largest unit from any data set's _last_ item if (units === 'B') { let maxLastBytes = 0; - forEach(series, s => { + forEach(series, (s) => { const lastDataPoint = last(s.data) || [null, 0]; maxLastBytes = Math.max(maxLastBytes, lastDataPoint[1]); // lastDataPoint[1] is the "y" value }); diff --git a/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js b/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js index ab322324ac200..738775ed8d4d9 100644 --- a/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js +++ b/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js @@ -71,7 +71,7 @@ export class HorizontalLegend extends React.Component { @@ -113,7 +113,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( @@ -189,7 +189,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( @@ -253,7 +253,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( diff --git a/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx b/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx index 860fe22cb8032..7abf34700ad7a 100644 --- a/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx @@ -58,7 +58,7 @@ export const DeleteProvider: React.FunctionComponent = ({ setIsDeleteInProgress(true); try { - result = await roleMappingsAPI.deleteRoleMappings(roleMappings.map(rm => rm.name)); + result = await roleMappingsAPI.deleteRoleMappings(roleMappings.map((rm) => rm.name)); } catch (e) { notifications.toasts.addError(e, { title: i18n.translate( @@ -76,8 +76,8 @@ export const DeleteProvider: React.FunctionComponent = ({ closeModal(); - const successfulDeletes = result.filter(res => res.success); - const erroredDeletes = result.filter(res => !res.success); + const successfulDeletes = result.filter((res) => res.success); + const erroredDeletes = result.filter((res) => !res.success); // Surface success notifications if (successfulDeletes.length > 0) { diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx index 149c1271123d2..eea6bbef94306 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx @@ -64,10 +64,7 @@ describe('EditRoleMappingPage', () => { target: { value: 'my-role-mapping' }, }); - wrapper - .find(RoleComboBox) - .props() - .onChange(['foo_role']); + wrapper.find(RoleComboBox).props().onChange(['foo_role']); findTestSubject(wrapper, 'roleMappingsAddRuleButton').simulate('click'); @@ -127,10 +124,7 @@ describe('EditRoleMappingPage', () => { findTestSubject(wrapper, 'switchToRolesButton').simulate('click'); - wrapper - .find(RoleComboBox) - .props() - .onChange(['foo_role']); + wrapper.find(RoleComboBox).props().onChange(['foo_role']); findTestSubject(wrapper, 'roleMappingsAddRuleButton').simulate('click'); wrapper.find('button[id="addRuleOption"]').simulate('click'); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx index 142b53cbb50f2..3b16bd8dc44ac 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx @@ -106,7 +106,7 @@ export class EditRoleMappingPage extends Component { this.setState({ roleMapping })} + onChange={(roleMapping) => this.setState({ roleMapping })} mode={this.editingExistingRoleMapping() ? 'edit' : 'create'} validateForm={this.state.validateForm} canUseInlineScripts={this.state.canUseInlineScripts} @@ -119,7 +119,7 @@ export class EditRoleMappingPage extends Component { rawRules={this.state.roleMapping!.rules} validateForm={this.state.validateForm} onValidityChange={this.onRuleValidityChange} - onChange={rules => + onChange={(rules) => this.setState({ roleMapping: { ...this.state.roleMapping!, @@ -218,7 +218,7 @@ export class EditRoleMappingPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingsPrompt => { + {(deleteRoleMappingsPrompt) => { return ( @@ -279,7 +279,7 @@ export class EditRoleMappingPage extends Component { }); this.backToRoleMappingsList(); }) - .catch(e => { + .catch((e) => { this.props.notifications.toasts.addError(e, { title: i18n.translate('xpack.security.management.editRoleMapping.saveError', { defaultMessage: `Error saving role mapping`, diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx index b376a3943ff48..3df9987141fb2 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx @@ -172,7 +172,7 @@ export class MappingInfoPanel extends Component { mode={this.state.rolesMode} canUseInlineScripts={this.props.canUseInlineScripts} canUseStoredScripts={this.props.canUseStoredScripts} - onChange={roleMapping => this.props.onChange(roleMapping)} + onChange={(roleMapping) => this.props.onChange(roleMapping)} /> @@ -240,7 +240,7 @@ export class MappingInfoPanel extends Component { mode={this.state.rolesMode} canUseInlineScripts={this.props.canUseInlineScripts} canUseStoredScripts={this.props.canUseStoredScripts} - onChange={roleMapping => this.props.onChange(roleMapping)} + onChange={(roleMapping) => this.props.onChange(roleMapping)} /> @@ -286,7 +286,7 @@ export class MappingInfoPanel extends Component { showLabel={false} data-test-subj="roleMappingsEnabledSwitch" checked={this.props.roleMapping.enabled} - onChange={e => { + onChange={(e) => { this.props.onChange({ ...this.props.roleMapping, enabled: e.target.checked, diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx index 8e1597cf3d598..b0f558ee71be8 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx @@ -59,7 +59,7 @@ export class RoleSelector extends React.Component { isLoading={this.state.roles.length === 0} availableRoles={this.state.roles} selectedRoleNames={roles} - onChange={selectedRoles => { + onChange={(selectedRoles) => { this.props.onChange({ ...this.props.roleMapping, roles: selectedRoles, @@ -80,7 +80,7 @@ export class RoleSelector extends React.Component { canUseStoredScripts={this.props.canUseStoredScripts} canUseInlineScripts={this.props.canUseInlineScripts} roleTemplate={rt} - onChange={updatedTemplate => { + onChange={(updatedTemplate) => { const templates = [...(this.props.roleMapping.role_templates || [])]; templates.splice(index, 1, updatedTemplate); this.props.onChange({ @@ -103,7 +103,7 @@ export class RoleSelector extends React.Component { { + onClick={(type) => { switch (type) { case 'inline': { const templates = this.props.roleMapping.role_templates || []; @@ -147,8 +147,8 @@ export class RoleSelector extends React.Component { private hasDeprecatedRolesAssigned = () => { return ( - this.props.roleMapping.roles?.some(r => - this.state.roles.some(role => role.name === r && isRoleDeprecated(role)) + this.props.roleMapping.roles?.some((r) => + this.state.roles.some((role) => role.name === r && isRoleDeprecated(role)) ) ?? false ); }; diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx index d79651d7b9cd6..0191f7194e8e5 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx @@ -81,7 +81,7 @@ export const RoleTemplateEditor = ({ checked={roleTemplate.format === 'json'} label={returnsJsonLabel} showLabel={false} - onChange={e => { + onChange={(e) => { onChange({ ...roleTemplate, format: e.target.checked ? 'json' : 'string', @@ -164,7 +164,7 @@ export const RoleTemplateEditor = ({ { + onChange={(e) => { onChange({ ...roleTemplate, template: { @@ -213,7 +213,7 @@ export const RoleTemplateEditor = ({ { + onChange={(e) => { onChange({ ...roleTemplate, template: { diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx index aa65c5c9bcae7..9bbf4b7ff405a 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx @@ -53,7 +53,7 @@ export const RoleTemplateTypeSelect = (props: Props) => { singleSelection={{ asPlainText: true }} selectedOptions={selectedOptions} data-test-subj="roleMappingsFormTemplateType" - onChange={selected => { + onChange={(selected) => { const [{ id }] = selected; if (id === 'inline') { props.onChange({ diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx index 6022c836c6904..125e751f9a91b 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx @@ -41,7 +41,7 @@ const userFields = [ }, ]; -const fieldOptions = userFields.map(f => ({ label: f.name })); +const fieldOptions = userFields.map((f) => ({ label: f.name })); type ComparisonOption = 'text' | 'number' | 'null' | 'boolean'; const comparisonOptions: Record< @@ -196,7 +196,7 @@ export class FieldRuleEditor extends Component { ]} data-test-subj={`fieldRuleEditorValueType-${valueIndex}`} value={inputType} - onChange={e => + onChange={(e) => this.onComparisonTypeChange(valueIndex, e.target.value as ComparisonOption) } /> diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx index 5946aac4306b1..48eb1380bd08f 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx @@ -48,7 +48,7 @@ describe('RuleGroupEditor', () => { await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); @@ -76,13 +76,11 @@ describe('RuleGroupEditor', () => { const anyRule = new AnyRule(); - findTestSubject(wrapper, 'ruleGroupTitle') - .first() - .simulate('click'); + findTestSubject(wrapper, 'ruleGroupTitle').first().simulate('click'); await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); @@ -116,13 +114,11 @@ describe('RuleGroupEditor', () => { const anyRule = new AnyRule(); - findTestSubject(wrapper, 'ruleGroupTitle') - .first() - .simulate('click'); + findTestSubject(wrapper, 'ruleGroupTitle').first().simulate('click'); await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx index b10a6dd8d183f..2e6cfa5f1cde6 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx @@ -90,7 +90,7 @@ export class RuleGroupEditor extends Component { parentRule={this.props.rule} allowAdd={this.props.allowAdd} ruleDepth={this.props.ruleDepth + 1} - onChange={updatedSubRule => { + onChange={(updatedSubRule) => { const updatedRule = this.props.rule.clone() as RuleGroup; updatedRule.replaceRule(subRuleIndex, updatedSubRule); this.props.onChange(updatedRule); @@ -112,7 +112,7 @@ export class RuleGroupEditor extends Component { { + onChange={(updatedSubRule) => { const updatedRule = this.props.rule.clone() as RuleGroup; updatedRule.replaceRule(subRuleIndex, updatedSubRule); this.props.onChange(updatedRule); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx index 6bef9c09eeef3..6f9853041ffbe 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx @@ -42,7 +42,7 @@ export const RuleGroupTitle = (props: Props) => { const areSubRulesValid = newRule.canContainRules(currentSubRules); if (areSubRulesValid) { const clone = newRule.clone() as RuleGroup; - currentSubRules.forEach(subRule => clone.addRule(subRule)); + currentSubRules.forEach((subRule) => clone.addRule(subRule)); props.onChange(clone); setIsMenuOpen(false); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx index 2e3db275788ee..cb50d30b02a1e 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx @@ -127,7 +127,7 @@ export class VisualRuleEditor extends Component { rule={rule as RuleGroup} ruleDepth={0} allowAdd={this.canUseVisualEditor()} - onChange={value => onChange(value)} + onChange={(value) => onChange(value)} onDelete={this.onRuleDelete} /> ); @@ -135,7 +135,7 @@ export class VisualRuleEditor extends Component { return ( onChange(value)} + onChange={(value) => onChange(value)} onDelete={this.onRuleDelete} /> ); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts index ddf3b4499f73b..d046945747a57 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts @@ -28,7 +28,7 @@ describe('All rule', () => { const rule = new AllRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts index ecea27a7fb87f..f948d4c15e611 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts @@ -50,13 +50,13 @@ export class AllRule extends RuleGroup { /** {@see RuleGroup.clone} */ public clone() { - return new AllRule(this.rules.map(r => r.clone())); + return new AllRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { return { - all: [...this.rules.map(rule => rule.toRaw())], + all: [...this.rules.map((rule) => rule.toRaw())], }; } } diff --git a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts index 767aa075755af..d56469c4c9622 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts @@ -22,7 +22,7 @@ describe('Any rule', () => { const rule = new AnyRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts index 6a4f2eaf1b362..5f3f190dd0f37 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts @@ -49,19 +49,19 @@ export class AnyRule extends RuleGroup { public canContainRules(rules: Rule[]) { const forbiddenRules = [ExceptAllRule, ExceptAnyRule]; return rules.every( - candidate => !forbiddenRules.some(forbidden => candidate instanceof forbidden) + (candidate) => !forbiddenRules.some((forbidden) => candidate instanceof forbidden) ); } /** {@see RuleGroup.clone} */ public clone() { - return new AnyRule(this.rules.map(r => r.clone())); + return new AnyRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { return { - any: [...this.rules.map(rule => rule.toRaw())], + any: [...this.rules.map((rule) => rule.toRaw())], }; } } diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts index 7a00e5b19638f..73a5451534ec0 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts @@ -28,7 +28,7 @@ describe('Except All rule', () => { const rule = new ExceptAllRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts index a67c2622a2533..af75f08539c1c 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts @@ -50,13 +50,13 @@ export class ExceptAllRule extends RuleGroup { /** {@see RuleGroup.clone} */ public clone() { - return new ExceptAllRule(this.rules.map(r => r.clone())); + return new ExceptAllRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { const rawRule = { - all: [...this.rules.map(rule => rule.toRaw())], + all: [...this.rules.map((rule) => rule.toRaw())], }; return { diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts index e4e182ce88d8d..902c706d75aec 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts @@ -22,7 +22,7 @@ describe('Except Any rule', () => { const rule = new ExceptAnyRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts index 12ec3fe85b80d..e7bc6a7b0ae4e 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts @@ -48,19 +48,19 @@ export class ExceptAnyRule extends RuleGroup { public canContainRules(rules: Rule[]) { const forbiddenRules = [ExceptAllRule, ExceptAnyRule]; return rules.every( - candidate => !forbiddenRules.some(forbidden => candidate instanceof forbidden) + (candidate) => !forbiddenRules.some((forbidden) => candidate instanceof forbidden) ); } /** {@see RuleGroup.clone} */ public clone() { - return new ExceptAnyRule(this.rules.map(r => r.clone())); + return new ExceptAnyRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { const rawRule = { - any: [...this.rules.map(rule => rule.toRaw())], + any: [...this.rules.map((rule) => rule.toRaw())], }; return { diff --git a/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts index 3447e81707002..b7bb2a4170ff1 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts @@ -7,7 +7,7 @@ import { FieldRule } from '.'; describe('FieldRule', () => { - ['*', 1, null, true, false].forEach(value => { + ['*', 1, null, true, false].forEach((value) => { it(`can convert itself to raw form with a single value of ${value}`, () => { const rule = new FieldRule('username', value); expect(rule.toRaw()).toEqual({ diff --git a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts index ad486a8b314c4..fea110e6beca4 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts @@ -252,7 +252,7 @@ describe('generateRulesFromRaw', () => { expect((rules as FieldRule).value).toEqual([0, '*', null, 'foo', true, false]); }); - [{}, () => null, undefined, [{}, undefined, [], () => null]].forEach(invalidValue => { + [{}, () => null, undefined, [{}, undefined, [], () => null]].forEach((invalidValue) => { it(`does not support a value of ${invalidValue}`, () => { expect(() => { generateRulesFromRaw({ diff --git a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts index a384e61e521ab..44c6ace3bfeac 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts @@ -92,7 +92,7 @@ function createRuleForType( const [field, value] = entries[0] as [string, FieldRuleValue]; const values = Array.isArray(value) ? value : [value]; - values.forEach(fieldValue => { + values.forEach((fieldValue) => { const valueType = typeof fieldValue; if (fieldValue !== null && !['string', 'number', 'boolean'].includes(valueType)) { throw new RuleBuilderError( diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts b/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts index 0a88ed1da9ac3..8e8bae42d4ad8 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts @@ -47,11 +47,11 @@ export class RoleMappingsAPIClient { public async deleteRoleMappings(names: string[]): Promise { return Promise.all( - names.map(name => + names.map((name) => this.http .delete(`/internal/security/role_mapping/${encodeURIComponent(name)}`) .then(() => ({ success: true, name })) - .catch(error => ({ success: false, name, error })) + .catch((error) => ({ success: false, name, error })) ) ); } diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx index 5802c3444e85f..d0bc96b4fcedf 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx @@ -192,9 +192,7 @@ export class RoleMappingsGridPage extends Component { id="xpack.security.management.roleMappings.roleMappingTableLoadingMessage" defaultMessage="Loading role mappings…" /> - ) : ( - undefined - ); + ) : undefined; const sorting = { sort: { @@ -222,7 +220,7 @@ export class RoleMappingsGridPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingsPrompt => { + {(deleteRoleMappingsPrompt) => { return ( deleteRoleMappingsPrompt(selectedItems, this.onRoleMappingsDeleted)} @@ -240,9 +238,7 @@ export class RoleMappingsGridPage extends Component { ); }} - ) : ( - undefined - ), + ) : undefined, toolsRight: ( { } const roleLinks = assignedRoleNames.map((rolename, index) => { const role: Role | string = - this.state.roles?.find(r => r.name === rolename) ?? rolename; + this.state.roles?.find((r) => r.name === rolename) ?? rolename; return ; }); @@ -386,7 +382,7 @@ export class RoleMappingsGridPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingPrompt => { + {(deleteRoleMappingPrompt) => { return ( (null); useEffect(() => { userAPIClient.getUsers().then( - users => setUserNames(users.map(user => user.username)), - err => fatalErrors.add(err) + (users) => setUserNames(users.map((user) => user.username)), + (err) => fatalErrors.add(err) ); }, [fatalErrors, userAPIClient]); @@ -143,7 +143,7 @@ function usePrivileges( ]).then( ([kibanaPrivileges, builtInESPrivileges]) => setPrivileges([kibanaPrivileges, builtInESPrivileges]), - err => fatalErrors.add(err) + (err) => fatalErrors.add(err) ); }, [privilegesAPIClient, fatalErrors]); @@ -170,7 +170,7 @@ function useRole( } as Role); rolePromise - .then(fetchedRole => { + .then((fetchedRole) => { if (action === 'clone' && checkIfRoleReserved(fetchedRole)) { backToRoleList(); return; @@ -225,8 +225,8 @@ function useSpaces(http: HttpStart, fatalErrors: FatalErrorsSetup, spacesEnabled const [spaces, setSpaces] = useState(null); useEffect(() => { (spacesEnabled ? http.get('/api/spaces/space') : Promise.resolve([])).then( - fetchedSpaces => setSpaces(fetchedSpaces), - err => fatalErrors.add(err) + (fetchedSpaces) => setSpaces(fetchedSpaces), + (err) => fatalErrors.add(err) ); }, [http, fatalErrors, spacesEnabled]); @@ -255,7 +255,7 @@ function useFeatures( fatalErrors.add(err); }) - .then(retrievedFeatures => { + .then((retrievedFeatures) => { setFeatures(retrievedFeatures); }); }, [fatalErrors, getFeatures]); @@ -380,9 +380,7 @@ export const EditRolePage: FunctionComponent = ({ id="xpack.security.management.editRole.roleNameFormRowHelpText" defaultMessage="A role's name cannot be changed once it has been created." /> - ) : ( - undefined - ) + ) : undefined } {...validator.validateRoleName(role)} > diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx index 54be04ade370e..0041e63da1fba 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx @@ -24,11 +24,11 @@ export class ClusterPrivileges extends Component { public buildComboBox = (items: string[]) => { const role = this.props.role; - const options = items.map(i => ({ + const options = items.map((i) => ({ label: i, })); - const selectedOptions = (role.elasticsearch.cluster || []).map(k => ({ label: k })); + const selectedOptions = (role.elasticsearch.cluster || []).map((k) => ({ label: k })); return ( diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx index 96249ccf3ff87..46e0183b2f38c 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx @@ -133,12 +133,12 @@ export class ElasticsearchPrivileges extends Component { ) : undefined } - options={this.props.runAsUsers.map(username => ({ + options={this.props.runAsUsers.map((username) => ({ id: username, label: username, isGroupLabelOption: false, }))} - selectedOptions={this.props.role.elasticsearch.run_as.map(u => ({ label: u }))} + selectedOptions={this.props.role.elasticsearch.run_as.map((u) => ({ label: u }))} onCreateOption={this.onCreateRunAsOption} onChange={this.onRunAsUserChange} isDisabled={!editable} diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx index 32e8a558ecbc6..ed5ade0d23bf3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx @@ -198,9 +198,7 @@ export class IndexPrivilegeForm extends Component { id="xpack.security.management.editRoles.indexPrivilegeForm.grantedFieldsFormRowHelpText" defaultMessage="If no fields are granted, then users assigned to this role will not be able to see any data for this index." /> - ) : ( - undefined - ) + ) : undefined } > diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx index 1157640ca57a7..e4a2bbd260deb 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx @@ -147,14 +147,14 @@ export class IndexPrivileges extends Component { return; } - const patterns = privileges.map(index => index.names.join(',')); + const patterns = privileges.map((index) => index.names.join(',')); const cachedPatterns = Object.keys(this.state.availableFields); const patternsToFetch = _.difference(patterns, cachedPatterns); const fetchRequests = patternsToFetch.map(this.loadFieldsForPattern); - Promise.all(fetchRequests).then(response => { + Promise.all(fetchRequests).then((response) => { this.setState({ availableFields: { ...this.state.availableFields, diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts index 440ed78f944ba..9df50b198bde0 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts @@ -19,7 +19,7 @@ import { SubFeatureForm } from '../sub_feature_form'; export function getDisplayedFeaturePrivileges(wrapper: ReactWrapper) { const allExpanderButtons = findTestSubject(wrapper, 'expandFeaturePrivilegeRow'); - allExpanderButtons.forEach(button => button.simulate('click')); + allExpanderButtons.forEach((button) => button.simulate('click')); // each expanded row renders its own `EuiTableRow`, so there are 2 rows // for each feature: one for the primary feature privilege, and one for the sub privilege form diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx index 5d7b13acf79da..10aa59083dff6 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx @@ -41,7 +41,7 @@ export class ChangeAllPrivilegesControl extends Component { ); - const items = this.props.privileges.map(privilege => { + const items = this.props.privileges.map((privilege) => { return ( { }; describe('FeatureTable', () => { - [true, false].forEach(canCustomizeSubFeaturePrivileges => { + [true, false].forEach((canCustomizeSubFeaturePrivileges) => { describe(`with sub feature privileges ${ canCustomizeSubFeaturePrivileges ? 'allowed' : 'disallowed' }`, () => { @@ -312,7 +312,7 @@ describe('FeatureTable', () => { canCustomizeSubFeaturePrivileges: true, }); - kibanaFeatures.forEach(feature => { + kibanaFeatures.forEach((feature) => { const rowExpander = findTestSubject(wrapper, `expandFeaturePrivilegeRow-${feature.id}`); if (!feature.subFeatures || feature.subFeatures.length === 0) { expect(rowExpander).toHaveLength(0); @@ -345,9 +345,7 @@ describe('FeatureTable', () => { expect(wrapper.find(FeatureTableExpandedRow)).toHaveLength(0); - findTestSubject(wrapper, 'expandFeaturePrivilegeRow') - .first() - .simulate('click'); + findTestSubject(wrapper, 'expandFeaturePrivilegeRow').first().simulate('click'); expect(wrapper.find(FeatureTableExpandedRow)).toHaveLength(1); }); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx index 4610da95e9649..0776f2af2ddd7 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx @@ -78,7 +78,7 @@ export class FeatureTable extends Component { return 0; }) - .map(feature => { + .map((feature) => { return { featureId: feature.id, feature, @@ -98,7 +98,7 @@ export class FeatureTable extends Component { ...acc, [featureId]: ( f.id === featureId)!} + feature={featurePrivileges.find((f) => f.id === featureId)!} privilegeIndex={this.props.privilegeIndex} onChange={this.props.onChange} privilegeCalculator={this.props.privilegeCalculator} @@ -208,7 +208,7 @@ export class FeatureTable extends Component { this.props.privilegeIndex ); - const options = primaryFeaturePrivileges.map(privilege => { + const options = primaryFeaturePrivileges.map((privilege) => { return { id: `${feature.id}_${privilege.id}`, label: privilege.name, @@ -268,7 +268,7 @@ export class FeatureTable extends Component { private toggleExpandedFeature = (featureId: string) => { if (this.state.expandedFeatures.includes(featureId)) { this.setState({ - expandedFeatures: this.state.expandedFeatures.filter(ef => ef !== featureId), + expandedFeatures: this.state.expandedFeatures.filter((ef) => ef !== featureId), }); } else { this.setState({ diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx index fb302c2269485..ca73c4d183f23 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx @@ -31,13 +31,13 @@ export const FeatureTableExpandedRow = ({ const [isCustomizing, setIsCustomizing] = useState(() => { return feature .getMinimalFeaturePrivileges() - .some(p => selectedFeaturePrivileges.includes(p.id)); + .some((p) => selectedFeaturePrivileges.includes(p.id)); }); useEffect(() => { const hasMinimalFeaturePrivilegeSelected = feature .getMinimalFeaturePrivileges() - .some(p => selectedFeaturePrivileges.includes(p.id)); + .some((p) => selectedFeaturePrivileges.includes(p.id)); if (!hasMinimalFeaturePrivilegeSelected && isCustomizing) { setIsCustomizing(false); @@ -75,7 +75,7 @@ export const FeatureTableExpandedRow = ({ } /> - {feature.getSubFeatures().map(subFeature => { + {feature.getSubFeatures().map((subFeature) => { return ( onChange(feature.id, updatedPrivileges)} + onChange={(updatedPrivileges) => onChange(feature.id, updatedPrivileges)} selectedFeaturePrivileges={selectedFeaturePrivileges} disabled={disabled || !isCustomizing} /> diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx index ba7eff601f4c1..ced90e24b9c72 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx @@ -27,7 +27,7 @@ const createRole = (kibana: Role['kibana'] = []): Role => { }; const featureId = 'with_sub_features'; -const subFeature = kibanaFeatures.find(kf => kf.id === featureId)!.subFeatures[0]; +const subFeature = kibanaFeatures.find((kf) => kf.id === featureId)!.subFeatures[0]; const securedSubFeature = new SecuredSubFeature(subFeature.toRaw()); describe('SubFeatureForm', () => { @@ -57,8 +57,8 @@ describe('SubFeatureForm', () => { const checkboxes = wrapper.find(EuiCheckbox); const buttonGroups = wrapper.find(EuiButtonGroup); - expect(checkboxes.everyWhere(checkbox => checkbox.props().disabled === true)).toBe(true); - expect(buttonGroups.everyWhere(checkbox => checkbox.props().isDisabled === true)).toBe(true); + expect(checkboxes.everyWhere((checkbox) => checkbox.props().disabled === true)).toBe(true); + expect(buttonGroups.everyWhere((checkbox) => checkbox.props().isDisabled === true)).toBe(true); }); it('fires onChange when an independent privilege is selected', () => { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx index d4b6721ddad05..5432a50c1f0df 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx @@ -64,12 +64,14 @@ export const SubFeatureForm = (props: Props) => { id={`${props.featureId}_${privilege.id}`} label={privilege.name} data-test-subj="independentSubFeaturePrivilegeControl" - onChange={e => { + onChange={(e) => { const { checked } = e.target; if (checked) { props.onChange([...props.selectedFeaturePrivileges, privilege.id]); } else { - props.onChange(props.selectedFeaturePrivileges.filter(sp => sp !== privilege.id)); + props.onChange( + props.selectedFeaturePrivileges.filter((sp) => sp !== privilege.id) + ); } }} checked={isGranted} @@ -116,10 +118,10 @@ export const SubFeatureForm = (props: Props) => { options={options} idSelected={firstSelectedPrivilege?.id ?? NO_PRIVILEGE_VALUE} isDisabled={props.disabled} - onChange={selectedPrivilegeId => { + onChange={(selectedPrivilegeId) => { // Deselect all privileges which belong to this mutually-exclusive group const privilegesWithoutGroupEntries = props.selectedFeaturePrivileges.filter( - sp => !privilegeGroup.privileges.some(privilege => privilege.id === sp) + (sp) => !privilegeGroup.privileges.some((privilege) => privilege.id === sp) ); // fire on-change with the newly selected privilege if (selectedPrivilegeId === NO_PRIVILEGE_VALUE) { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx index 316818e4deed3..155e41baeba1e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx @@ -41,12 +41,7 @@ describe('FeatureTableCell', () => { ); expect(wrapper.text()).toMatchInlineSnapshot(`"Test Feature "`); - expect( - wrapper - .find(EuiIcon) - .first() - .props() - ).toMatchObject({ + expect(wrapper.find(EuiIcon).first().props()).toMatchObject({ type: feature.icon, }); expect(wrapper.find(EuiIconTip).props().content).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts index edf2af918fd04..53bebf6f5bb93 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts @@ -515,10 +515,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( @@ -543,10 +543,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( @@ -573,10 +573,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts index 8cff37f4bd4b0..87aabcb6fbf63 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts @@ -27,7 +27,7 @@ export class PrivilegeFormCalculator { const entry = this.role.kibana[privilegeIndex]; const basePrivileges = this.kibanaPrivileges.getBasePrivileges(entry); - return basePrivileges.find(bp => entry.base.includes(bp.id)); + return basePrivileges.find((bp) => entry.base.includes(bp.id)); } /** @@ -67,7 +67,7 @@ export class PrivilegeFormCalculator { this.role.kibana[privilegeIndex], ]); - return feature.getSubFeaturePrivileges().some(sfp => { + return feature.getSubFeaturePrivileges().some((sfp) => { const isGranted = formPrivileges.grantsPrivilege(sfp); const isGrantedByDisplayedPrimary = displayedPrimary?.grantsPrivilege(sfp) ?? isGranted; @@ -90,7 +90,7 @@ export class PrivilegeFormCalculator { return feature .getPrimaryFeaturePrivileges({ includeMinimalFeaturePrivileges: true }) - .find(fp => { + .find((fp) => { return selectedFeaturePrivileges.includes(fp.id) || basePrivilege?.grantsPrivilege(fp); }); } @@ -112,7 +112,7 @@ export class PrivilegeFormCalculator { const feature = this.kibanaPrivileges.getSecuredFeature(featureId); const subFeaturePrivilege = feature .getSubFeaturePrivileges() - .find(ap => ap.id === privilegeId)!; + .find((ap) => ap.id === privilegeId)!; const assignedPrivileges = this.kibanaPrivileges.createCollectionFromRoleKibanaPrivileges([ kibanaPrivilege, @@ -138,7 +138,7 @@ export class PrivilegeFormCalculator { kibanaPrivilege, ]); - return subFeatureGroup.privileges.find(p => { + return subFeatureGroup.privileges.find((p) => { return assignedPrivileges.grantsPrivilege(p); }); } @@ -155,7 +155,7 @@ export class PrivilegeFormCalculator { return feature .getPrimaryFeaturePrivileges({ includeMinimalFeaturePrivileges: true }) - .some(apfp => selectedFeaturePrivileges.includes(apfp.id)); + .some((apfp) => selectedFeaturePrivileges.includes(apfp.id)); } /** @@ -184,8 +184,8 @@ export class PrivilegeFormCalculator { const startingPrivileges = feature .getSubFeaturePrivileges() - .filter(ap => primary.grantsPrivilege(ap)) - .map(p => p.id); + .filter((ap) => primary.grantsPrivilege(ap)) + .map((p) => p.id); nextPrivileges.push(primary.getMinimalPrivilegeId(), ...startingPrivileges); } else { @@ -216,14 +216,14 @@ export class PrivilegeFormCalculator { const hasAssignedBasePrivileges = this.kibanaPrivileges .getBasePrivileges(entry) - .some(base => entry.base.includes(base.id)); + .some((base) => entry.base.includes(base.id)); const featuresWithDirectlyAssignedPrivileges = this.kibanaPrivileges .getSecuredFeatures() - .filter(feature => + .filter((feature) => feature .getAllPrivileges() - .some(privilege => entry.feature[feature.id]?.includes(privilege.id)) + .some((privilege) => entry.feature[feature.id]?.includes(privilege.id)) ); const hasSupersededBasePrivileges = @@ -231,15 +231,15 @@ export class PrivilegeFormCalculator { this.kibanaPrivileges .getBasePrivileges(entry) .some( - privilege => + (privilege) => globalPrivileges.grantsPrivilege(privilege) && !formPrivileges.grantsPrivilege(privilege) ); - const hasSupersededFeaturePrivileges = featuresWithDirectlyAssignedPrivileges.some(feature => + const hasSupersededFeaturePrivileges = featuresWithDirectlyAssignedPrivileges.some((feature) => feature .getAllPrivileges() - .some(fp => globalPrivileges.grantsPrivilege(fp) && !formPrivileges.grantsPrivilege(fp)) + .some((fp) => globalPrivileges.grantsPrivilege(fp) && !formPrivileges.grantsPrivilege(fp)) ); return hasSupersededBasePrivileges || hasSupersededFeaturePrivileges; @@ -270,12 +270,12 @@ export class PrivilegeFormCalculator { const selectedFeaturePrivileges = this.getSelectedFeaturePrivileges(featureId, privilegeIndex); - return feature.getPrimaryFeaturePrivileges().find(fp => { + return feature.getPrimaryFeaturePrivileges().find((fp) => { const correspondingMinimalPrivilegeId = fp.getMinimalPrivilegeId(); const correspendingMinimalPrivilege = feature .getMinimalFeaturePrivileges() - .find(mp => mp.id === correspondingMinimalPrivilegeId)!; + .find((mp) => mp.id === correspondingMinimalPrivilegeId)!; // There are two cases where the minimal privileges aren't available: // 1. The feature has no registered sub-features @@ -298,6 +298,6 @@ export class PrivilegeFormCalculator { } private locateGlobalPrivilege(role: Role) { - return role.kibana.find(entry => isGlobalPrivilegeDefinition(entry)); + return role.kibana.find((entry) => isGlobalPrivilegeDefinition(entry)); } } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts index 63b38b6967575..b920e7b696375 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts @@ -32,7 +32,7 @@ export function getDisplayedFeaturePrivileges( role: Role ): DisplayedFeaturePrivileges { const allExpanderButtons = findTestSubject(wrapper, 'expandPrivilegeSummaryRow'); - allExpanderButtons.forEach(button => button.simulate('click')); + allExpanderButtons.forEach((button) => button.simulate('click')); // each expanded row renders its own `EuiTableRow`, so there are 2 rows // for each feature: one for the primary feature privilege, and one for the sub privilege form @@ -81,7 +81,7 @@ function getDisplayedSubFeaturePrivileges( displayedFeatures[feature.id] = displayedFeatures[feature.id] ?? {}; - subFeatureEntries.forEach(subFeatureEntry => { + subFeatureEntries.forEach((subFeatureEntry) => { const subFeatureName = findTestSubject(subFeatureEntry, 'subFeatureName').text(); const entryElements = findTestSubject(subFeatureEntry as ReactWrapper, 'entry', '|='); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts index 27ed8c443045a..5ad0f6752b1cd 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts @@ -32,7 +32,7 @@ export class PrivilegeSummaryCalculator { const effectiveSubPrivileges = feature .getSubFeaturePrivileges() - .filter(ap => assignedPrivileges.grantsPrivilege(ap)); + .filter((ap) => assignedPrivileges.grantsPrivilege(ap)); const hasCustomizedSubFeaturePrivileges = this.hasCustomizedSubFeaturePrivileges( feature, @@ -45,7 +45,7 @@ export class PrivilegeSummaryCalculator { [feature.id]: { primary: displayedPrimaryFeaturePrivilege, hasCustomizedSubFeaturePrivileges, - subFeature: effectiveSubPrivileges.map(p => p.id), + subFeature: effectiveSubPrivileges.map((p) => p.id), }, }; }, {} as EffectiveFeaturePrivileges); @@ -58,7 +58,7 @@ export class PrivilegeSummaryCalculator { ) { const formPrivileges = this.collectAssignedPrivileges(entry); - return feature.getSubFeaturePrivileges().some(sfp => { + return feature.getSubFeaturePrivileges().some((sfp) => { const isGranted = formPrivileges.grantsPrivilege(sfp); const isGrantedByDisplayedPrimary = displayedPrimaryFeaturePrivilege?.grantsPrivilege(sfp) ?? isGranted; @@ -77,11 +77,11 @@ export class PrivilegeSummaryCalculator { const hasMinimalPrivileges = feature.subFeatures.length > 0; - const effectivePrivilege = primaryFeaturePrivileges.find(pfp => { + const effectivePrivilege = primaryFeaturePrivileges.find((pfp) => { const isPrimaryGranted = assignedPrivileges.grantsPrivilege(pfp); if (!isPrimaryGranted && hasMinimalPrivileges) { const correspondingMinimal = minimalPrimaryFeaturePrivileges.find( - mpfp => mpfp.id === pfp.getMinimalPrivilegeId() + (mpfp) => mpfp.id === pfp.getMinimalPrivilegeId() )!; return assignedPrivileges.grantsPrivilege(correspondingMinimal); @@ -104,6 +104,6 @@ export class PrivilegeSummaryCalculator { } private locateGlobalPrivilege(role: Role) { - return role.kibana.find(entry => isGlobalPrivilegeDefinition(entry)); + return role.kibana.find((entry) => isGlobalPrivilegeDefinition(entry)); } } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx index 3283f7a58a27c..d7483e840ec7e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx @@ -18,7 +18,7 @@ interface Props { export const PrivilegeSummaryExpandedRow = (props: Props) => { return ( - {props.feature.getSubFeatures().map(subFeature => { + {props.feature.getSubFeatures().map((subFeature) => { return ( @@ -107,7 +107,7 @@ export const PrivilegeSummaryExpandedRow = (props: Props) => { privilegeGroup: SubFeaturePrivilegeGroup, index: number ) { - const firstSelectedPrivilege = privilegeGroup.privileges.find(p => + const firstSelectedPrivilege = privilegeGroup.privileges.find((p) => effectiveSubFeaturePrivileges.includes(p.id) )?.name; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx index 0498f099b536b..502868a509f91 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx @@ -83,7 +83,7 @@ const expectNoPrivileges = (displayedPrivileges: any, expectSubFeatures: boolean }; describe('PrivilegeSummaryTable', () => { - [true, false].forEach(allowSubFeaturePrivileges => { + [true, false].forEach((allowSubFeaturePrivileges) => { describe(`when sub feature privileges are ${ allowSubFeaturePrivileges ? 'allowed' : 'disallowed' }`, () => { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx index e04ca36b6d193..4b5169de3dfc3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx @@ -43,7 +43,7 @@ export const PrivilegeSummaryTable = (props: Props) => { const toggleExpandedFeature = (featureId: string) => { if (expandedFeatures.includes(featureId)) { - setExpandedFeatures(expandedFeatures.filter(ef => ef !== featureId)); + setExpandedFeatures(expandedFeatures.filter((ef) => ef !== featureId)); } else { setExpandedFeatures([...expandedFeatures, featureId]); } @@ -88,7 +88,7 @@ export const PrivilegeSummaryTable = (props: Props) => { } return 0; }); - const privilegeColumns = rawKibanaPrivileges.map(entry => { + const privilegeColumns = rawKibanaPrivileges.map((entry) => { const key = getColumnKey(entry); return { name: , @@ -140,7 +140,7 @@ export const PrivilegeSummaryTable = (props: Props) => { }; }, {} as Record); - const items = props.kibanaPrivileges.getSecuredFeatures().map(feature => { + const items = props.kibanaPrivileges.getSecuredFeatures().map((feature) => { return { feature, featureId: feature.id, @@ -153,7 +153,7 @@ export const PrivilegeSummaryTable = (props: Props) => { columns={columns} items={items} itemId="featureId" - rowProps={record => { + rowProps={(record) => { return { 'data-test-subj': `summaryTableRow-${record.featureId}`, }; @@ -164,7 +164,7 @@ export const PrivilegeSummaryTable = (props: Props) => { [featureId]: ( p[featureId])} + effectiveFeaturePrivileges={Object.values(privileges).map((p) => p[featureId])} /> ), }; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx index 8ed9bb449b595..24ac0022b12af 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx @@ -20,9 +20,9 @@ const SPACES_DISPLAY_COUNT = 4; export const SpaceColumnHeader = (props: Props) => { const isGlobal = isGlobalPrivilegeDefinition(props.entry); - const entrySpaces = props.entry.spaces.map(spaceId => { + const entrySpaces = props.entry.spaces.map((spaceId) => { return ( - props.spaces.find(s => s.id === spaceId) ?? { + props.spaces.find((s) => s.id === spaceId) ?? { id: spaceId, name: spaceId, disabledFeatures: [], @@ -31,7 +31,7 @@ export const SpaceColumnHeader = (props: Props) => { }); return (
    - {entrySpaces.slice(0, SPACES_DISPLAY_COUNT).map(space => { + {entrySpaces.slice(0, SPACES_DISPLAY_COUNT).map((space) => { return ( {' '} @@ -43,7 +43,7 @@ export const SpaceColumnHeader = (props: Props) => { />
    s.id !== '*')} + spaces={props.spaces.filter((s) => s.id !== '*')} buttonText={i18n.translate( 'xpack.security.management.editRole.spacePrivilegeMatrix.showAllSpacesLink', { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx index bda0227372c09..493ae290cac5e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx @@ -31,7 +31,7 @@ export class PrivilegeSelector extends Component { } options.push( - ...availablePrivileges.map(p => ({ + ...availablePrivileges.map((p) => ({ value: p, text: p, })) diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx index d68d43e8089c7..34b4db89623bb 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx @@ -83,7 +83,7 @@ export class SimplePrivilegeSection extends Component { {reservedPrivileges.length > 0 ? ( ({ label: rp }))} + selectedOptions={reservedPrivileges.map((rp) => ({ label: rp }))} isDisabled /> ) : ( @@ -215,7 +215,7 @@ export class SimplePrivilegeSection extends Component { } onChange={this.onFeaturePrivilegeChange} onChangeAll={this.onChangeAllFeaturePrivileges} - privilegeIndex={this.props.role.kibana.findIndex(k => + privilegeIndex={this.props.role.kibana.findIndex((k) => isGlobalPrivilegeDefinition(k) )} canCustomizeSubFeaturePrivileges={this.props.canCustomizeSubFeaturePrivileges} @@ -248,7 +248,7 @@ export class SimplePrivilegeSection extends Component { if (privilege === NO_PRIVILEGE_VALUE) { // Remove global entry if no privilege value - role.kibana = role.kibana.filter(entry => !isGlobalPrivilegeDefinition(entry)); + role.kibana = role.kibana.filter((entry) => !isGlobalPrivilegeDefinition(entry)); } else if (privilege === CUSTOM_PRIVILEGE_VALUE) { // Remove base privilege if customizing feature privileges form.base = []; @@ -280,7 +280,7 @@ export class SimplePrivilegeSection extends Component { const form = this.locateGlobalPrivilege(role) || this.createGlobalPrivilegeEntry(role); if (privileges.length > 0) { - this.props.kibanaPrivileges.getSecuredFeatures().forEach(feature => { + this.props.kibanaPrivileges.getSecuredFeatures().forEach((feature) => { form.feature[feature.id] = [...privileges]; }); } else { @@ -292,7 +292,7 @@ export class SimplePrivilegeSection extends Component { private maybeRenderSpacePrivilegeWarning = () => { const kibanaPrivileges = this.props.role.kibana; const hasSpacePrivileges = kibanaPrivileges.some( - privilege => !isGlobalPrivilegeDefinition(privilege) + (privilege) => !isGlobalPrivilegeDefinition(privilege) ); if (hasSpacePrivileges) { @@ -306,12 +306,12 @@ export class SimplePrivilegeSection extends Component { }; private locateGlobalPrivilegeIndex = (role: Role) => { - return role.kibana.findIndex(privileges => isGlobalPrivilegeDefinition(privileges)); + return role.kibana.findIndex((privileges) => isGlobalPrivilegeDefinition(privileges)); }; private locateGlobalPrivilege = (role: Role) => { const spacePrivileges = role.kibana; - return spacePrivileges.find(privileges => isGlobalPrivilegeDefinition(privileges)); + return spacePrivileges.find((privileges) => isGlobalPrivilegeDefinition(privileges)); }; private createGlobalPrivilegeEntry(role: Role): RoleKibanaPrivilege { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx index 93f1d9bba460d..7b5d8d8c1ed27 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx @@ -40,7 +40,7 @@ function getDisplayValue(privilege: string | string[] | undefined) { if (isPrivilegeMissing) { displayValue = ; } else { - displayValue = privileges.map(p => _.capitalize(p)).join(', '); + displayValue = privileges.map((p) => _.capitalize(p)).join(', '); } return displayValue; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx index 968730181fe10..32eed6c878016 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx @@ -218,10 +218,7 @@ describe('PrivilegeSpaceForm', () => { /> ); - wrapper - .find(SpaceSelector) - .props() - .onChange(['*']); + wrapper.find(SpaceSelector).props().onChange(['*']); wrapper.update(); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx index 4e9e02bb531f1..c457401196ba1 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx @@ -452,8 +452,8 @@ export class PrivilegeSpaceForm extends Component { // remove any spaces that no longer exist if (!this.isDefiningGlobalPrivilege()) { - form.spaces = form.spaces.filter(spaceId => - this.props.spaces.find(space => space.id === spaceId) + form.spaces = form.spaces.filter((spaceId) => + this.props.spaces.find((space) => space.id === spaceId) ); } @@ -532,10 +532,10 @@ export class PrivilegeSpaceForm extends Component { if (privileges.length === 0) { entry.feature = {}; } else { - this.props.kibanaPrivileges.getSecuredFeatures().forEach(feature => { + this.props.kibanaPrivileges.getSecuredFeatures().forEach((feature) => { const nextFeaturePrivilege = feature .getPrimaryFeaturePrivileges() - .find(pfp => privileges.includes(pfp.id)); + .find((pfp) => privileges.includes(pfp.id)); if (nextFeaturePrivilege) { entry.feature[feature.id] = [nextFeaturePrivilege.id]; } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx index b1c7cb4b631e6..5530d9964f8cd 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx @@ -176,7 +176,7 @@ const getTableFromComponent = ( return [ ...acc, { - spaces: spacesBadge.map(badge => badge.text().trim()), + spaces: spacesBadge.map((badge) => badge.text().trim()), privileges: { summary: privilegesDisplay.text().trim(), overridden: diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx index 30a275876fdc7..585c07c2e834f 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx @@ -78,8 +78,8 @@ export class PrivilegeSpaceTable extends Component { const rows: TableRow[] = spacePrivileges.map((spacePrivs, privilegeIndex) => { const spaces = spacePrivs.spaces.map( - spaceId => - displaySpaces.find(space => space.id === spaceId) || { + (spaceId) => + displaySpaces.find((space) => space.id === spaceId) || { id: spaceId, name: spaceId, disabledFeatures: [], @@ -122,7 +122,7 @@ export class PrivilegeSpaceTable extends Component { if (record.isGlobal) { button = ( s.id !== '*')} + spaces={this.props.displaySpaces.filter((s) => s.id !== '*')} buttonText={i18n.translate( 'xpack.security.management.editRole.spacePrivilegeTable.showAllSpacesLink', { @@ -238,7 +238,7 @@ export class PrivilegeSpaceTable extends Component { 'xpack.security.management.editRole.spacePrivilegeTable.editPrivilegesLabel', { defaultMessage: `Edit privileges for the following spaces: {spaceNames}.`, - values: { spaceNames: record.spaces.map(s => s.name).join(', ') }, + values: { spaceNames: record.spaces.map((s) => s.name).join(', ') }, } )} color={'primary'} @@ -256,7 +256,7 @@ export class PrivilegeSpaceTable extends Component { 'xpack.security.management.editRole.spacePrivilegeTable.deletePrivilegesLabel', { defaultMessage: `Delete privileges for the following spaces: {spaceNames}.`, - values: { spaceNames: record.spaces.map(s => s.name).join(', ') }, + values: { spaceNames: record.spaces.map((s) => s.name).join(', ') }, } )} color={'danger'} @@ -296,7 +296,7 @@ export class PrivilegeSpaceTable extends Component { private toggleExpandSpacesGroup = (privilegeIndex: number) => { if (this.state.expandedSpacesGroups.includes(privilegeIndex)) { this.setState({ - expandedSpacesGroups: this.state.expandedSpacesGroups.filter(i => i !== privilegeIndex), + expandedSpacesGroups: this.state.expandedSpacesGroups.filter((i) => i !== privilegeIndex), }); } else { this.setState({ @@ -312,7 +312,9 @@ export class PrivilegeSpaceTable extends Component { this.props.onChange(roleCopy); this.setState({ - expandedSpacesGroups: this.state.expandedSpacesGroups.filter(i => i !== item.privilegeIndex), + expandedSpacesGroups: this.state.expandedSpacesGroups.filter( + (i) => i !== item.privilegeIndex + ), }); }; } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx index 86b09e5332792..734f7b1826723 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx @@ -243,7 +243,7 @@ export class SpaceAwarePrivilegeSection extends Component { ); return this.getDisplaySpaces().filter( - displaySpace => !spacesToExclude.includes(displaySpace.id) + (displaySpace) => !spacesToExclude.includes(displaySpace.id) ); }; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx index 70790f785ad58..4344cd4b0784e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx @@ -26,7 +26,7 @@ const spaceToOption = (space?: Space, currentSelection?: 'global' | 'spaces') => }; const spaceIdToOption = (spaces: Space[]) => (s: string) => - spaceToOption(spaces.find(space => space.id === s)); + spaceToOption(spaces.find((space) => space.id === s)); interface Props { spaces: Space[]; @@ -65,11 +65,11 @@ export class SpaceSelector extends Component { } private onChange = (selectedSpaces: EuiComboBoxOptionOption[]) => { - this.props.onChange(selectedSpaces.map(s => (s.id as string).split('spaceOption_')[1])); + this.props.onChange(selectedSpaces.map((s) => (s.id as string).split('spaceOption_')[1])); }; private getOptions = () => { - const options = this.props.spaces.map(space => + const options = this.props.spaces.map((space) => spaceToOption( space, this.props.selectedSpaceIds.includes('*') diff --git a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx index 20882864645d3..9c68a097a890e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx @@ -62,7 +62,7 @@ describe('SpacesPopoverList', () => { }); it('renders a search box when there are 8 or more spaces', () => { - const lotsOfSpaces = [1, 2, 3, 4, 5, 6, 7, 8].map(num => ({ + const lotsOfSpaces = [1, 2, 3, 4, 5, 6, 7, 8].map((num) => ({ id: `space-${num}`, name: `Space ${num}`, disabledFeatures: [], @@ -100,10 +100,7 @@ describe('SpacesPopoverList', () => { expect(wrapper.find(EuiPopover).props().isOpen).toEqual(true); - wrapper - .find(EuiPopover) - .props() - .closePopover(); + wrapper.find(EuiPopover).props().closePopover(); wrapper.update(); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx index 63ee311f3155e..9c1a94d3d06f3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx @@ -104,7 +104,7 @@ export class SpacesPopoverList extends Component { let filteredSpaces = spaces; if (searchTerm) { - filteredSpaces = spaces.filter(space => { + filteredSpaces = spaces.filter((space) => { const { name, description = '' } = space; return ( name.toLowerCase().indexOf(searchTerm) >= 0 || diff --git a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts index e9be52557bd7d..868674aec6f86 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts @@ -62,7 +62,7 @@ describe('validateRoleName', () => { }); const charList = `!#%^&*()+=[]{}\|';:"/,<>?`.split(''); - charList.forEach(element => { + charList.forEach((element) => { test(`it cannot support the "${element}" character`, () => { const role = { name: `role-${element}`, diff --git a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts index 02d3061b82b96..89b16b1467776 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts @@ -85,7 +85,7 @@ export class RoleValidator { const areIndicesValid = role.elasticsearch.indices - .map(indexPriv => this.validateIndexPrivilege(indexPriv)) + .map((indexPriv) => this.validateIndexPrivilege(indexPriv)) .find((result: RoleValidationResult) => result.isInvalid) == null; if (areIndicesValid) { @@ -171,7 +171,7 @@ export class RoleValidator { const privileges = role.kibana || []; - const arePrivilegesValid = privileges.every(assignedPrivilege => { + const arePrivilegesValid = privileges.every((assignedPrivilege) => { return assignedPrivilege.base.length > 0 || Object.keys(assignedPrivilege.feature).length > 0; }); diff --git a/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts b/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts index 7c21a4b5c0ee6..f5c85d3d92be2 100644 --- a/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts +++ b/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts @@ -18,7 +18,7 @@ export class KibanaPrivilege { } private checkActions(knownActions: string[], candidateActions: string[]) { - const missing = candidateActions.filter(action => !knownActions.includes(action)); + const missing = candidateActions.filter((action) => !knownActions.includes(action)); const hasAllRequested = knownActions.length > 0 && candidateActions.length > 0 && missing.length === 0; diff --git a/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts b/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts index d8d75e90847e3..a1617f71a0df8 100644 --- a/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts +++ b/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts @@ -19,7 +19,7 @@ function toBasePrivilege(entry: [string, string[]]): [string, KibanaPrivilege] { function recordsToBasePrivilegeMap( record: Record ): ReadonlyMap { - return new Map(Object.entries(record).map(entry => toBasePrivilege(entry))); + return new Map(Object.entries(record).map((entry) => toBasePrivilege(entry))); } export class KibanaPrivileges { @@ -33,7 +33,7 @@ export class KibanaPrivileges { this.global = recordsToBasePrivilegeMap(rawKibanaPrivileges.global); this.spaces = recordsToBasePrivilegeMap(rawKibanaPrivileges.space); this.feature = new Map( - features.map(feature => { + features.map((feature) => { const rawPrivs = rawKibanaPrivileges.features[feature.id]; return [feature.id, new SecuredFeature(feature.toRaw(), rawPrivs)]; }) @@ -60,7 +60,7 @@ export class KibanaPrivileges { assignedPrivileges.includes(privilege.id); const privileges: KibanaPrivilege[] = roleKibanaPrivileges - .map(entry => { + .map((entry) => { const assignedBasePrivileges = this.getBasePrivileges(entry).filter( filterAssigned(entry.base) ); diff --git a/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts b/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts index cbbd22857666e..d023f18d39279 100644 --- a/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts +++ b/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts @@ -20,7 +20,7 @@ export class PrivilegeCollection { } private checkActions(knownActions: ReadonlySet, candidateActions: string[]) { - const missing = candidateActions.filter(action => !knownActions.has(action)); + const missing = candidateActions.filter((action) => !knownActions.has(action)); const hasAllRequested = knownActions.size > 0 && candidateActions.length > 0 && missing.length === 0; diff --git a/x-pack/plugins/security/public/management/roles/model/secured_feature.ts b/x-pack/plugins/security/public/management/roles/model/secured_feature.ts index 7fc466a70b984..284a85583c33c 100644 --- a/x-pack/plugins/security/public/management/roles/model/secured_feature.ts +++ b/x-pack/plugins/security/public/management/roles/model/secured_feature.ts @@ -34,7 +34,7 @@ export class SecuredFeature extends Feature { } this.securedSubFeatures = - this.config.subFeatures?.map(sf => new SecuredSubFeature(sf, actionMapping)) ?? []; + this.config.subFeatures?.map((sf) => new SecuredSubFeature(sf, actionMapping)) ?? []; this.subFeaturePrivileges = this.securedSubFeatures.reduce((acc, subFeature) => { return [...acc, ...subFeature.privilegeIterator()]; diff --git a/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts b/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts index 3d69e5e709bb0..f7bdd9ba520ad 100644 --- a/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts +++ b/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts @@ -24,7 +24,7 @@ export class SecuredSubFeature extends SubFeature { } public getPrivilegeGroups() { - return this.privilegeGroups.map(pg => new SubFeaturePrivilegeGroup(pg, this.actionMapping)); + return this.privilegeGroups.map((pg) => new SubFeaturePrivilegeGroup(pg, this.actionMapping)); } public *privilegeIterator({ @@ -34,8 +34,8 @@ export class SecuredSubFeature extends SubFeature { } = {}): IterableIterator { for (const group of this.privilegeGroups) { yield* group.privileges - .map(gp => new SubFeaturePrivilege(gp, this.actionMapping[gp.id])) - .filter(privilege => predicate(privilege, this)); + .map((gp) => new SubFeaturePrivilege(gp, this.actionMapping[gp.id])) + .filter((privilege) => predicate(privilege, this)); } } } diff --git a/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts b/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts index b437649236e27..17d899874d8ff 100644 --- a/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts +++ b/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts @@ -19,7 +19,7 @@ export class SubFeaturePrivilegeGroup { public get privileges() { return this.config.privileges.map( - p => new SubFeaturePrivilege(p, this.actionMapping[p.id] || []) + (p) => new SubFeaturePrivilege(p, this.actionMapping[p.id] || []) ); } } diff --git a/x-pack/plugins/security/public/management/roles/roles_api_client.ts b/x-pack/plugins/security/public/management/roles/roles_api_client.ts index d7e98e03a965b..50c490d2924ba 100644 --- a/x-pack/plugins/security/public/management/roles/roles_api_client.ts +++ b/x-pack/plugins/security/public/management/roles/roles_api_client.ts @@ -34,18 +34,18 @@ export class RolesAPIClient { const isPlaceholderPrivilege = (indexPrivilege: RoleIndexPrivilege) => indexPrivilege.names.length === 0; role.elasticsearch.indices = role.elasticsearch.indices.filter( - indexPrivilege => !isPlaceholderPrivilege(indexPrivilege) + (indexPrivilege) => !isPlaceholderPrivilege(indexPrivilege) ); // Remove any placeholder query entries - role.elasticsearch.indices.forEach(index => index.query || delete index.query); + role.elasticsearch.indices.forEach((index) => index.query || delete index.query); // If spaces are disabled, then do not persist any space privileges if (!spacesEnabled) { role.kibana = role.kibana.filter(isGlobalPrivilegeDefinition); } - role.kibana.forEach(kibanaPrivilege => { + role.kibana.forEach((kibanaPrivilege) => { // If a base privilege is defined, then do not persist feature privileges if (kibanaPrivilege.base.length > 0) { kibanaPrivilege.feature = {}; diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx index 37eed3357241d..d1b266d2a68fe 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx @@ -71,7 +71,7 @@ export class ConfirmDelete extends Component { />

      - {rolesToDelete.map(roleName => ( + {rolesToDelete.map((roleName) => (
    • {roleName}
    • ))}
    @@ -129,7 +129,7 @@ export class ConfirmDelete extends Component { private deleteRoles = async () => { const { rolesToDelete, callback, rolesAPIClient, notifications } = this.props; const errors: string[] = []; - const deleteOperations = rolesToDelete.map(roleName => { + const deleteOperations = rolesToDelete.map((roleName) => { const deleteRoleTask = async () => { try { await rolesAPIClient.deleteRole(roleName); diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx index 410d5bc9f7643..e0a7d96d1cf72 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx @@ -73,7 +73,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -90,7 +90,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -107,7 +107,7 @@ describe('', () => { notifications={coreMock.createStart().notifications} /> ); - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(PermissionDenied).length > 0; }); expect(wrapper.find(PermissionDenied)).toMatchSnapshot(); @@ -122,7 +122,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -151,7 +151,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx index 04a74a1a9b99a..4f0d7ca8621a3 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx @@ -118,7 +118,7 @@ export class RolesGridPage extends Component { {this.state.showDeleteConfirmation ? ( role.name)} + rolesToDelete={this.state.selection.map((role) => role.name)} callback={this.handleDelete} notifications={this.props.notifications} rolesAPIClient={this.props.rolesAPIClient} @@ -259,7 +259,7 @@ export class RolesGridPage extends Component { }; private getVisibleRoles = (roles: Role[], filter: string, includeReservedRoles: boolean) => { - return roles.filter(role => { + return roles.filter((role) => { const normalized = `${role.name}`.toLowerCase(); const normalizedQuery = filter.toLowerCase(); return ( diff --git a/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx b/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx index 047cad7bead81..7a97794303558 100644 --- a/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx +++ b/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx @@ -267,7 +267,7 @@ export class ChangePasswordForm extends Component { this.validateConfirmPassword(true), ]; - const firstFailure = validation.find(result => result.isInvalid); + const firstFailure = validation.find((result) => result.isInvalid); if (firstFailure) { return firstFailure; } diff --git a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx index 9c5a8b0b75ead..e39a4acdaaff9 100644 --- a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx +++ b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx @@ -80,7 +80,7 @@ describe('ConfirmDeleteUsers', () => { const onCancel = jest.fn(); const apiClientMock = userAPIClientMock.create(); - apiClientMock.deleteUser.mockImplementation(user => { + apiClientMock.deleteUser.mockImplementation((user) => { if (user === 'foo') { return Promise.reject('something terrible happened'); } diff --git a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx index 53acbf42273e8..a6fbc6be945c9 100644 --- a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx +++ b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx @@ -58,7 +58,7 @@ export class ConfirmDeleteUsers extends Component { />

      - {usersToDelete.map(username => ( + {usersToDelete.map((username) => (
    • {username}
    • ))}
    @@ -79,7 +79,7 @@ export class ConfirmDeleteUsers extends Component { private deleteUsers = () => { const { usersToDelete, callback, userAPIClient, notifications } = this.props; const errors: string[] = []; - usersToDelete.forEach(async username => { + usersToDelete.forEach(async (username) => { try { await userAPIClient.deleteUser(username); notifications.toasts.addSuccess( diff --git a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx index 7172ff178eb6b..49da4c66a7630 100644 --- a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx +++ b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx @@ -382,8 +382,8 @@ export class EditUserPage extends Component { return null; } - const hasAnyDeprecatedRolesAssigned = selectedRoles.some(selected => { - const role = roles.find(r => r.name === selected); + const hasAnyDeprecatedRolesAssigned = selectedRoles.some((selected) => { + const role = roles.find((r) => r.name === selected); return role && isRoleDeprecated(role); }); @@ -394,9 +394,7 @@ export class EditUserPage extends Component { defaultMessage="This user is assigned a deprecated role. Please migrate to a supported role." />
    - ) : ( - undefined - ); + ) : undefined; return (
    diff --git a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx index f8882129772f7..5fd2b4ec85589 100644 --- a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx +++ b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx @@ -143,7 +143,7 @@ export class UsersGridPage extends Component { width: '30%', render: (rolenames: string[]) => { const roleLinks = rolenames.map((rolename, index) => { - const roleDefinition = roles?.find(role => role.name === rolename) ?? rolename; + const roleDefinition = roles?.find((role) => role.name === rolename) ?? rolename; return ; }); return
    {roleLinks}
    ; @@ -231,7 +231,7 @@ export class UsersGridPage extends Component { {showDeleteConfirmation ? ( user.username)} + usersToDelete={selection.map((user) => user.username)} callback={this.handleDelete} userAPIClient={this.props.userAPIClient} notifications={this.props.notifications} diff --git a/x-pack/plugins/security/public/nav_control/nav_control_component.tsx b/x-pack/plugins/security/public/nav_control/nav_control_component.tsx index eaa1d8dee0a11..3ddabb0dc55f8 100644 --- a/x-pack/plugins/security/public/nav_control/nav_control_component.tsx +++ b/x-pack/plugins/security/public/nav_control/nav_control_component.tsx @@ -41,7 +41,7 @@ export class SecurityNavControl extends Component { authenticatedUser: null, }; - props.user.then(authenticatedUser => { + props.user.then((authenticatedUser) => { this.setState({ authenticatedUser, }); diff --git a/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts b/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts index 66731cf19006d..acf62f3376b8b 100644 --- a/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts +++ b/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts @@ -15,7 +15,7 @@ import { mockAuthenticatedUser } from '../../common/model/authenticated_user.moc const validLicense = { isAvailable: true, - getFeature: feature => { + getFeature: (feature) => { expect(feature).toEqual('security'); return { diff --git a/x-pack/plugins/security/public/session/session_expired.test.ts b/x-pack/plugins/security/public/session/session_expired.test.ts index f5ad9cb464e3e..1ec2f772050f9 100644 --- a/x-pack/plugins/security/public/session/session_expired.test.ts +++ b/x-pack/plugins/security/public/session/session_expired.test.ts @@ -26,8 +26,8 @@ describe('#logout', () => { beforeEach(() => { window.history.pushState({}, '', CURRENT_URL); mockGetItem.mockReset(); - newUrlPromise = new Promise(resolve => { - jest.spyOn(window.location, 'assign').mockImplementation(url => { + newUrlPromise = new Promise((resolve) => { + jest.spyOn(window.location, 'assign').mockImplementation((url) => { resolve(url); }); }); diff --git a/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts b/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts index 427bdb04f9c61..40cbd00858b5f 100644 --- a/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts +++ b/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts @@ -13,7 +13,7 @@ import { createSessionTimeoutMock } from './session_timeout.mock'; const mockCurrentUrl = (url: string) => window.history.pushState({}, '', url); const setupHttp = (basePath: string) => { - const { http } = setup(injectedMetadata => { + const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue(basePath); }); return http; diff --git a/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts b/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts index fba2a2ec98146..78c82cbc3a9a6 100644 --- a/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts +++ b/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts @@ -12,7 +12,7 @@ import { UnauthorizedResponseHttpInterceptor } from './unauthorized_response_htt jest.mock('./session_expired'); const drainPromiseQueue = () => { - return new Promise(resolve => { + return new Promise((resolve) => { setImmediate(resolve); }); }; @@ -20,7 +20,7 @@ const drainPromiseQueue = () => { const mockCurrentUrl = (url: string) => window.history.pushState({}, '', url); const setupHttp = (basePath: string) => { - const { http } = setup(injectedMetadata => { + const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue(basePath); }); return http; @@ -34,7 +34,7 @@ afterEach(() => { it(`logs out 401 responses`, async () => { const http = setupHttp('/foo'); const sessionExpired = new SessionExpired(`${http.basePath}/logout`, tenant); - const logoutPromise = new Promise(resolve => { + const logoutPromise = new Promise((resolve) => { jest.spyOn(sessionExpired, 'logout').mockImplementation(() => resolve()); }); const interceptor = new UnauthorizedResponseHttpInterceptor(sessionExpired, http.anonymousPaths); diff --git a/x-pack/plugins/security/server/authentication/authenticator.ts b/x-pack/plugins/security/server/authentication/authenticator.ts index 58dea2b23e546..98342a8494e38 100644 --- a/x-pack/plugins/security/server/authentication/authenticator.ts +++ b/x-pack/plugins/security/server/authentication/authenticator.ts @@ -475,7 +475,7 @@ export class Authenticator { * @param providerType Type of the provider (`basic`, `saml`, `pki` etc.). */ isProviderTypeEnabled(providerType: string) { - return [...this.providers.values()].some(provider => provider.type === providerType); + return [...this.providers.values()].some((provider) => provider.type === providerType); } /** @@ -511,7 +511,7 @@ export class Authenticator { */ private setupHTTPAuthenticationProvider(options: AuthenticationProviderOptions) { const supportedSchemes = new Set( - this.options.config.authc.http.schemes.map(scheme => scheme.toLowerCase()) + this.options.config.authc.http.schemes.map((scheme) => scheme.toLowerCase()) ); // If `autoSchemesEnabled` is set we should allow schemes that other providers use to diff --git a/x-pack/plugins/security/server/authentication/providers/http.ts b/x-pack/plugins/security/server/authentication/providers/http.ts index 6b75ae2d48156..3e33a52cbbc6b 100644 --- a/x-pack/plugins/security/server/authentication/providers/http.ts +++ b/x-pack/plugins/security/server/authentication/providers/http.ts @@ -39,7 +39,7 @@ export class HTTPAuthenticationProvider extends BaseAuthenticationProvider { throw new Error('Supported schemes should be specified'); } this.supportedSchemes = new Set( - [...httpOptions.supportedSchemes].map(scheme => scheme.toLowerCase()) + [...httpOptions.supportedSchemes].map((scheme) => scheme.toLowerCase()) ); } diff --git a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts index 6eb47cfa83e32..ca80761ee140c 100644 --- a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts @@ -280,11 +280,11 @@ describe('KerberosAuthenticationProvider', () => { } describe('`login` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.login(request)); + defineCommonLoginAndAuthenticateTests((request) => provider.login(request)); }); describe('`authenticate` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.authenticate(request, null)); + defineCommonLoginAndAuthenticateTests((request) => provider.authenticate(request, null)); it('does not handle authentication via `authorization` header with non-negotiate scheme.', async () => { const request = httpServerMock.createKibanaRequest({ @@ -376,7 +376,7 @@ describe('KerberosAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/kerberos.ts b/x-pack/plugins/security/server/authentication/providers/kerberos.ts index c4bbe554a3da1..2540c21210bd5 100644 --- a/x-pack/plugins/security/server/authentication/providers/kerberos.ts +++ b/x-pack/plugins/security/server/authentication/providers/kerberos.ts @@ -339,7 +339,7 @@ export class KerberosAuthenticationProvider extends BaseAuthenticationProvider { private getNegotiateChallenge(error: ElasticsearchError) { const challenges = ([] as string[]).concat(error.output.headers[WWWAuthenticateHeaderName]); - const negotiateChallenge = challenges.find(challenge => + const negotiateChallenge = challenges.find((challenge) => challenge.toLowerCase().startsWith('negotiate') ); if (negotiateChallenge) { diff --git a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts index 14fe42aac7599..2d42d90ab60b8 100644 --- a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts @@ -464,7 +464,7 @@ describe('OIDCAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'expired-token', refreshToken: 'valid-refresh-token' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/pki.test.ts b/x-pack/plugins/security/server/authentication/providers/pki.test.ts index 638bb5732f3c0..28db64edd9e32 100644 --- a/x-pack/plugins/security/server/authentication/providers/pki.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/pki.test.ts @@ -241,11 +241,11 @@ describe('PKIAuthenticationProvider', () => { } describe('`login` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.login(request)); + defineCommonLoginAndAuthenticateTests((request) => provider.login(request)); }); describe('`authenticate` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.authenticate(request, null)); + defineCommonLoginAndAuthenticateTests((request) => provider.authenticate(request, null)); it('does not handle authentication via `authorization` header.', async () => { const request = httpServerMock.createKibanaRequest({ diff --git a/x-pack/plugins/security/server/authentication/providers/saml.test.ts b/x-pack/plugins/security/server/authentication/providers/saml.test.ts index ec50ac090f1e7..461ad3e38eca5 100644 --- a/x-pack/plugins/security/server/authentication/providers/saml.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/saml.test.ts @@ -835,7 +835,7 @@ describe('SAMLAuthenticationProvider', () => { realm: 'test-realm', }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${state.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/saml.ts b/x-pack/plugins/security/server/authentication/providers/saml.ts index 5c5ec49890901..3161144023c1f 100644 --- a/x-pack/plugins/security/server/authentication/providers/saml.ts +++ b/x-pack/plugins/security/server/authentication/providers/saml.ts @@ -177,8 +177,9 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider { this.logger.debug('Login has been successfully performed.'); } else { this.logger.debug( - `Failed to perform a login: ${authenticationResult.error && - authenticationResult.error.message}` + `Failed to perform a login: ${ + authenticationResult.error && authenticationResult.error.message + }` ); } diff --git a/x-pack/plugins/security/server/authentication/providers/token.test.ts b/x-pack/plugins/security/server/authentication/providers/token.test.ts index 7472adb30307c..92cea424e575d 100644 --- a/x-pack/plugins/security/server/authentication/providers/token.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/token.test.ts @@ -211,7 +211,7 @@ describe('TokenAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( @@ -386,7 +386,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authenticationError = new errors.AuthenticationException('Some error'); - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authorization/actions/ui.ts b/x-pack/plugins/security/server/authorization/actions/ui.ts index 3dae9a47b3827..fa5bea867e9cc 100644 --- a/x-pack/plugins/security/server/authorization/actions/ui.ts +++ b/x-pack/plugins/security/server/authorization/actions/ui.ts @@ -26,7 +26,7 @@ export class UIActions { if ( uiCapabilityParts.length === 0 || uiCapabilityParts.findIndex( - part => !part || !isString(part) || !uiCapabilitiesRegex.test(part) + (part) => !part || !isString(part) || !uiCapabilitiesRegex.test(part) ) >= 0 ) { throw new Error( diff --git a/x-pack/plugins/security/server/authorization/api_authorization.test.ts b/x-pack/plugins/security/server/authorization/api_authorization.test.ts index 409f998cfe8d2..183a36274142c 100644 --- a/x-pack/plugins/security/server/authorization/api_authorization.test.ts +++ b/x-pack/plugins/security/server/authorization/api_authorization.test.ts @@ -82,7 +82,7 @@ describe('initAPIAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: true }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); @@ -117,7 +117,7 @@ describe('initAPIAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: false }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); diff --git a/x-pack/plugins/security/server/authorization/api_authorization.ts b/x-pack/plugins/security/server/authorization/api_authorization.ts index 88b3f2c6f7155..3e3ea34618da9 100644 --- a/x-pack/plugins/security/server/authorization/api_authorization.ts +++ b/x-pack/plugins/security/server/authorization/api_authorization.ts @@ -20,14 +20,14 @@ export function initAPIAuthorization( const tags = request.route.options.tags; const tagPrefix = 'access:'; - const actionTags = tags.filter(tag => tag.startsWith(tagPrefix)); + const actionTags = tags.filter((tag) => tag.startsWith(tagPrefix)); // if there are no tags starting with "access:", just continue if (actionTags.length === 0) { return toolkit.next(); } - const apiActions = actionTags.map(tag => actions.api.get(tag.substring(tagPrefix.length))); + const apiActions = actionTags.map((tag) => actions.api.get(tag.substring(tagPrefix.length))); const checkPrivileges = checkPrivilegesDynamicallyWithRequest(request); const checkPrivilegesResponse = await checkPrivileges(apiActions); diff --git a/x-pack/plugins/security/server/authorization/app_authorization.test.ts b/x-pack/plugins/security/server/authorization/app_authorization.test.ts index 6d23333022302..1dc56161d6363 100644 --- a/x-pack/plugins/security/server/authorization/app_authorization.test.ts +++ b/x-pack/plugins/security/server/authorization/app_authorization.test.ts @@ -117,7 +117,7 @@ describe('initAppAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: true }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); @@ -157,7 +157,7 @@ describe('initAppAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: false }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); diff --git a/x-pack/plugins/security/server/authorization/app_authorization.ts b/x-pack/plugins/security/server/authorization/app_authorization.ts index 8516e8228ab5a..aead8cb07897c 100644 --- a/x-pack/plugins/security/server/authorization/app_authorization.ts +++ b/x-pack/plugins/security/server/authorization/app_authorization.ts @@ -20,7 +20,7 @@ class ProtectedApplications { this.applications = new Set( this.featuresService .getFeatures() - .map(feature => feature.app) + .map((feature) => feature.app) .flat() ); } diff --git a/x-pack/plugins/security/server/authorization/check_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_privileges.test.ts index a64c5d509ca11..65a3d1bf1650b 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.test.ts @@ -333,7 +333,7 @@ describe('#atSpaces', () => { applications: [ { application, - resources: options.spaceIds.map(spaceId => `space:${spaceId}`), + resources: options.spaceIds.map((spaceId) => `space:${spaceId}`), privileges: uniq([ mockActions.version, mockActions.login, diff --git a/x-pack/plugins/security/server/authorization/check_privileges.ts b/x-pack/plugins/security/server/authorization/check_privileges.ts index 177a49d6defe9..44e9438bd07f5 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.ts @@ -52,7 +52,7 @@ export function checkPrivilegesWithRequestFactory( applicationPrivilegesResponse: HasPrivilegesResponseApplication ) => { return Object.values(applicationPrivilegesResponse).some( - resource => !resource[actions.version] && resource[actions.login] + (resource) => !resource[actions.version] && resource[actions.login] ); }; @@ -121,7 +121,7 @@ export function checkPrivilegesWithRequestFactory( return await checkPrivilegesAtResources([spaceResource], privilegeOrPrivileges); }, async atSpaces(spaceIds: string[], privilegeOrPrivileges: string | string[]) { - const spaceResources = spaceIds.map(spaceId => + const spaceResources = spaceIds.map((spaceId) => ResourceSerializer.serializeSpaceResource(spaceId) ); return await checkPrivilegesAtResources(spaceResources, privilegeOrPrivileges); diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts index 43b3824500579..4ab00b511b48b 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts @@ -78,7 +78,7 @@ describe('#checkSavedObjectsPrivileges', () => { expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledTimes(1); expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledWith(request); expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledTimes(1); - const spaceIds = mockSpacesService!.namespaceToSpaceId.mock.results.map(x => x.value); + const spaceIds = mockSpacesService!.namespaceToSpaceId.mock.results.map((x) => x.value); expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledWith(spaceIds, actions); }); }); diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts index 43140143a1773..d9b070c72f946 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts @@ -37,7 +37,7 @@ export const checkSavedObjectsPrivilegesWithRequestFactory = ( } else if (!namespaceOrNamespaces.length) { throw new Error(`Can't check saved object privileges for 0 namespaces`); } - const spaceIds = namespaceOrNamespaces.map(x => spacesService.namespaceToSpaceId(x)); + const spaceIds = namespaceOrNamespaces.map((x) => spacesService.namespaceToSpaceId(x)); return await checkPrivilegesWithRequest(request).atSpaces(spaceIds, actions); } else if (spacesService) { const spaceId = spacesService.namespaceToSpaceId(namespaceOrNamespaces); diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts index ea97a1b3b590c..082484d5fa6b4 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts @@ -20,15 +20,15 @@ const mockRequest = httpServerMock.createKibanaRequest(); const createMockAuthz = (options: MockAuthzOptions) => { const mock = authorizationMock.create({ version: '1.0.0-zeta1' }); - mock.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mock.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { expect(request).toBe(mockRequest); - return jest.fn().mockImplementation(checkActions => { + return jest.fn().mockImplementation((checkActions) => { if ('rejectCheckPrivileges' in options) { throw options.rejectCheckPrivileges; } - const expected = options.resolveCheckPrivileges.privileges.map(x => x.privilege); + const expected = options.resolveCheckPrivileges.privileges.map((x) => x.privilege); expect(checkActions).toEqual(expected); return options.resolveCheckPrivileges; }); diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts index f0f1a42ad0bd5..72937c15756ac 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts @@ -19,8 +19,8 @@ export function disableUICapabilitiesFactory( authz: Authorization ) { const featureNavLinkIds = features - .map(feature => feature.navLinkId) - .filter(navLinkId => navLinkId != null); + .map((feature) => feature.navLinkId) + .filter((navLinkId) => navLinkId != null); const shouldDisableFeatureUICapability = ( featureId: keyof UICapabilities, @@ -60,7 +60,9 @@ export function disableUICapabilitiesFactory( return [authz.actions.ui.get(featureId, uiCapability)]; } if (isObject(value)) { - return Object.keys(value).map(item => authz.actions.ui.get(featureId, uiCapability, item)); + return Object.keys(value).map((item) => + authz.actions.ui.get(featureId, uiCapability, item) + ); } throw new Error(`Expected value type of boolean or object, but found ${value}`); } @@ -106,7 +108,7 @@ export function disableUICapabilitiesFactory( const action = authz.actions.ui.get(featureId, ...uiCapabilityParts); return checkPrivilegesResponse.privileges.some( - x => x.privilege === action && x.authorized === true + (x) => x.privilege === action && x.authorized === true ); }; diff --git a/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts b/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts index ecfe0d34fdbcb..b35bfe9b0a271 100644 --- a/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts +++ b/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts @@ -7,14 +7,14 @@ import { PrivilegeSerializer } from './privilege_serializer'; describe(`#isSerializedGlobalBasePrivilege`, () => { - ['all', 'read'].forEach(validValue => { + ['all', 'read'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedGlobalBasePrivilege(validValue)).toBe(true); }); }); ['space_all', 'space_read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach( - invalidValue => { + (invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedGlobalBasePrivilege(invalidValue)).toBe(false); }); @@ -23,13 +23,13 @@ describe(`#isSerializedGlobalBasePrivilege`, () => { }); describe(`#isSerializedSpaceBasePrivilege`, () => { - ['space_all', 'space_read'].forEach(validValue => { + ['space_all', 'space_read'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedSpaceBasePrivilege(validValue)).toBe(true); }); }); - ['all', 'read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach(invalid => { + ['all', 'read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach((invalid) => { test(`returns false for '${invalid}'`, () => { expect(PrivilegeSerializer.isSerializedSpaceBasePrivilege(invalid)).toBe(false); }); @@ -37,7 +37,7 @@ describe(`#isSerializedSpaceBasePrivilege`, () => { }); describe(`#isSerializedReservedPrivilege`, () => { - ['reserved_foo', 'reserved_bar'].forEach(validValue => { + ['reserved_foo', 'reserved_bar'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedReservedPrivilege(validValue)).toBe(true); }); @@ -52,7 +52,7 @@ describe(`#isSerializedReservedPrivilege`, () => { 'bar', 'feature_foo', 'feature_foo.privilege1', - ].forEach(invalidValue => { + ].forEach((invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedReservedPrivilege(invalidValue)).toBe(false); }); @@ -60,14 +60,14 @@ describe(`#isSerializedReservedPrivilege`, () => { }); describe(`#isSerializedFeaturePrivilege`, () => { - ['feature_foo.privilege1', 'feature_bar.privilege2'].forEach(validValue => { + ['feature_foo.privilege1', 'feature_bar.privilege2'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedFeaturePrivilege(validValue)).toBe(true); }); }); ['all', 'read', 'space_all', 'space_read', 'reserved_foo', 'reserved_bar'].forEach( - invalidValue => { + (invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedFeaturePrivilege(invalidValue)).toBe(false); }); @@ -154,7 +154,7 @@ describe('#deserializeFeaturePrivilege', () => { 'feature_foo_privilege-1', // no '.' 'feature_foo.', // has a '.' but nothing after it 'feature_.privilege-1', // nothing before the '.' - ].forEach(privilege => { + ].forEach((privilege) => { test(`throws error when deserializing ${privilege}`, () => { expect(() => PrivilegeSerializer.deserializeFeaturePrivilege(privilege) diff --git a/x-pack/plugins/security/server/authorization/privilege_serializer.ts b/x-pack/plugins/security/server/authorization/privilege_serializer.ts index 2bbebaa1cc951..bc5bf81c2d429 100644 --- a/x-pack/plugins/security/server/authorization/privilege_serializer.ts +++ b/x-pack/plugins/security/server/authorization/privilege_serializer.ts @@ -10,7 +10,7 @@ const reservedPrefix = 'reserved_'; const basePrivilegeNames = ['all', 'read']; const globalBasePrivileges = [...basePrivilegeNames]; const spaceBasePrivileges = basePrivilegeNames.map( - privilegeName => `${spacePrefix}${privilegeName}` + (privilegeName) => `${spacePrefix}${privilegeName}` ); const deserializeFeaturePrivilegeRegexp = new RegExp( `^${featurePrefix}([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$` diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts index b13132f6efbe5..6b7d94bb0127e 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts @@ -10,7 +10,7 @@ import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; export class FeaturePrivilegeApiBuilder extends BaseFeaturePrivilegeBuilder { public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { if (privilegeDefinition.api) { - return privilegeDefinition.api.map(operation => this.actions.api.get(operation)); + return privilegeDefinition.api.map((operation) => this.actions.api.get(operation)); } return []; diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts index 514d6734b47ba..213aa83f2d26e 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts @@ -15,6 +15,6 @@ export class FeaturePrivilegeAppBuilder extends BaseFeaturePrivilegeBuilder { return []; } - return appIds.map(appId => this.actions.app.get(appId)); + return appIds.map((appId) => this.actions.app.get(appId)); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts index fc15aff32b975..f1ea7091b9481 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts @@ -15,7 +15,7 @@ export class FeaturePrivilegeCatalogueBuilder extends BaseFeaturePrivilegeBuilde return []; } - return catalogueEntries.map(catalogueEntryId => + return catalogueEntries.map((catalogueEntryId) => this.actions.ui.get('catalogue', catalogueEntryId) ); } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts index c293319070419..3d6dfbdac0251 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts @@ -30,7 +30,7 @@ export const featurePrivilegeBuilderFactory = (actions: Actions): FeaturePrivile return { getActions(privilege: FeatureKibanaPrivileges, feature: Feature) { - return flatten(builders.map(builder => builder.getActions(privilege, feature))); + return flatten(builders.map((builder) => builder.getActions(privilege, feature))); }, }; }; diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts index 7a2bb87d72b45..be784949dc2fa 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts @@ -16,7 +16,7 @@ export class FeaturePrivilegeManagementBuilder extends BaseFeaturePrivilegeBuild } return Object.entries(managementSections).reduce((acc, [sectionId, items]) => { - return [...acc, ...items.map(item => this.actions.ui.get('management', sectionId, item))]; + return [...acc, ...items.map((item) => this.actions.ui.get('management', sectionId, item))]; }, [] as string[]); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts index 9baa8dadc2923..2c325fc8c6cb7 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts @@ -16,13 +16,13 @@ export class FeaturePrivilegeSavedObjectBuilder extends BaseFeaturePrivilegeBuil public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { return uniq([ ...flatten( - privilegeDefinition.savedObject.all.map(type => [ - ...allOperations.map(operation => this.actions.savedObject.get(type, operation)), + privilegeDefinition.savedObject.all.map((type) => [ + ...allOperations.map((operation) => this.actions.savedObject.get(type, operation)), ]) ), ...flatten( - privilegeDefinition.savedObject.read.map(type => [ - ...readOperations.map(operation => this.actions.savedObject.get(type, operation)), + privilegeDefinition.savedObject.read.map((type) => [ + ...readOperations.map((operation) => this.actions.savedObject.get(type, operation)), ]) ), ]); diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts index 28a22285c2b8f..31bc351206e54 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts @@ -9,6 +9,6 @@ import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; export class FeaturePrivilegeUIBuilder extends BaseFeaturePrivilegeBuilder { public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { - return privilegeDefinition.ui.map(ui => this.actions.ui.get(feature.id, ui)); + return privilegeDefinition.ui.map((ui) => this.actions.ui.get(feature.id, ui)); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts index 7d92eacfe6b35..485783253d29d 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts @@ -140,7 +140,7 @@ describe('featurePrivilegeIterator', () => { const actualPrivileges = Array.from( featurePrivilegeIterator(feature, { augmentWithSubFeaturePrivileges: true, - predicate: privilegeId => privilegeId === 'all', + predicate: (privilegeId) => privilegeId === 'all', }) ); diff --git a/x-pack/plugins/security/server/authorization/privileges/privileges.ts b/x-pack/plugins/security/server/authorization/privileges/privileges.ts index 9a8935f80a174..f3b2881e79ece 100644 --- a/x-pack/plugins/security/server/authorization/privileges/privileges.ts +++ b/x-pack/plugins/security/server/authorization/privileges/privileges.ts @@ -31,12 +31,14 @@ export function privilegesFactory( get() { const features = featuresService.getFeatures(); const { allowSubFeaturePrivileges } = licenseService.getFeatures(); - const basePrivilegeFeatures = features.filter(feature => !feature.excludeFromBasePrivileges); + const basePrivilegeFeatures = features.filter( + (feature) => !feature.excludeFromBasePrivileges + ); let allActions: string[] = []; let readActions: string[] = []; - basePrivilegeFeatures.forEach(feature => { + basePrivilegeFeatures.forEach((feature) => { for (const { privilegeId, privilege } of featurePrivilegeIterator(feature, { augmentWithSubFeaturePrivileges: true, predicate: (pId, featurePrivilege) => !featurePrivilege.excludeFromBasePrivileges, @@ -110,7 +112,7 @@ export function privilegesFactory( }, reserved: features.reduce((acc: Record, feature: Feature) => { if (feature.reserved) { - feature.reserved.privileges.forEach(reservedPrivilege => { + feature.reserved.privileges.forEach((reservedPrivilege) => { acc[reservedPrivilege.id] = [ actions.version, ...uniq(featurePrivilegeBuilder.getActions(reservedPrivilege.privilege, feature)), diff --git a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts index dc406c17925dd..fff4345c72409 100644 --- a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts +++ b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts @@ -101,7 +101,7 @@ const registerPrivilegesWithClusterTest = ( test(description, async () => { const mockClusterClient = elasticsearchServiceMock.createClusterClient(); - mockClusterClient.callAsInternalUser.mockImplementation(async api => { + mockClusterClient.callAsInternalUser.mockImplementation(async (api) => { switch (api) { case 'shield.getPrivilege': { if (throwErrorWhenGettingPrivileges) { diff --git a/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts b/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts index 510feb1151a9b..79e5348b4ac64 100644 --- a/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts +++ b/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts @@ -9,15 +9,15 @@ import { Feature } from '../../../features/server'; export function validateFeaturePrivileges(features: Feature[]) { for (const feature of features) { const seenPrivilegeIds = new Set(); - Object.keys(feature.privileges ?? {}).forEach(privilegeId => { + Object.keys(feature.privileges ?? {}).forEach((privilegeId) => { seenPrivilegeIds.add(privilegeId); seenPrivilegeIds.add(`minimal_${privilegeId}`); }); const subFeatureEntries = feature.subFeatures ?? []; - subFeatureEntries.forEach(subFeature => { - subFeature.privilegeGroups.forEach(subFeaturePrivilegeGroup => { - subFeaturePrivilegeGroup.privileges.forEach(subFeaturePrivilege => { + subFeatureEntries.forEach((subFeature) => { + subFeature.privilegeGroups.forEach((subFeaturePrivilegeGroup) => { + subFeaturePrivilegeGroup.privileges.forEach((subFeaturePrivilege) => { if (seenPrivilegeIds.has(subFeaturePrivilege.id)) { throw new Error( `Feature '${feature.id}' already has a privilege with ID '${subFeaturePrivilege.id}'. Sub feature '${subFeature.name}' cannot also specify this.` diff --git a/x-pack/plugins/security/server/config.ts b/x-pack/plugins/security/server/config.ts index 695653a2ac1db..4026666d042bd 100644 --- a/x-pack/plugins/security/server/config.ts +++ b/x-pack/plugins/security/server/config.ts @@ -15,7 +15,7 @@ const providerOptionsSchema = (providerType: string, optionsSchema: Type) = schema.conditional( schema.siblingRef('providers'), schema.arrayOf(schema.string(), { - validate: providers => (!providers.includes(providerType) ? 'error' : undefined), + validate: (providers) => (!providers.includes(providerType) ? 'error' : undefined), }), optionsSchema, schema.never() @@ -45,7 +45,7 @@ function getUniqueProviderSchema( return schema.maybe( schema.recordOf(schema.string(), schema.object(getCommonProviderSchemaProperties(overrides)), { validate(config) { - if (Object.values(config).filter(provider => provider.enabled).length > 1) { + if (Object.values(config).filter((provider) => provider.enabled).length > 1) { return `Only one "${providerType}" provider can be configured.`; } }, @@ -65,7 +65,7 @@ const providersConfigSchema = schema.object( icon: schema.string({ defaultValue: 'logoElasticsearch' }), showInSelector: schema.boolean({ defaultValue: true, - validate: value => { + validate: (value) => { if (!value) { return '`basic` provider only supports `true` in `showInSelector`.'; } @@ -81,7 +81,7 @@ const providersConfigSchema = schema.object( icon: schema.string({ defaultValue: 'logoElasticsearch' }), showInSelector: schema.boolean({ defaultValue: true, - validate: value => { + validate: (value) => { if (!value) { return '`token` provider only supports `true` in `showInSelector`.'; } diff --git a/x-pack/plugins/security/server/index.ts b/x-pack/plugins/security/server/index.ts index 0011737d85734..0de86c72002c9 100644 --- a/x-pack/plugins/security/server/index.ts +++ b/x-pack/plugins/security/server/index.ts @@ -53,7 +53,7 @@ export const config: PluginConfigDescriptor> = { } return Object.values(providers?.[providerType] || {}).some( - provider => (provider as { enabled: boolean | undefined })?.enabled !== false + (provider) => (provider as { enabled: boolean | undefined })?.enabled !== false ); }; diff --git a/x-pack/plugins/security/server/plugin.ts b/x-pack/plugins/security/server/plugin.ts index 77a2d716e6d87..89cffde92d564 100644 --- a/x-pack/plugins/security/server/plugin.ts +++ b/x-pack/plugins/security/server/plugin.ts @@ -115,7 +115,7 @@ export class Plugin { public async setup(core: CoreSetup, { features, licensing }: PluginSetupDependencies) { const [config, legacyConfig] = await combineLatest([ this.initializerContext.config.create>().pipe( - map(rawConfig => + map((rawConfig) => createConfig(rawConfig, this.initializerContext.logger.get('config'), { isTLSEnabled: core.http.isTlsEnabled, }) @@ -196,7 +196,7 @@ export class Plugin { license, - registerSpacesService: service => { + registerSpacesService: (service) => { if (this.wasSpacesServiceAccessed()) { throw new Error('Spaces service has been accessed before registration.'); } diff --git a/x-pack/plugins/security/server/routes/api_keys/invalidate.ts b/x-pack/plugins/security/server/routes/api_keys/invalidate.ts index cb86c1024ae9a..dd472c0b60cbc 100644 --- a/x-pack/plugins/security/server/routes/api_keys/invalidate.ts +++ b/x-pack/plugins/security/server/routes/api_keys/invalidate.ts @@ -33,7 +33,7 @@ export function defineInvalidateApiKeysRoutes({ router, clusterClient }: RouteDe // Invalidate all API keys in parallel. const invalidationResult = ( await Promise.all( - request.body.apiKeys.map(async key => { + request.body.apiKeys.map(async (key) => { try { const body: { id: string; owner?: boolean } = { id: key.id }; if (!request.body.isAdmin) { diff --git a/x-pack/plugins/security/server/routes/authentication/basic.test.ts b/x-pack/plugins/security/server/routes/authentication/basic.test.ts index 5eed8e166c957..944bc567de586 100644 --- a/x-pack/plugins/security/server/routes/authentication/basic.test.ts +++ b/x-pack/plugins/security/server/routes/authentication/basic.test.ts @@ -28,7 +28,7 @@ describe('Basic authentication routes', () => { router = routeParamsMock.router; authc = routeParamsMock.authc; - authc.isProviderTypeEnabled.mockImplementation(provider => provider === 'basic'); + authc.isProviderTypeEnabled.mockImplementation((provider) => provider === 'basic'); mockContext = ({ licensing: { @@ -156,7 +156,7 @@ describe('Basic authentication routes', () => { it('prefers `token` authentication provider if it is enabled', async () => { authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockAuthenticatedUser())); authc.isProviderTypeEnabled.mockImplementation( - provider => provider === 'token' || provider === 'basic' + (provider) => provider === 'token' || provider === 'basic' ); const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory); diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts index c9e963f0b8fc7..08cd3ba487b0b 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts @@ -16,8 +16,8 @@ export function defineGetBuiltinPrivilegesRoutes({ router, clusterClient }: Rout .callAsCurrentUser('shield.getBuiltinPrivileges'); // Exclude the `none` privilege, as it doesn't make sense as an option within the Kibana UI - privileges.cluster = privileges.cluster.filter(privilege => privilege !== 'none'); - privileges.index = privileges.index.filter(privilege => privilege !== 'none'); + privileges.cluster = privileges.cluster.filter((privilege) => privilege !== 'none'); + privileges.index = privileges.index.filter((privilege) => privilege !== 'none'); return response.ok({ body: privileges }); } diff --git a/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts b/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts index 609b7d2f35c4b..0fd087231b770 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts @@ -56,13 +56,13 @@ function transformRoleApplicationsToKibanaPrivileges( application: string ) { const roleKibanaApplications = roleApplications.filter( - roleApplication => + (roleApplication) => roleApplication.application === application || roleApplication.application === RESERVED_PRIVILEGES_APPLICATION_WILDCARD ); // if any application entry contains an empty resource, we throw an error - if (roleKibanaApplications.some(entry => entry.resources.length === 0)) { + if (roleKibanaApplications.some((entry) => entry.resources.length === 0)) { throw new Error(`ES returned an application entry without resources, can't process this`); } @@ -70,9 +70,9 @@ function transformRoleApplicationsToKibanaPrivileges( // and there are privileges which aren't reserved, we won't transform these if ( roleKibanaApplications.some( - entry => + (entry) => entry.application === RESERVED_PRIVILEGES_APPLICATION_WILDCARD && - !entry.privileges.every(privilege => + !entry.privileges.every((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) ) @@ -85,9 +85,9 @@ function transformRoleApplicationsToKibanaPrivileges( // if space privilege assigned globally, we can't transform these if ( roleKibanaApplications.some( - entry => + (entry) => entry.resources.includes(GLOBAL_RESOURCE) && - entry.privileges.some(privilege => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) ) ) @@ -100,10 +100,10 @@ function transformRoleApplicationsToKibanaPrivileges( // if global base or reserved privilege assigned at a space, we can't transform these if ( roleKibanaApplications.some( - entry => + (entry) => !entry.resources.includes(GLOBAL_RESOURCE) && entry.privileges.some( - privilege => + (privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) || PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) @@ -117,12 +117,12 @@ function transformRoleApplicationsToKibanaPrivileges( // if reserved privilege assigned with feature or base privileges, we won't transform these if ( roleKibanaApplications.some( - entry => - entry.privileges.some(privilege => + (entry) => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) && entry.privileges.some( - privilege => !PrivilegeSerializer.isSerializedReservedPrivilege(privilege) + (privilege) => !PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) ) ) { @@ -134,14 +134,14 @@ function transformRoleApplicationsToKibanaPrivileges( // if base privilege assigned with feature privileges, we won't transform these if ( roleKibanaApplications.some( - entry => - entry.privileges.some(privilege => + (entry) => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ) && - (entry.privileges.some(privilege => + (entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) ) || - entry.privileges.some(privilege => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) )) ) @@ -154,7 +154,7 @@ function transformRoleApplicationsToKibanaPrivileges( // if any application entry contains the '*' resource in addition to another resource, we can't transform these if ( roleKibanaApplications.some( - entry => entry.resources.includes(GLOBAL_RESOURCE) && entry.resources.length > 1 + (entry) => entry.resources.includes(GLOBAL_RESOURCE) && entry.resources.length > 1 ) ) { return { @@ -162,11 +162,11 @@ function transformRoleApplicationsToKibanaPrivileges( }; } - const allResources = roleKibanaApplications.map(entry => entry.resources).flat(); + const allResources = roleKibanaApplications.map((entry) => entry.resources).flat(); // if we have improperly formatted resource entries, we can't transform these if ( allResources.some( - resource => + (resource) => resource !== GLOBAL_RESOURCE && !ResourceSerializer.isSerializedSpaceResource(resource) ) ) { @@ -187,25 +187,25 @@ function transformRoleApplicationsToKibanaPrivileges( value: roleKibanaApplications.map(({ resources, privileges }) => { // if we're dealing with a global entry, which we've ensured above is only possible if it's the only item in the array if (resources.length === 1 && resources[0] === GLOBAL_RESOURCE) { - const reservedPrivileges = privileges.filter(privilege => + const reservedPrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ); - const basePrivileges = privileges.filter(privilege => + const basePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) ); - const featurePrivileges = privileges.filter(privilege => + const featurePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ); return { ...(reservedPrivileges.length ? { - _reserved: reservedPrivileges.map(privilege => + _reserved: reservedPrivileges.map((privilege) => PrivilegeSerializer.deserializeReservedPrivilege(privilege) ), } : {}), - base: basePrivileges.map(privilege => + base: basePrivileges.map((privilege) => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege) ), feature: featurePrivileges.reduce((acc, privilege) => { @@ -222,14 +222,14 @@ function transformRoleApplicationsToKibanaPrivileges( }; } - const basePrivileges = privileges.filter(privilege => + const basePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) ); - const featurePrivileges = privileges.filter(privilege => + const featurePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ); return { - base: basePrivileges.map(privilege => + base: basePrivileges.map((privilege) => PrivilegeSerializer.deserializeSpaceBasePrivilege(privilege) ), feature: featurePrivileges.reduce((acc, privilege) => { @@ -242,7 +242,7 @@ function transformRoleApplicationsToKibanaPrivileges( ]), }; }, {} as RoleKibanaPrivilege['feature']), - spaces: resources.map(resource => ResourceSerializer.deserializeSpaceResource(resource)), + spaces: resources.map((resource) => ResourceSerializer.deserializeSpaceResource(resource)), }; }), }; @@ -255,11 +255,11 @@ const extractUnrecognizedApplicationNames = ( return getUniqueList( roleApplications .filter( - roleApplication => + (roleApplication) => roleApplication.application !== application && roleApplication.application !== RESERVED_PRIVILEGES_APPLICATION_WILDCARD ) - .map(roleApplication => roleApplication.application) + .map((roleApplication) => roleApplication.application) ); }; diff --git a/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts b/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts index a5f6b2fd9fcc1..e0af14f90d01c 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts @@ -142,7 +142,7 @@ export function getPutPayloadSchema( schema.string({ validate(value) { const globalPrivileges = getBasePrivilegeNames().global; - if (!globalPrivileges.some(privilege => privilege === value)) { + if (!globalPrivileges.some((privilege) => privilege === value)) { return `unknown global privilege "${value}", must be one of [${globalPrivileges}]`; } }, @@ -152,7 +152,7 @@ export function getPutPayloadSchema( schema.string({ validate(value) { const spacePrivileges = getBasePrivilegeNames().space; - if (!spacePrivileges.some(privilege => privilege === value)) { + if (!spacePrivileges.some((privilege) => privilege === value)) { return `unknown space privilege "${value}", must be one of [${spacePrivileges}]`; } }, @@ -235,7 +235,7 @@ export const transformPutPayloadToElasticsearchRole = ( kibana = [], } = rolePayload; const otherApplications = allExistingApplications.filter( - roleApplication => roleApplication.application !== application + (roleApplication) => roleApplication.application !== application ); return { @@ -259,12 +259,12 @@ const transformPrivilegesToElasticsearchPrivileges = ( return { privileges: [ ...(base - ? base.map(privilege => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege)) + ? base.map((privilege) => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege)) : []), ...(feature ? Object.entries(feature) .map(([featureName, featurePrivileges]) => - featurePrivileges.map(privilege => + featurePrivileges.map((privilege) => PrivilegeSerializer.serializeFeaturePrivilege(featureName, privilege) ) ) @@ -279,12 +279,12 @@ const transformPrivilegesToElasticsearchPrivileges = ( return { privileges: [ ...(base - ? base.map(privilege => PrivilegeSerializer.serializeSpaceBasePrivilege(privilege)) + ? base.map((privilege) => PrivilegeSerializer.serializeSpaceBasePrivilege(privilege)) : []), ...(feature ? Object.entries(feature) .map(([featureName, featurePrivileges]) => - featurePrivileges.map(privilege => + featurePrivileges.map((privilege) => PrivilegeSerializer.serializeFeaturePrivilege(featureName, privilege) ) ) @@ -292,7 +292,7 @@ const transformPrivilegesToElasticsearchPrivileges = ( : []), ], application, - resources: (spaces as string[]).map(resource => + resources: (spaces as string[]).map((resource) => ResourceSerializer.serializeSpaceResource(resource) ), }; diff --git a/x-pack/plugins/security/server/routes/indices/get_fields.ts b/x-pack/plugins/security/server/routes/indices/get_fields.ts index 64c3d4f7471ef..356b78aa33879 100644 --- a/x-pack/plugins/security/server/routes/indices/get_fields.ts +++ b/x-pack/plugins/security/server/routes/indices/get_fields.ts @@ -34,7 +34,7 @@ export function defineGetFieldsRoutes({ router, clusterClient }: RouteDefinition body: Array.from( new Set( Object.values(indexMappings) - .map(indexMapping => Object.keys(indexMapping.mappings)) + .map((indexMapping) => Object.keys(indexMapping.mappings)) .flat() ) ), diff --git a/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts b/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts index 2be4f4cd89177..b056d9e358737 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts @@ -80,7 +80,7 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log .callAsInternalUser('nodes.info', { filterPath: 'nodes.*.settings.script', }) - .catch(error => { + .catch((error) => { // fall back to assuming that node settings are unset/at their default values. // this will allow the role mappings UI to permit both role template script types, // even if ES will disallow it at mapping evaluation time. @@ -95,7 +95,7 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log method: 'GET', path: '/_xpack/usage', }) - .catch(error => { + .catch((error) => { // fall back to no external realms configured. // this will cause a warning in the UI about no compatible realms being enabled, but will otherwise allow // the mappings screen to function correctly. @@ -115,12 +115,12 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log let canUseStoredScripts = true; let canUseInlineScripts = true; if (usesCustomScriptSettings(nodeScriptSettings)) { - canUseStoredScripts = Object.values(nodeScriptSettings.nodes).some(node => { + canUseStoredScripts = Object.values(nodeScriptSettings.nodes).some((node) => { const allowedTypes = node.settings.script.allowed_types; return !allowedTypes || allowedTypes.includes('stored'); }); - canUseInlineScripts = Object.values(nodeScriptSettings.nodes).some(node => { + canUseInlineScripts = Object.values(nodeScriptSettings.nodes).some((node) => { const allowedTypes = node.settings.script.allowed_types; return !allowedTypes || allowedTypes.includes('inline'); }); diff --git a/x-pack/plugins/security/server/routes/role_mapping/get.ts b/x-pack/plugins/security/server/routes/role_mapping/get.ts index def6fabc0e322..63598584b5d1b 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/get.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/get.ts @@ -39,7 +39,7 @@ export function defineRoleMappingGetRoutes(params: RouteDefinitionParams) { return { name, ...mapping, - role_templates: (mapping.role_templates || []).map(entry => { + role_templates: (mapping.role_templates || []).map((entry) => { return { ...entry, template: tryParseRoleTemplate(entry.template as string), diff --git a/x-pack/plugins/security/server/routes/views/index.test.ts b/x-pack/plugins/security/server/routes/views/index.test.ts index 7cddef9bf2b98..0c0117dec5390 100644 --- a/x-pack/plugins/security/server/routes/views/index.test.ts +++ b/x-pack/plugins/security/server/routes/views/index.test.ts @@ -12,7 +12,7 @@ describe('View routes', () => { it('does not register Login routes if both `basic` and `token` providers are disabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'basic' && provider !== 'token' + (provider) => provider !== 'basic' && provider !== 'token' ); defineViewRoutes(routeParamsMock); @@ -37,7 +37,7 @@ describe('View routes', () => { it('registers Login routes if `basic` provider is enabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'token' + (provider) => provider !== 'token' ); defineViewRoutes(routeParamsMock); @@ -64,7 +64,7 @@ describe('View routes', () => { it('registers Login routes if `token` provider is enabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'basic' + (provider) => provider !== 'basic' ); defineViewRoutes(routeParamsMock); diff --git a/x-pack/plugins/security/server/saved_objects/index.ts b/x-pack/plugins/security/server/saved_objects/index.ts index 40c17e5429aa8..29fbe3af21b95 100644 --- a/x-pack/plugins/security/server/saved_objects/index.ts +++ b/x-pack/plugins/security/server/saved_objects/index.ts @@ -31,14 +31,16 @@ export function setupSavedObjects({ const getKibanaRequest = (request: KibanaRequest | LegacyRequest) => request instanceof KibanaRequest ? request : KibanaRequest.from(request); - savedObjects.setClientFactoryProvider(repositoryFactory => ({ request, includedHiddenTypes }) => { - const kibanaRequest = getKibanaRequest(request); - return new SavedObjectsClient( - authz.mode.useRbacForRequest(kibanaRequest) - ? repositoryFactory.createInternalRepository(includedHiddenTypes) - : repositoryFactory.createScopedRepository(kibanaRequest, includedHiddenTypes) - ); - }); + savedObjects.setClientFactoryProvider( + (repositoryFactory) => ({ request, includedHiddenTypes }) => { + const kibanaRequest = getKibanaRequest(request); + return new SavedObjectsClient( + authz.mode.useRbacForRequest(kibanaRequest) + ? repositoryFactory.createInternalRepository(includedHiddenTypes) + : repositoryFactory.createScopedRepository(kibanaRequest, includedHiddenTypes) + ); + } + ); savedObjects.addClientWrapper(Number.MAX_SAFE_INTEGER - 1, 'security', ({ client, request }) => { const kibanaRequest = getKibanaRequest(request); diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts index 3c4034e07f995..c646cd95228f0 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts @@ -76,7 +76,7 @@ const expectForbiddenError = async (fn: Function, args: Record) => const spaceId = args.options?.namespace || 'default'; const ACTION = getCalls[0][1]; - const types = getCalls.map(x => x[0]); + const types = getCalls.map((x) => x[0]); const missing = [{ spaceId, privilege: actions[0] }]; // if there was more than one type, only the first type was unauthorized const spaceIds = [spaceId]; @@ -99,7 +99,7 @@ const expectSuccess = async (fn: Function, args: Record) => { SavedObjectActions['get'] >).mock.calls; const ACTION = getCalls[0][1]; - const types = getCalls.map(x => x[0]); + const types = getCalls.map((x) => x[0]); const spaceIds = [args.options?.namespace || 'default']; expect(clientOpts.auditLogger.savedObjectsAuthorizationFailure).not.toHaveBeenCalled(); @@ -123,7 +123,7 @@ const expectPrivilegeCheck = async (fn: Function, args: Record) => const getResults = (clientOpts.actions.savedObject.get as jest.MockedFunction< SavedObjectActions['get'] >).mock.results; - const actions = getResults.map(x => x.value); + const actions = getResults.map((x) => x.value); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledTimes(1); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledWith( @@ -206,8 +206,8 @@ function getMockCheckPrivilegesSuccess(actions: string | string[], namespaces?: hasAllRequested: true, username: USERNAME, privileges: _namespaces - .map(resource => - _actions.map(action => ({ + .map((resource) => + _actions.map((action) => ({ resource, privilege: action, authorized: true, diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts index 29503d475be73..969344afae5e3 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts @@ -207,14 +207,14 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra ) { const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; const actionsToTypesMap = new Map( - types.map(type => [this.actions.savedObject.get(type, action), type]) + types.map((type) => [this.actions.savedObject.get(type, action), type]) ); const actions = Array.from(actionsToTypesMap.keys()); const result = await this.checkPrivileges(actions, namespaceOrNamespaces); const { hasAllRequested, username, privileges } = result; const spaceIds = uniq( - privileges.map(({ resource }) => resource).filter(x => x !== undefined) + privileges.map(({ resource }) => resource).filter((x) => x !== undefined) ).sort() as string[]; const isAuthorized = @@ -253,7 +253,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra } private getUniqueObjectTypes(objects: Array<{ type: string }>) { - return uniq(objects.map(o => o.type)); + return uniq(objects.map((o) => o.type)); } private async getNamespacesPrivilegeMap(namespaces: string[]) { @@ -287,7 +287,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra } return 0; }; - return spaceIds.map(spaceId => (privilegeMap[spaceId] ? spaceId : '?')).sort(comparator); + return spaceIds.map((spaceId) => (privilegeMap[spaceId] ? spaceId : '?')).sort(comparator); } private async redactSavedObjectNamespaces( @@ -312,7 +312,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra return response; } const { saved_objects: savedObjects } = response; - const namespaces = uniq(savedObjects.flatMap(savedObject => savedObject.namespaces || [])); + const namespaces = uniq(savedObjects.flatMap((savedObject) => savedObject.namespaces || [])); if (namespaces.length === 0) { return response; } @@ -321,7 +321,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra return { ...response, - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ ...savedObject, namespaces: savedObject.namespaces && diff --git a/x-pack/plugins/siem/common/endpoint/generate_data.test.ts b/x-pack/plugins/siem/common/endpoint/generate_data.test.ts index f99fa5c871d89..3dcf20c41f269 100644 --- a/x-pack/plugins/siem/common/endpoint/generate_data.test.ts +++ b/x-pack/plugins/siem/common/endpoint/generate_data.test.ts @@ -142,7 +142,7 @@ describe('data generator', () => { function buildResolverTree(events: Event[]): Node { // First pass we gather up all the events by entity_id const tree: Record = {}; - events.forEach(event => { + events.forEach((event) => { if (event.process.entity_id in tree) { tree[event.process.entity_id].events.push(event); } else { @@ -169,7 +169,7 @@ describe('data generator', () => { let visitedEvents = 0; for (let i = 0; i < generations + 1; i++) { let nextNodes: Node[] = []; - nodes.forEach(node => { + nodes.forEach((node) => { nextNodes = nextNodes.concat(node.children); visitedEvents += node.events.length; }); diff --git a/x-pack/plugins/siem/common/endpoint/generate_data.ts b/x-pack/plugins/siem/common/endpoint/generate_data.ts index 9e3b5a22f1607..f520e2bf91041 100644 --- a/x-pack/plugins/siem/common/endpoint/generate_data.ts +++ b/x-pack/plugins/siem/common/endpoint/generate_data.ts @@ -752,15 +752,15 @@ export class EndpointDocGenerator { } private randomMac(): string { - return [...this.randomNGenerator(255, 6)].map(x => x.toString(16)).join('-'); + return [...this.randomNGenerator(255, 6)].map((x) => x.toString(16)).join('-'); } private randomIP(): string { - return [10, ...this.randomNGenerator(255, 3)].map(x => x.toString()).join('.'); + return [10, ...this.randomNGenerator(255, 3)].map((x) => x.toString()).join('.'); } private randomVersion(): string { - return [6, ...this.randomNGenerator(10, 2)].map(x => x.toString()).join('.'); + return [6, ...this.randomNGenerator(10, 2)].map((x) => x.toString()).join('.'); } private randomChoice(choices: T[]): T { @@ -768,7 +768,7 @@ export class EndpointDocGenerator { } private randomString(length: number): string { - return [...this.randomNGenerator(36, length)].map(x => x.toString(36)).join(''); + return [...this.randomNGenerator(36, length)].map((x) => x.toString(36)).join(''); } private randomHostname(): string { diff --git a/x-pack/plugins/siem/common/exact_check.ts b/x-pack/plugins/siem/common/exact_check.ts index 9484765f9973d..30c5b585a3480 100644 --- a/x-pack/plugins/siem/common/exact_check.ts +++ b/x-pack/plugins/siem/common/exact_check.ts @@ -58,8 +58,8 @@ export const findDifferencesRecursive = (original: T, decodedValue: T): strin return []; } else { const decodedKeys = Object.keys(decodedValue); - const differences = Object.keys(original).flatMap(originalKey => { - const foundKey = decodedKeys.some(key => key === originalKey); + const differences = Object.keys(original).flatMap((originalKey) => { + const foundKey = decodedKeys.some((key) => key === originalKey); const topLevelKey = foundKey ? [] : [originalKey]; // I use lodash to cheat and get an any (not going to lie ;-)) const valueObjectOrArrayOriginal = get(originalKey, original); diff --git a/x-pack/plugins/siem/common/format_errors.ts b/x-pack/plugins/siem/common/format_errors.ts index a9c222050ee38..d712979f9eff3 100644 --- a/x-pack/plugins/siem/common/format_errors.ts +++ b/x-pack/plugins/siem/common/format_errors.ts @@ -7,15 +7,15 @@ import * as t from 'io-ts'; export const formatErrors = (errors: t.Errors): string[] => { - return errors.map(error => { + return errors.map((error) => { if (error.message != null) { return error.message; } else { const mappedContext = error.context .filter( - entry => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' + (entry) => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' ) - .map(entry => entry.key) + .map((entry) => entry.key) .join(','); return `Invalid value "${error.value}" supplied to "${mappedContext}"`; } diff --git a/x-pack/plugins/siem/common/test_utils.ts b/x-pack/plugins/siem/common/test_utils.ts index 29b0119dcbeb7..b96639ad7b034 100644 --- a/x-pack/plugins/siem/common/test_utils.ts +++ b/x-pack/plugins/siem/common/test_utils.ts @@ -36,7 +36,7 @@ export const getPaths = (validation: t.Validation): string[] => { return pipe( validation, fold( - errors => formatErrors(errors), + (errors) => formatErrors(errors), () => ['no errors'] ) ); diff --git a/x-pack/plugins/siem/cypress/integration/cases.spec.ts b/x-pack/plugins/siem/cypress/integration/cases.spec.ts index 8f35a3209c69d..bb2dffe8ddd7d 100644 --- a/x-pack/plugins/siem/cypress/integration/cases.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/cases.spec.ts @@ -84,22 +84,14 @@ describe('Cases', () => { const expectedTags = case1.tags.join(''); cy.get(CASE_DETAILS_PAGE_TITLE).should('have.text', case1.name); cy.get(CASE_DETAILS_STATUS).should('have.text', 'open'); - cy.get(CASE_DETAILS_USER_ACTION) - .eq(USER) - .should('have.text', case1.reporter); - cy.get(CASE_DETAILS_USER_ACTION) - .eq(ACTION) - .should('have.text', 'added description'); + cy.get(CASE_DETAILS_USER_ACTION).eq(USER).should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USER_ACTION).eq(ACTION).should('have.text', 'added description'); cy.get(CASE_DETAILS_DESCRIPTION).should( 'have.text', `${case1.description} ${case1.timeline.title}` ); - cy.get(CASE_DETAILS_USERNAMES) - .eq(REPORTER) - .should('have.text', case1.reporter); - cy.get(CASE_DETAILS_USERNAMES) - .eq(PARTICIPANTS) - .should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USERNAMES).eq(REPORTER).should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USERNAMES).eq(PARTICIPANTS).should('have.text', case1.reporter); cy.get(CASE_DETAILS_TAGS).should('have.text', expectedTags); cy.get(CASE_DETAILS_PUSH_TO_EXTERNAL_SERVICE_BTN).should('have.attr', 'disabled'); diff --git a/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts b/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts index 9be9067a38ee8..339dee6bb9666 100644 --- a/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts @@ -31,16 +31,12 @@ describe.skip('Cases connectors', () => { openAddNewConnectorOption(); addServiceNowConnector(serviceNowConnector); - cy.wait('@createConnector') - .its('status') - .should('eql', 200); + cy.wait('@createConnector').its('status').should('eql', 200); cy.get(TOASTER).should('have.text', "Created 'New connector'"); selectLastConnectorCreated(); - cy.wait('@saveConnector', { timeout: 10000 }) - .its('status') - .should('eql', 200); + cy.wait('@saveConnector', { timeout: 10000 }).its('status').should('eql', 200); cy.get(TOASTER).should('have.text', 'Saved external connection settings'); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/detections.spec.ts b/x-pack/plugins/siem/cypress/integration/detections.spec.ts index f38cb2285b480..91727595708f6 100644 --- a/x-pack/plugins/siem/cypress/integration/detections.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/detections.spec.ts @@ -41,7 +41,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { cy.get(SHOWING_SIGNALS).should('have.text', `Showing ${numberOfSignals} signals`); const numberOfSignalsToBeClosed = 3; @@ -127,7 +127,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { const numberOfSignalsToBeClosed = 1; const numberOfSignalsToBeSelected = 3; @@ -141,9 +141,7 @@ describe('Detections', () => { waitForSignals(); const expectedNumberOfSignals = +numberOfSignals - numberOfSignalsToBeClosed; - cy.get(NUMBER_OF_SIGNALS) - .invoke('text') - .should('eq', expectedNumberOfSignals.toString()); + cy.get(NUMBER_OF_SIGNALS).invoke('text').should('eq', expectedNumberOfSignals.toString()); cy.get(SHOWING_SIGNALS) .invoke('text') .should('eql', `Showing ${expectedNumberOfSignals.toString()} signals`); @@ -174,7 +172,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { const numberOfSignalsToBeOpened = 1; const numberOfSignalsToBeSelected = 3; @@ -189,9 +187,7 @@ describe('Detections', () => { waitForSignals(); const expectedNumberOfSignals = +numberOfSignals - numberOfSignalsToBeOpened; - cy.get(NUMBER_OF_SIGNALS) - .invoke('text') - .should('eq', expectedNumberOfSignals.toString()); + cy.get(NUMBER_OF_SIGNALS).invoke('text').should('eq', expectedNumberOfSignals.toString()); cy.get(SHOWING_SIGNALS) .invoke('text') .should('eql', `Showing ${expectedNumberOfSignals.toString()} signals`); diff --git a/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts b/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts index 2cac6e0f603b9..6ea34f5203adc 100644 --- a/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts @@ -33,11 +33,9 @@ describe('Detections timeline', () => { cy.get(SIGNAL_ID) .first() .invoke('text') - .then(eventId => { + .then((eventId) => { investigateFirstSignalInTimeline(); - cy.get(PROVIDER_BADGE) - .invoke('text') - .should('eql', `_id: "${eventId}"`); + cy.get(PROVIDER_BADGE).invoke('text').should('eql', `_id: "${eventId}"`); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts b/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts index aa463b01fd190..26ebaeb844825 100644 --- a/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts @@ -61,13 +61,11 @@ describe('Events Viewer', () => { }); it('displays the `default ECS` category (by default)', () => { - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', 'default ECS'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', 'default ECS'); }); it('displays a checked checkbox for all of the default events viewer columns that are also in the default ECS category', () => { - defaultHeadersInDefaultEcsCategory.forEach(header => + defaultHeadersInDefaultEcsCategory.forEach((header) => cy.get(FIELDS_BROWSER_CHECKBOX(header.id)).should('be.checked') ); }); @@ -137,25 +135,19 @@ describe('Events Viewer', () => { const filterInput = 'aa7ca589f1b8220002f2fc61c64cfbf1'; // this will never match real data cy.get(HEADER_SUBTITLE) .invoke('text') - .then(initialNumberOfEvents => { + .then((initialNumberOfEvents) => { kqlSearch(`${filterInput}{enter}`); - cy.get(HEADER_SUBTITLE) - .invoke('text') - .should('not.equal', initialNumberOfEvents); + cy.get(HEADER_SUBTITLE).invoke('text').should('not.equal', initialNumberOfEvents); }); }); it('loads more events when the load more button is clicked', () => { const defaultNumberOfLoadedEvents = '25'; - cy.get(LOCAL_EVENTS_COUNT) - .invoke('text') - .should('equal', defaultNumberOfLoadedEvents); + cy.get(LOCAL_EVENTS_COUNT).invoke('text').should('equal', defaultNumberOfLoadedEvents); cy.get(LOAD_MORE).click({ force: true }); - cy.get(LOCAL_EVENTS_COUNT) - .invoke('text') - .should('not.equal', defaultNumberOfLoadedEvents); + cy.get(LOCAL_EVENTS_COUNT).invoke('text').should('not.equal', defaultNumberOfLoadedEvents); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts b/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts index 8dddd97f2d830..b058c9fb51fd1 100644 --- a/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts @@ -58,9 +58,7 @@ describe('Fields Browser', () => { }); it('displays the `default ECS` category (by default)', () => { - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', 'default ECS'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', 'default ECS'); }); it('the `defaultECS` (selected) category count matches the default timeline header count', () => { @@ -70,7 +68,7 @@ describe('Fields Browser', () => { }); it('displays a checked checkbox for all of the default timeline columns', () => { - defaultHeaders.forEach(header => + defaultHeaders.forEach((header) => cy.get(`[data-test-subj="field-${header.id}-checkbox"]`).should('be.checked') ); }); @@ -80,9 +78,7 @@ describe('Fields Browser', () => { filterFieldsBrowser(filterInput); - cy.get(FIELDS_BROWSER_CATEGORIES_COUNT) - .invoke('text') - .should('eq', '2 categories'); + cy.get(FIELDS_BROWSER_CATEGORIES_COUNT).invoke('text').should('eq', '2 categories'); }); it('displays a search results label with the expected count of fields matching the filter input', () => { @@ -92,10 +88,10 @@ describe('Fields Browser', () => { cy.get(FIELDS_BROWSER_HOST_CATEGORIES_COUNT) .invoke('text') - .then(hostCategoriesCount => { + .then((hostCategoriesCount) => { cy.get(FIELDS_BROWSER_SYSTEM_CATEGORIES_COUNT) .invoke('text') - .then(systemCategoriesCount => { + .then((systemCategoriesCount) => { cy.get(FIELDS_BROWSER_FIELDS_COUNT) .invoke('text') .should('eq', `${+hostCategoriesCount + +systemCategoriesCount} fields`); @@ -108,9 +104,7 @@ describe('Fields Browser', () => { filterFieldsBrowser(filterInput); - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_COUNT) - .invoke('text') - .should('eq', '4'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_COUNT).invoke('text').should('eq', '4'); }); }); @@ -140,9 +134,7 @@ describe('Fields Browser', () => { const category = 'host'; filterFieldsBrowser(category); - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', category); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', category); }); it('adds a field to the timeline when the user clicks the checkbox', () => { diff --git a/x-pack/plugins/siem/cypress/integration/inspect.spec.ts b/x-pack/plugins/siem/cypress/integration/inspect.spec.ts index b6b4e7a72b8f6..d770eb6c761cf 100644 --- a/x-pack/plugins/siem/cypress/integration/inspect.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/inspect.spec.ts @@ -30,7 +30,7 @@ describe('Inspect', () => { closesModal(); }); - INSPECT_HOSTS_BUTTONS_IN_SIEM.forEach(table => + INSPECT_HOSTS_BUTTONS_IN_SIEM.forEach((table) => it(`inspects the ${table.title}`, () => { openStatsAndTables(table); cy.get(INSPECT_MODAL).should('be.visible'); @@ -46,7 +46,7 @@ describe('Inspect', () => { closesModal(); }); - INSPECT_NETWORK_BUTTONS_IN_SIEM.forEach(table => + INSPECT_NETWORK_BUTTONS_IN_SIEM.forEach((table) => it(`inspects the ${table.title}`, () => { openStatsAndTables(table); cy.get(INSPECT_MODAL).should('be.visible'); diff --git a/x-pack/plugins/siem/cypress/integration/overview.spec.ts b/x-pack/plugins/siem/cypress/integration/overview.spec.ts index cadb4beca0f9e..55bcbfafaa092 100644 --- a/x-pack/plugins/siem/cypress/integration/overview.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/overview.spec.ts @@ -20,20 +20,16 @@ describe('Overview Page', () => { it('Host stats render with correct values', () => { expandHostStats(); - HOST_STATS.forEach(stat => { - cy.get(stat.domId) - .invoke('text') - .should('eq', stat.value); + HOST_STATS.forEach((stat) => { + cy.get(stat.domId).invoke('text').should('eq', stat.value); }); }); it('Network stats render with correct values', () => { expandNetworkStats(); - NETWORK_STATS.forEach(stat => { - cy.get(stat.domId) - .invoke('text') - .should('eq', stat.value); + NETWORK_STATS.forEach((stat) => { + cy.get(stat.domId).invoke('text').should('eq', stat.value); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/pagination.spec.ts b/x-pack/plugins/siem/cypress/integration/pagination.spec.ts index 482c97fe29c3b..e430520fe1dc4 100644 --- a/x-pack/plugins/siem/cypress/integration/pagination.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/pagination.spec.ts @@ -32,13 +32,13 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .then(processNameFirstPage => { + .then((processNameFirstPage) => { goToThirdPage(); waitForUncommonProcessesToBeLoaded(); cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .should(processNameSecondPage => { + .should((processNameSecondPage) => { expect(processNameFirstPage).not.to.eq(processNameSecondPage); }); }); @@ -54,7 +54,7 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .then(expectedThirdPageResult => { + .then((expectedThirdPageResult) => { openAuthentications(); waitForAuthenticationsToBeLoaded(); cy.get(FIRST_PAGE_SELECTOR).should('have.class', 'euiPaginationButton-isActive'); @@ -64,7 +64,7 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .should(actualThirdPageResult => { + .should((actualThirdPageResult) => { expect(expectedThirdPageResult).to.eq(actualThirdPageResult); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts index ce6a49b675ef1..d07850e23f05e 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts @@ -46,13 +46,13 @@ describe('Signal detection rules', () => { cy.get(RULE_NAME) .eq(FIFTH_RULE) .invoke('text') - .then(fifthRuleName => { + .then((fifthRuleName) => { activateRule(FIFTH_RULE); waitForRuleToBeActivated(); cy.get(RULE_NAME) .eq(SEVENTH_RULE) .invoke('text') - .then(seventhRuleName => { + .then((seventhRuleName) => { activateRule(SEVENTH_RULE); waitForRuleToBeActivated(); sortByActivatedRules(); @@ -60,23 +60,19 @@ describe('Signal detection rules', () => { cy.get(RULE_NAME) .eq(FIRST_RULE) .invoke('text') - .then(firstRuleName => { + .then((firstRuleName) => { cy.get(RULE_NAME) .eq(SECOND_RULE) .invoke('text') - .then(secondRuleName => { + .then((secondRuleName) => { const expectedRulesNames = `${firstRuleName} ${secondRuleName}`; cy.wrap(expectedRulesNames).should('include', fifthRuleName); cy.wrap(expectedRulesNames).should('include', seventhRuleName); }); }); - cy.get(RULE_SWITCH) - .eq(FIRST_RULE) - .should('have.attr', 'role', 'switch'); - cy.get(RULE_SWITCH) - .eq(SECOND_RULE) - .should('have.attr', 'role', 'switch'); + cy.get(RULE_SWITCH).eq(FIRST_RULE).should('have.attr', 'role', 'switch'); + cy.get(RULE_SWITCH).eq(SECOND_RULE).should('have.attr', 'role', 'switch'); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts index 30a26ad9d18ea..4b5e12124dd40 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts @@ -84,52 +84,44 @@ describe('Signal detection rules, custom', () => { fillAboutRuleAndContinue(newRule); createAndActivateRule(); - cy.get(CUSTOM_RULES_BTN) - .invoke('text') - .should('eql', 'Custom rules (1)'); + cy.get(CUSTOM_RULES_BTN).invoke('text').should('eql', 'Custom rules (1)'); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); const expectedNumberOfRules = totalNumberOfPrebuiltRulesInEsArchive + 1; - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); filterByCustomRules(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', 1); }); - cy.get(RULE_NAME) - .invoke('text') - .should('eql', newRule.name); - cy.get(RISK_SCORE) - .invoke('text') - .should('eql', newRule.riskScore); - cy.get(SEVERITY) - .invoke('text') - .should('eql', newRule.severity); + cy.get(RULE_NAME).invoke('text').should('eql', newRule.name); + cy.get(RISK_SCORE).invoke('text').should('eql', newRule.riskScore); + cy.get(SEVERITY).invoke('text').should('eql', newRule.severity); cy.get('[data-test-subj="rule-switch"]').should('have.attr', 'aria-checked', 'true'); goToRuleDetails(); let expectedUrls = ''; - newRule.referenceUrls.forEach(url => { + newRule.referenceUrls.forEach((url) => { expectedUrls = expectedUrls + url; }); let expectedFalsePositives = ''; - newRule.falsePositivesExamples.forEach(falsePositive => { + newRule.falsePositivesExamples.forEach((falsePositive) => { expectedFalsePositives = expectedFalsePositives + falsePositive; }); let expectedTags = ''; - newRule.tags.forEach(tag => { + newRule.tags.forEach((tag) => { expectedTags = expectedTags + tag; }); let expectedMitre = ''; - newRule.mitre.forEach(mitre => { + newRule.mitre.forEach((mitre) => { expectedMitre = expectedMitre + mitre.tactic; - mitre.techniques.forEach(technique => { + mitre.techniques.forEach((technique) => { expectedMitre = expectedMitre + technique; }); }); @@ -142,69 +134,35 @@ describe('Signal detection rules, custom', () => { 'winlogbeat-*', ]; - cy.get(RULE_NAME_HEADER) - .invoke('text') - .should('eql', `${newRule.name} Beta`); + cy.get(RULE_NAME_HEADER).invoke('text').should('eql', `${newRule.name} Beta`); - cy.get(ABOUT_RULE_DESCRIPTION) - .invoke('text') - .should('eql', newRule.description); - cy.get(ABOUT_STEP) - .eq(ABOUT_SEVERITY) - .invoke('text') - .should('eql', newRule.severity); - cy.get(ABOUT_STEP) - .eq(ABOUT_RISK) - .invoke('text') - .should('eql', newRule.riskScore); - cy.get(ABOUT_STEP) - .eq(ABOUT_URLS) - .invoke('text') - .should('eql', expectedUrls); + cy.get(ABOUT_RULE_DESCRIPTION).invoke('text').should('eql', newRule.description); + cy.get(ABOUT_STEP).eq(ABOUT_SEVERITY).invoke('text').should('eql', newRule.severity); + cy.get(ABOUT_STEP).eq(ABOUT_RISK).invoke('text').should('eql', newRule.riskScore); + cy.get(ABOUT_STEP).eq(ABOUT_URLS).invoke('text').should('eql', expectedUrls); cy.get(ABOUT_STEP) .eq(ABOUT_FALSE_POSITIVES) .invoke('text') .should('eql', expectedFalsePositives); - cy.get(ABOUT_STEP) - .eq(ABOUT_MITRE) - .invoke('text') - .should('eql', expectedMitre); - cy.get(ABOUT_STEP) - .eq(ABOUT_TAGS) - .invoke('text') - .should('eql', expectedTags); + cy.get(ABOUT_STEP).eq(ABOUT_MITRE).invoke('text').should('eql', expectedMitre); + cy.get(ABOUT_STEP).eq(ABOUT_TAGS).invoke('text').should('eql', expectedTags); - cy.get(RULE_ABOUT_DETAILS_HEADER_TOGGLE) - .eq(INVESTIGATION_NOTES_TOGGLE) - .click({ force: true }); - cy.get(ABOUT_INVESTIGATION_NOTES) - .invoke('text') - .should('eql', INVESTIGATION_NOTES_MARKDOWN); + cy.get(RULE_ABOUT_DETAILS_HEADER_TOGGLE).eq(INVESTIGATION_NOTES_TOGGLE).click({ force: true }); + cy.get(ABOUT_INVESTIGATION_NOTES).invoke('text').should('eql', INVESTIGATION_NOTES_MARKDOWN); - cy.get(DEFINITION_INDEX_PATTERNS).then(patterns => { + cy.get(DEFINITION_INDEX_PATTERNS).then((patterns) => { cy.wrap(patterns).each((pattern, index) => { - cy.wrap(pattern) - .invoke('text') - .should('eql', expectedIndexPatterns[index]); + cy.wrap(pattern).invoke('text').should('eql', expectedIndexPatterns[index]); }); }); cy.get(DEFINITION_STEP) .eq(DEFINITION_CUSTOM_QUERY) .invoke('text') .should('eql', `${newRule.customQuery} `); - cy.get(DEFINITION_STEP) - .eq(DEFINITION_TIMELINE) - .invoke('text') - .should('eql', 'None'); + cy.get(DEFINITION_STEP).eq(DEFINITION_TIMELINE).invoke('text').should('eql', 'None'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_RUNS) - .invoke('text') - .should('eql', '5m'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_LOOPBACK) - .invoke('text') - .should('eql', '1m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_RUNS).invoke('text').should('eql', '5m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_LOOPBACK).invoke('text').should('eql', '1m'); }); }); @@ -224,7 +182,7 @@ describe('Deletes custom rules', () => { it('Deletes one rule', () => { cy.get(RULES_TABLE) .find(RULES_ROW) - .then(rules => { + .then((rules) => { const initialNumberOfRules = rules.length; const expectedNumberOfRulesAfterDeletion = initialNumberOfRules - 1; @@ -235,7 +193,7 @@ describe('Deletes custom rules', () => { deleteFirstRule(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(SHOWING_RULES_TEXT) @@ -250,7 +208,7 @@ describe('Deletes custom rules', () => { it('Deletes more than one rule', () => { cy.get(RULES_TABLE) .find(RULES_ROW) - .then(rules => { + .then((rules) => { const initialNumberOfRules = rules.length; const numberOfRulesToBeDeleted = 3; const expectedNumberOfRulesAfterDeletion = initialNumberOfRules - numberOfRulesToBeDeleted; @@ -259,7 +217,7 @@ describe('Deletes custom rules', () => { deleteSelectedRules(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(SHOWING_RULES_TEXT) diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts index f0e8b4556f704..aa1a111102160 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts @@ -37,8 +37,8 @@ describe('Export rules', () => { waitForSignalsIndexToBeCreated(); goToManageSignalDetectionRules(); exportFirstRule(); - cy.wait('@export').then(xhr => { - cy.readFile(EXPECTED_EXPORTED_RULE_FILE_PATH).then($expectedExportedJson => { + cy.wait('@export').then((xhr) => { + cy.readFile(EXPECTED_EXPORTED_RULE_FILE_PATH).then(($expectedExportedJson) => { cy.wrap(xhr.responseBody).should('eql', $expectedExportedJson); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts index e8b7441718765..cb04d8117a923 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts @@ -81,92 +81,65 @@ describe('Signal detection rules, machine learning', () => { fillAboutRuleAndContinue(machineLearningRule); createAndActivateRule(); - cy.get(CUSTOM_RULES_BTN) - .invoke('text') - .should('eql', 'Custom rules (1)'); + cy.get(CUSTOM_RULES_BTN).invoke('text').should('eql', 'Custom rules (1)'); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); const expectedNumberOfRules = totalNumberOfPrebuiltRulesInEsArchive + 1; - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); filterByCustomRules(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', 1); }); - cy.get(RULE_NAME) - .invoke('text') - .should('eql', machineLearningRule.name); - cy.get(RISK_SCORE) - .invoke('text') - .should('eql', machineLearningRule.riskScore); - cy.get(SEVERITY) - .invoke('text') - .should('eql', machineLearningRule.severity); + cy.get(RULE_NAME).invoke('text').should('eql', machineLearningRule.name); + cy.get(RISK_SCORE).invoke('text').should('eql', machineLearningRule.riskScore); + cy.get(SEVERITY).invoke('text').should('eql', machineLearningRule.severity); cy.get(RULE_SWITCH).should('have.attr', 'aria-checked', 'true'); goToRuleDetails(); let expectedUrls = ''; - machineLearningRule.referenceUrls.forEach(url => { + machineLearningRule.referenceUrls.forEach((url) => { expectedUrls = expectedUrls + url; }); let expectedFalsePositives = ''; - machineLearningRule.falsePositivesExamples.forEach(falsePositive => { + machineLearningRule.falsePositivesExamples.forEach((falsePositive) => { expectedFalsePositives = expectedFalsePositives + falsePositive; }); let expectedTags = ''; - machineLearningRule.tags.forEach(tag => { + machineLearningRule.tags.forEach((tag) => { expectedTags = expectedTags + tag; }); let expectedMitre = ''; - machineLearningRule.mitre.forEach(mitre => { + machineLearningRule.mitre.forEach((mitre) => { expectedMitre = expectedMitre + mitre.tactic; - mitre.techniques.forEach(technique => { + mitre.techniques.forEach((technique) => { expectedMitre = expectedMitre + technique; }); }); - cy.get(RULE_NAME_HEADER) - .invoke('text') - .should('eql', `${machineLearningRule.name} Beta`); + cy.get(RULE_NAME_HEADER).invoke('text').should('eql', `${machineLearningRule.name} Beta`); - cy.get(ABOUT_RULE_DESCRIPTION) - .invoke('text') - .should('eql', machineLearningRule.description); + cy.get(ABOUT_RULE_DESCRIPTION).invoke('text').should('eql', machineLearningRule.description); cy.get(ABOUT_STEP) .eq(ABOUT_SEVERITY) .invoke('text') .should('eql', machineLearningRule.severity); - cy.get(ABOUT_STEP) - .eq(ABOUT_RISK) - .invoke('text') - .should('eql', machineLearningRule.riskScore); - cy.get(ABOUT_STEP) - .eq(ABOUT_URLS) - .invoke('text') - .should('eql', expectedUrls); + cy.get(ABOUT_STEP).eq(ABOUT_RISK).invoke('text').should('eql', machineLearningRule.riskScore); + cy.get(ABOUT_STEP).eq(ABOUT_URLS).invoke('text').should('eql', expectedUrls); cy.get(ABOUT_STEP) .eq(ABOUT_FALSE_POSITIVES) .invoke('text') .should('eql', expectedFalsePositives); - cy.get(ABOUT_STEP) - .eq(ABOUT_MITRE) - .invoke('text') - .should('eql', expectedMitre); - cy.get(ABOUT_STEP) - .eq(ABOUT_TAGS) - .invoke('text') - .should('eql', expectedTags); + cy.get(ABOUT_STEP).eq(ABOUT_MITRE).invoke('text').should('eql', expectedMitre); + cy.get(ABOUT_STEP).eq(ABOUT_TAGS).invoke('text').should('eql', expectedTags); - cy.get(DEFINITION_STEP) - .eq(RULE_TYPE) - .invoke('text') - .should('eql', 'Machine Learning'); + cy.get(DEFINITION_STEP).eq(RULE_TYPE).invoke('text').should('eql', 'Machine Learning'); cy.get(DEFINITION_STEP) .eq(ANOMALY_SCORE) .invoke('text') @@ -180,18 +153,9 @@ describe('Signal detection rules, machine learning', () => { .invoke('text') .should('eql', machineLearningRule.machineLearningJob); - cy.get(DEFINITION_STEP) - .eq(DEFINITION_TIMELINE) - .invoke('text') - .should('eql', 'None'); + cy.get(DEFINITION_STEP).eq(DEFINITION_TIMELINE).invoke('text').should('eql', 'None'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_RUNS) - .invoke('text') - .should('eql', '5m'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_LOOPBACK) - .invoke('text') - .should('eql', '1m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_RUNS).invoke('text').should('eql', '5m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_LOOPBACK).invoke('text').should('eql', '1m'); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts index 866302e81e1a0..005e24dad2a16 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts @@ -56,14 +56,12 @@ describe('Signal detection rules, prebuilt rules', () => { loadPrebuiltDetectionRules(); waitForPrebuiltDetectionRulesToBeLoaded(); - cy.get(ELASTIC_RULES_BTN) - .invoke('text') - .should('eql', expectedElasticRulesBtnText); + cy.get(ELASTIC_RULES_BTN).invoke('text').should('eql', expectedElasticRulesBtnText); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); }); @@ -83,14 +81,12 @@ describe('Deleting prebuilt rules', () => { loadPrebuiltDetectionRules(); waitForPrebuiltDetectionRulesToBeLoaded(); - cy.get(ELASTIC_RULES_BTN) - .invoke('text') - .should('eql', expectedElasticRulesBtnText); + cy.get(ELASTIC_RULES_BTN).invoke('text').should('eql', expectedElasticRulesBtnText); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); }); @@ -103,7 +99,7 @@ describe('Deleting prebuilt rules', () => { const numberOfRulesToBeSelected = 2; selectNumberOfRules(numberOfRulesToBeSelected); - cy.get(COLLAPSED_ACTION_BTN).each(collapsedItemActionBtn => { + cy.get(COLLAPSED_ACTION_BTN).each((collapsedItemActionBtn) => { cy.wrap(collapsedItemActionBtn).should('have.attr', 'disabled'); }); }); @@ -120,7 +116,7 @@ describe('Deleting prebuilt rules', () => { cy.get(ELASTIC_RULES_BTN) .invoke('text') .should('eql', `Elastic rules (${expectedNumberOfRulesAfterDeletion})`); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(RELOAD_PREBUILT_RULES_BTN).should('exist'); @@ -136,7 +132,7 @@ describe('Deleting prebuilt rules', () => { changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterRecovering); }); cy.get(ELASTIC_RULES_BTN) @@ -162,7 +158,7 @@ describe('Deleting prebuilt rules', () => { cy.get(ELASTIC_RULES_BTN) .invoke('text') .should('eql', `Elastic rules (${expectedNumberOfRulesAfterDeletion})`); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); @@ -174,7 +170,7 @@ describe('Deleting prebuilt rules', () => { changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterRecovering); }); cy.get(ELASTIC_RULES_BTN) diff --git a/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts b/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts index 08eb3df57c7a0..243886752706d 100644 --- a/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts @@ -44,11 +44,11 @@ describe('timeline data providers', () => { cy.get(TIMELINE_DROPPED_DATA_PROVIDERS) .first() .invoke('text') - .then(dataProviderText => { + .then((dataProviderText) => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() .invoke('text') - .should(hostname => { + .should((hostname) => { expect(dataProviderText).to.eq(`host.name: "${hostname}"AND`); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts b/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts index f738ff792049a..0668b91ca4fc1 100644 --- a/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts @@ -24,7 +24,7 @@ describe('timeline search or filter KQL bar', () => { cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); diff --git a/x-pack/plugins/siem/cypress/integration/url_state.spec.ts b/x-pack/plugins/siem/cypress/integration/url_state.spec.ts index cd60745b19040..5625e1812f696 100644 --- a/x-pack/plugins/siem/cypress/integration/url_state.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/url_state.spec.ts @@ -197,10 +197,7 @@ describe('url state', () => { 'href', "#/link-to/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))" ); - cy.get(HOSTS_NAMES) - .first() - .invoke('text') - .should('eq', 'siem-kibana'); + cy.get(HOSTS_NAMES).first().invoke('text').should('eq', 'siem-kibana'); openFirstHostDetails(); clearSearchBar(); @@ -241,7 +238,7 @@ describe('url state', () => { cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); @@ -252,7 +249,7 @@ describe('url state', () => { cy.wait(5000); cy.url({ timeout: 30000 }).should('match', /\w*-\w*-\w*-\w*-\w*/); - cy.url().then(url => { + cy.url().then((url) => { const matched = url.match(/\w*-\w*-\w*-\w*-\w*/); const newTimelineId = matched && matched.length > 0 ? matched[0] : 'null'; expect(matched).to.have.lengthOf(1); @@ -260,9 +257,7 @@ describe('url state', () => { cy.visit('/app/kibana'); cy.visit(`/app/siem#/overview?timeline\=(id:'${newTimelineId}',isOpen:!t)`); cy.contains('a', 'SIEM'); - cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE).invoke('text').should('not.equal', 'Updating'); cy.get(TIMELINE_TITLE).should('have.attr', 'value', timelineName); }); }); diff --git a/x-pack/plugins/siem/cypress/plugins/index.js b/x-pack/plugins/siem/cypress/plugins/index.js index 01d31b85de463..35e2669f1611a 100644 --- a/x-pack/plugins/siem/cypress/plugins/index.js +++ b/x-pack/plugins/siem/cypress/plugins/index.js @@ -20,7 +20,7 @@ // eslint-disable-next-line import/no-extraneous-dependencies const wp = require('@cypress/webpack-preprocessor'); -module.exports = on => { +module.exports = (on) => { const options = { webpackOptions: { resolve: { diff --git a/x-pack/plugins/siem/cypress/support/commands.js b/x-pack/plugins/siem/cypress/support/commands.js index e697dbce0f249..4bc62da22aca7 100644 --- a/x-pack/plugins/siem/cypress/support/commands.js +++ b/x-pack/plugins/siem/cypress/support/commands.js @@ -30,8 +30,8 @@ // -- This is will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) -Cypress.Commands.add('stubSIEMapi', function(dataFileName) { - cy.on('window:before:load', win => { +Cypress.Commands.add('stubSIEMapi', function (dataFileName) { + cy.on('window:before:load', (win) => { // @ts-ignore no null, this is a temp hack see issue above win.fetch = null; }); diff --git a/x-pack/plugins/siem/cypress/support/index.js b/x-pack/plugins/siem/cypress/support/index.js index 672acfd41a264..42abecd4b0bad 100644 --- a/x-pack/plugins/siem/cypress/support/index.js +++ b/x-pack/plugins/siem/cypress/support/index.js @@ -26,13 +26,13 @@ Cypress.Cookies.defaults({ whitelist: 'sid', }); -Cypress.on('uncaught:exception', err => { +Cypress.on('uncaught:exception', (err) => { if (err.message.includes('ResizeObserver loop limit exceeded')) { return false; } }); -Cypress.on('window:before:load', win => { +Cypress.on('window:before:load', (win) => { win.fetch = null; win.Blob = null; }); diff --git a/x-pack/plugins/siem/cypress/tasks/configure_cases.ts b/x-pack/plugins/siem/cypress/tasks/configure_cases.ts index 6ba9e875c7cb0..8ff8fbf4b0cb7 100644 --- a/x-pack/plugins/siem/cypress/tasks/configure_cases.ts +++ b/x-pack/plugins/siem/cypress/tasks/configure_cases.ts @@ -29,7 +29,7 @@ export const addServiceNowConnector = (connector: Connector) => { }; export const openAddNewConnectorOption = () => { - cy.get(MAIN_PAGE).then($page => { + cy.get(MAIN_PAGE).then(($page) => { if ($page.find(SERVICE_NOW_CONNECTOR_CARD).length !== 1) { cy.wait(1000); cy.get(CONNECTORS_DROPDOWN).click({ force: true }); @@ -42,7 +42,7 @@ export const selectLastConnectorCreated = () => { cy.get(CONNECTORS_DROPDOWN).click({ force: true }); cy.get('@createConnector') .its('response') - .then(response => { + .then((response) => { cy.get(CONNECTOR(response.body.id)).click(); }); }; diff --git a/x-pack/plugins/siem/cypress/tasks/create_new_case.ts b/x-pack/plugins/siem/cypress/tasks/create_new_case.ts index 491fdd84e9b38..2dac1065e23eb 100644 --- a/x-pack/plugins/siem/cypress/tasks/create_new_case.ts +++ b/x-pack/plugins/siem/cypress/tasks/create_new_case.ts @@ -24,7 +24,7 @@ export const backToCases = () => { export const createNewCase = (newCase: TestCase) => { cy.get(TITLE_INPUT).type(newCase.name, { force: true }); - newCase.tags.forEach(tag => { + newCase.tags.forEach((tag) => { cy.get(TAGS_INPUT).type(`${tag}{enter}`, { force: true }); }); cy.get(DESCRIPTION_INPUT).type(`${newCase.description} `, { force: true }); @@ -33,9 +33,7 @@ export const createNewCase = (newCase: TestCase) => { cy.get(TIMELINE_SEARCHBOX).type(`${newCase.timeline.title}{enter}`); cy.get(TIMELINE).should('be.visible'); cy.wait(300); - cy.get(TIMELINE) - .eq(1) - .click({ force: true }); + cy.get(TIMELINE).eq(1).click({ force: true }); cy.get(SUBMIT_BTN).click({ force: true }); cy.get(LOADING_SPINNER).should('exist'); diff --git a/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts b/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts index a20ad372a689c..6324b42f3783a 100644 --- a/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts +++ b/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts @@ -44,40 +44,30 @@ export const fillAboutRuleAndContinue = (rule: CustomRule | MachineLearningRule) cy.get(SEVERITY_DROPDOWN).click({ force: true }); cy.get(`#${rule.severity.toLowerCase()}`).click(); - cy.get(RISK_INPUT) - .clear({ force: true }) - .type(`${rule.riskScore}`, { force: true }); + cy.get(RISK_INPUT).clear({ force: true }).type(`${rule.riskScore}`, { force: true }); - rule.tags.forEach(tag => { + rule.tags.forEach((tag) => { cy.get(TAGS_INPUT).type(`${tag}{enter}`, { force: true }); }); cy.get(ADVANCED_SETTINGS_BTN).click({ force: true }); rule.referenceUrls.forEach((url, index) => { - cy.get(REFERENCE_URLS_INPUT) - .eq(index) - .type(url, { force: true }); + cy.get(REFERENCE_URLS_INPUT).eq(index).type(url, { force: true }); cy.get(ADD_REFERENCE_URL_BTN).click({ force: true }); }); rule.falsePositivesExamples.forEach((falsePositive, index) => { - cy.get(FALSE_POSITIVES_INPUT) - .eq(index) - .type(falsePositive, { force: true }); + cy.get(FALSE_POSITIVES_INPUT).eq(index).type(falsePositive, { force: true }); cy.get(ADD_FALSE_POSITIVE_BTN).click({ force: true }); }); rule.mitre.forEach((mitre, index) => { - cy.get(MITRE_TACTIC_DROPDOWN) - .eq(index) - .click({ force: true }); + cy.get(MITRE_TACTIC_DROPDOWN).eq(index).click({ force: true }); cy.contains(MITRE_TACTIC, mitre.tactic).click(); - mitre.techniques.forEach(technique => { - cy.get(MITRE_TECHNIQUES_INPUT) - .eq(index) - .type(`${technique}{enter}`, { force: true }); + mitre.techniques.forEach((technique) => { + cy.get(MITRE_TECHNIQUES_INPUT).eq(index).type(`${technique}{enter}`, { force: true }); }); cy.get(MITRE_BTN).click({ force: true }); @@ -85,17 +75,13 @@ export const fillAboutRuleAndContinue = (rule: CustomRule | MachineLearningRule) cy.get(INVESTIGATION_NOTES_TEXTAREA).type(rule.note, { force: true }); - cy.get(ABOUT_CONTINUE_BTN) - .should('exist') - .click({ force: true }); + cy.get(ABOUT_CONTINUE_BTN).should('exist').click({ force: true }); }; export const fillDefineCustomRuleAndContinue = (rule: CustomRule) => { cy.get(CUSTOM_QUERY_INPUT).type(rule.customQuery); cy.get(CUSTOM_QUERY_INPUT).should('have.attr', 'value', rule.customQuery); - cy.get(DEFINE_CONTINUE_BUTTON) - .should('exist') - .click({ force: true }); + cy.get(DEFINE_CONTINUE_BUTTON).should('exist').click({ force: true }); cy.get(CUSTOM_QUERY_INPUT).should('not.exist'); }; @@ -106,9 +92,7 @@ export const fillDefineMachineLearningRuleAndContinue = (rule: MachineLearningRu cy.get(ANOMALY_THRESHOLD_INPUT).type(`{selectall}${machineLearningRule.anomalyScoreThreshold}`, { force: true, }); - cy.get(DEFINE_CONTINUE_BUTTON) - .should('exist') - .click({ force: true }); + cy.get(DEFINE_CONTINUE_BUTTON).should('exist').click({ force: true }); cy.get(MACHINE_LEARNING_DROPDOWN).should('not.exist'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/date_picker.ts b/x-pack/plugins/siem/cypress/tasks/date_picker.ts index 0d778b737380b..809498d25c5d8 100644 --- a/x-pack/plugins/siem/cypress/tasks/date_picker.ts +++ b/x-pack/plugins/siem/cypress/tasks/date_picker.ts @@ -18,36 +18,26 @@ import { export const setEndDate = (date: string) => { cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT) - .clear() - .type(date); + cy.get(DATE_PICKER_ABSOLUTE_INPUT).clear().type(date); }; export const setStartDate = (date: string) => { cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT) - .clear() - .type(date); + cy.get(DATE_PICKER_ABSOLUTE_INPUT).clear().type(date); }; export const setTimelineEndDate = (date: string) => { cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON_TIMELINE).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); cy.get(DATE_PICKER_ABSOLUTE_INPUT).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT).then($el => { + cy.get(DATE_PICKER_ABSOLUTE_INPUT).then(($el) => { // @ts-ignore if (Cypress.dom.isAttached($el)) { cy.wrap($el).click({ force: true }); @@ -61,12 +51,10 @@ export const setTimelineStartDate = (date: string) => { force: true, }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); cy.get(DATE_PICKER_ABSOLUTE_INPUT).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT).then($el => { + cy.get(DATE_PICKER_ABSOLUTE_INPUT).then(($el) => { // @ts-ignore if (Cypress.dom.isAttached($el)) { cy.wrap($el).click({ force: true }); diff --git a/x-pack/plugins/siem/cypress/tasks/detections.ts b/x-pack/plugins/siem/cypress/tasks/detections.ts index c30a178eab489..9461dd5ff99cf 100644 --- a/x-pack/plugins/siem/cypress/tasks/detections.ts +++ b/x-pack/plugins/siem/cypress/tasks/detections.ts @@ -19,9 +19,7 @@ import { import { REFRESH_BUTTON } from '../screens/siem_header'; export const closeFirstSignal = () => { - cy.get(OPEN_CLOSE_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(OPEN_CLOSE_SIGNAL_BTN).first().click({ force: true }); }; export const closeSignals = () => { @@ -29,9 +27,7 @@ export const closeSignals = () => { }; export const expandFirstSignal = () => { - cy.get(EXPAND_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(EXPAND_SIGNAL_BTN).first().click({ force: true }); }; export const goToClosedSignals = () => { @@ -39,9 +35,7 @@ export const goToClosedSignals = () => { }; export const goToManageSignalDetectionRules = () => { - cy.get(MANAGE_SIGNAL_DETECTION_RULES_BTN) - .should('exist') - .click({ force: true }); + cy.get(MANAGE_SIGNAL_DETECTION_RULES_BTN).should('exist').click({ force: true }); }; export const goToOpenedSignals = () => { @@ -49,9 +43,7 @@ export const goToOpenedSignals = () => { }; export const openFirstSignal = () => { - cy.get(OPEN_CLOSE_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(OPEN_CLOSE_SIGNAL_BTN).first().click({ force: true }); }; export const openSignals = () => { @@ -60,27 +52,21 @@ export const openSignals = () => { export const selectNumberOfSignals = (numberOfSignals: number) => { for (let i = 0; i < numberOfSignals; i++) { - cy.get(SIGNAL_CHECKBOX) - .eq(i) - .click({ force: true }); + cy.get(SIGNAL_CHECKBOX).eq(i).click({ force: true }); } }; export const investigateFirstSignalInTimeline = () => { - cy.get(SEND_SIGNAL_TO_TIMELINE_BTN) - .first() - .click({ force: true }); + cy.get(SEND_SIGNAL_TO_TIMELINE_BTN).first().click({ force: true }); }; export const waitForSignals = () => { - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; export const waitForSignalsIndexToBeCreated = () => { cy.request({ url: '/api/detection_engine/index', retryOnStatusCodeFailure: true }).then( - response => { + (response) => { if (response.status !== 200) { cy.wait(7500); } diff --git a/x-pack/plugins/siem/cypress/tasks/fields_browser.ts b/x-pack/plugins/siem/cypress/tasks/fields_browser.ts index e1d2f24da424c..eb709d2dd5778 100644 --- a/x-pack/plugins/siem/cypress/tasks/fields_browser.ts +++ b/x-pack/plugins/siem/cypress/tasks/fields_browser.ts @@ -30,9 +30,9 @@ export const addsHostGeoContinentNameToTimeline = () => { export const addsHostGeoCountryNameToTimelineDraggingIt = () => { cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).should('exist'); - cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).then(field => drag(field)); + cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).then((field) => drag(field)); - cy.get(FIELDS_BROWSER_HEADER_DROP_AREA).then(headersDropArea => drop(headersDropArea)); + cy.get(FIELDS_BROWSER_HEADER_DROP_AREA).then((headersDropArea) => drop(headersDropArea)); }; export const clearFieldsBrowser = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts b/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts index 312df96df1ddf..f9f902c3de8c7 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts @@ -12,16 +12,16 @@ import { drag, dragWithoutDrop, drop } from '../../tasks/common'; export const dragAndDropFirstHostToTimeline = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(firstHost => drag(firstHost)); - cy.get(TIMELINE_DATA_PROVIDERS).then(dataProvidersDropArea => drop(dataProvidersDropArea)); + .then((firstHost) => drag(firstHost)); + cy.get(TIMELINE_DATA_PROVIDERS).then((dataProvidersDropArea) => drop(dataProvidersDropArea)); }; export const dragFirstHostToEmptyTimelineDataProviders = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(host => drag(host)); + .then((host) => drag(host)); - cy.get(TIMELINE_DATA_PROVIDERS_EMPTY).then(dataProvidersDropArea => + cy.get(TIMELINE_DATA_PROVIDERS_EMPTY).then((dataProvidersDropArea) => dragWithoutDrop(dataProvidersDropArea) ); }; @@ -29,12 +29,10 @@ export const dragFirstHostToEmptyTimelineDataProviders = () => { export const dragFirstHostToTimeline = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(host => drag(host)); + .then((host) => drag(host)); }; export const openFirstHostDetails = () => { - cy.get(HOSTS_NAMES) - .first() - .click({ force: true }); + cy.get(HOSTS_NAMES).first().click({ force: true }); }; export const waitForAllHostsToBeLoaded = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts b/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts index ce3767a340376..7ba7f227964ab 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts @@ -9,7 +9,5 @@ import { REFRESH_BUTTON } from '../../screens/siem_header'; export const waitForAuthenticationsToBeLoaded = () => { cy.get(AUTHENTICATIONS_TABLE).should('exist'); - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/events.ts b/x-pack/plugins/siem/cypress/tasks/hosts/events.ts index de0c99bd31dff..dff58b4b0e9ea 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/events.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/events.ts @@ -39,9 +39,7 @@ export const loadMoreEvents = () => { export const openEventsViewerFieldsBrowser = () => { cy.get(EVENTS_VIEWER_FIELDS_BUTTON).click({ force: true }); - cy.get(SERVER_SIDE_EVENT_COUNT) - .invoke('text') - .should('not.equal', '0'); + cy.get(SERVER_SIDE_EVENT_COUNT).invoke('text').should('not.equal', '0'); cy.get(FIELDS_BROWSER_CONTAINER).should('exist'); }; @@ -58,8 +56,5 @@ export const resetFields = () => { }; export const waitsForEventsToBeLoaded = () => { - cy.get(SERVER_SIDE_EVENT_COUNT) - .should('exist') - .invoke('text') - .should('not.equal', '0'); + cy.get(SERVER_SIDE_EVENT_COUNT).should('exist').invoke('text').should('not.equal', '0'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts b/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts index a28a7df07c3f8..c86b169d60a13 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts @@ -9,7 +9,5 @@ import { REFRESH_BUTTON } from '../../screens/siem_header'; export const waitForUncommonProcessesToBeLoaded = () => { cy.get(UNCOMMON_PROCESSES_TABLE).should('exist'); - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/login.ts b/x-pack/plugins/siem/cypress/tasks/login.ts index 1bbf41d05db00..13580037b3d7c 100644 --- a/x-pack/plugins/siem/cypress/tasks/login.ts +++ b/x-pack/plugins/siem/cypress/tasks/login.ts @@ -98,7 +98,7 @@ const loginViaConfig = () => { ); // read the login details from `kibana.dev.yaml` - cy.readFile(KIBANA_DEV_YML_PATH).then(kibanaDevYml => { + cy.readFile(KIBANA_DEV_YML_PATH).then((kibanaDevYml) => { const config = yaml.safeLoad(kibanaDevYml); // programmatically authenticate without interacting with the Kibana login page diff --git a/x-pack/plugins/siem/cypress/tasks/overview.ts b/x-pack/plugins/siem/cypress/tasks/overview.ts index 0ca4059a90097..38c3c00fbc365 100644 --- a/x-pack/plugins/siem/cypress/tasks/overview.ts +++ b/x-pack/plugins/siem/cypress/tasks/overview.ts @@ -7,9 +7,7 @@ import { OVERVIEW_HOST_STATS, OVERVIEW_NETWORK_STATS } from '../screens/overview'; export const expand = (statType: string) => { - cy.get(statType) - .find('button') - .invoke('click'); + cy.get(statType).find('button').invoke('click'); }; export const expandHostStats = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/siem_header.ts b/x-pack/plugins/siem/cypress/tasks/siem_header.ts index 4c43948445c58..2cc9199a42bbb 100644 --- a/x-pack/plugins/siem/cypress/tasks/siem_header.ts +++ b/x-pack/plugins/siem/cypress/tasks/siem_header.ts @@ -7,9 +7,7 @@ import { KQL_INPUT, REFRESH_BUTTON } from '../screens/siem_header'; export const clearSearchBar = () => { - cy.get(KQL_INPUT) - .clear() - .type('{enter}'); + cy.get(KQL_INPUT).clear().type('{enter}'); }; export const kqlSearch = (search: string) => { @@ -21,8 +19,5 @@ export const navigateFromHeaderTo = (page: string) => { }; export const refreshPage = () => { - cy.get(REFRESH_BUTTON) - .click({ force: true }) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).click({ force: true }).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/siem_main.ts b/x-pack/plugins/siem/cypress/tasks/siem_main.ts index 2bdc62ecbdc03..eece7edcb2b44 100644 --- a/x-pack/plugins/siem/cypress/tasks/siem_main.ts +++ b/x-pack/plugins/siem/cypress/tasks/siem_main.ts @@ -11,7 +11,7 @@ export const openTimeline = () => { }; export const openTimelineIfClosed = () => { - cy.get(MAIN_PAGE).then($page => { + cy.get(MAIN_PAGE).then(($page) => { if ($page.find(TIMELINE_TOGGLE_BUTTON).length === 1) { openTimeline(); } diff --git a/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts b/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts index 5a4d71de9e851..6b2c4644a95d1 100644 --- a/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts +++ b/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts @@ -27,9 +27,7 @@ import { } from '../screens/signal_detection_rules'; export const activateRule = (rulePosition: number) => { - cy.get(RULE_SWITCH) - .eq(rulePosition) - .click({ force: true }); + cy.get(RULE_SWITCH).eq(rulePosition).click({ force: true }); }; export const changeToThreeHundredRowsPerPage = () => { @@ -38,9 +36,7 @@ export const changeToThreeHundredRowsPerPage = () => { }; export const deleteFirstRule = () => { - cy.get(COLLAPSED_ACTION_BTN) - .first() - .click({ force: true }); + cy.get(COLLAPSED_ACTION_BTN).first().click({ force: true }); cy.get(DELETE_RULE_ACTION_BTN).click(); }; @@ -50,9 +46,7 @@ export const deleteSelectedRules = () => { }; export const exportFirstRule = () => { - cy.get(COLLAPSED_ACTION_BTN) - .first() - .click({ force: true }); + cy.get(COLLAPSED_ACTION_BTN).first().click({ force: true }); cy.get(EXPORT_ACTION_BTN).click(); cy.get(EXPORT_ACTION_BTN).should('not.exist'); }; @@ -72,9 +66,7 @@ export const goToRuleDetails = () => { }; export const loadPrebuiltDetectionRules = () => { - cy.get(LOAD_PREBUILT_RULES_BTN) - .should('exist') - .click({ force: true }); + cy.get(LOAD_PREBUILT_RULES_BTN).should('exist').click({ force: true }); }; export const reloadDeletedRules = () => { @@ -83,9 +75,7 @@ export const reloadDeletedRules = () => { export const selectNumberOfRules = (numberOfRules: number) => { for (let i = 0; i < numberOfRules; i++) { - cy.get(RULE_CHECKBOX) - .eq(i) - .click({ force: true }); + cy.get(RULE_CHECKBOX).eq(i).click({ force: true }); } }; diff --git a/x-pack/plugins/siem/cypress/tasks/timeline.ts b/x-pack/plugins/siem/cypress/tasks/timeline.ts index 7873a76bf99f1..38da611428b2e 100644 --- a/x-pack/plugins/siem/cypress/tasks/timeline.ts +++ b/x-pack/plugins/siem/cypress/tasks/timeline.ts @@ -29,10 +29,7 @@ export const hostExistsQuery = 'host.name: *'; export const addDescriptionToTimeline = (description: string) => { cy.get(TIMELINE_DESCRIPTION).type(`${description}{enter}`); - cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE) - .click() - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE).click().invoke('text').should('not.equal', 'Updating'); }; export const addNameToTimeline = (name: string) => { @@ -63,9 +60,7 @@ export const executeTimelineKQL = (query: string) => { }; export const expandFirstTimelineEventDetails = () => { - cy.get(TOGGLE_TIMELINE_EXPAND_EVENT) - .first() - .click({ force: true }); + cy.get(TOGGLE_TIMELINE_EXPAND_EVENT).first().click({ force: true }); }; export const openTimelineFieldsBrowser = () => { @@ -85,7 +80,7 @@ export const populateTimeline = () => { executeTimelineKQL(hostExistsQuery); cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); @@ -100,9 +95,9 @@ export const uncheckTimestampToggleField = () => { export const dragAndDropIdToggleFieldToTimeline = () => { cy.get(ID_HEADER_FIELD).should('not.exist'); - cy.get(ID_FIELD).then(field => drag(field)); + cy.get(ID_FIELD).then((field) => drag(field)); - cy.get(`[data-test-subj="timeline"] [data-test-subj="headers-group"]`).then(headersDropArea => + cy.get(`[data-test-subj="timeline"] [data-test-subj="headers-group"]`).then((headersDropArea) => drop(headersDropArea) ); }; diff --git a/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx b/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx index 42a5afb600fba..a3e76557a6ff5 100644 --- a/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx +++ b/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { HeaderPage, HeaderPageProps } from '../../../common/components/header_page'; import * as i18n from './translations'; -const DetectionEngineHeaderPageComponent: React.FC = props => ( +const DetectionEngineHeaderPageComponent: React.FC = (props) => ( ); diff --git a/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx b/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx index d6c18078f8acd..c8eb6f69c95ba 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx @@ -158,7 +158,7 @@ export const AddItem = ({ setShowValidation(true)} - onChange={e => updateItem(e, index)} + onChange={(e) => updateItem(e, index)} fullWidth {...euiFieldProps} /> diff --git a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx index 70de3d2a72dcc..e39ee38d71da7 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx @@ -314,16 +314,10 @@ describe('helpers', () => { expect(result[0].title).toEqual('Test label'); expect(wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]')).toHaveLength(2); expect( - wrapper - .find('[data-test-subj="stringArrayDescriptionBadgeItem"]') - .first() - .text() + wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]').first().text() ).toEqual('tag1'); expect( - wrapper - .find('[data-test-subj="stringArrayDescriptionBadgeItem"]') - .at(1) - .text() + wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]').at(1).text() ).toEqual('tag2'); }); }); @@ -353,16 +347,10 @@ describe('helpers', () => { expect(result[0].title).toEqual('Test label'); expect(wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]')).toHaveLength(2); expect( - wrapper - .find('[data-test-subj="urlsDescriptionReferenceLinkItem"]') - .first() - .text() + wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]').first().text() ).toEqual('www.test.com'); expect( - wrapper - .find('[data-test-subj="urlsDescriptionReferenceLinkItem"]') - .at(1) - .text() + wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]').at(1).text() ).toEqual('www.test2.com'); }); }); diff --git a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx index ad3ed538c875b..091065eedfc22 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx @@ -121,7 +121,7 @@ export const buildThreatDescription = ({ label, threat }: BuildThreatDescription description: ( {threat.map((singleThreat, index) => { - const tactic = tacticsOptions.find(t => t.id === singleThreat.tactic.id); + const tactic = tacticsOptions.find((t) => t.id === singleThreat.tactic.id); return ( - {singleThreat.technique.map(technique => { - const myTechnique = techniquesOptions.find(t => t.id === technique.id); + {singleThreat.technique.map((technique) => { + const myTechnique = techniquesOptions.find((t) => t.id === technique.id); return (